diff --git a/DownKyi.Core/BiliApi/Bangumi/BangumiInfo.cs b/DownKyi.Core/BiliApi/Bangumi/BangumiInfo.cs index 65d9a86..aea848c 100644 --- a/DownKyi.Core/BiliApi/Bangumi/BangumiInfo.cs +++ b/DownKyi.Core/BiliApi/Bangumi/BangumiInfo.cs @@ -14,9 +14,9 @@ public static class BangumiInfo /// public static BangumiMedia BangumiMediaInfo(long mediaId) { - string url = $"https://api.bilibili.com/pgc/review/user?media_id={mediaId}"; - string referer = "https://www.bilibili.com"; - string response = WebClient.RequestWeb(url, referer); + var url = $"https://api.bilibili.com/pgc/review/user?media_id={mediaId}"; + const string referer = "https://www.bilibili.com"; + var response = WebClient.RequestWeb(url, referer); try { @@ -25,10 +25,8 @@ public static class BangumiInfo { return media.Result.Media; } - else - { - return null; - } + + return null; } catch (Exception e) { @@ -44,10 +42,10 @@ public static class BangumiInfo /// /// /// - public static BangumiSeason BangumiSeasonInfo(long seasonId = -1, long episodeId = -1) + public static BangumiSeason? BangumiSeasonInfo(long seasonId = -1, long episodeId = -1) { - string baseUrl = "https://api.bilibili.com/pgc/view/web/season"; - string referer = "https://www.bilibili.com"; + const string baseUrl = "https://api.bilibili.com/pgc/view/web/season"; + const string referer = "https://www.bilibili.com"; string url; if (seasonId > -1) { @@ -62,19 +60,12 @@ public static class BangumiInfo return null; } - string response = WebClient.RequestWeb(url, referer); + var response = WebClient.RequestWeb(url, referer); try { var bangumiSeason = JsonConvert.DeserializeObject(response); - if (bangumiSeason != null) - { - return bangumiSeason.Result; - } - else - { - return null; - } + return bangumiSeason?.Result; } catch (Exception e) { diff --git a/DownKyi.Core/BiliApi/Bangumi/BangumiType.cs b/DownKyi.Core/BiliApi/Bangumi/BangumiType.cs index 99d233e..797f316 100644 --- a/DownKyi.Core/BiliApi/Bangumi/BangumiType.cs +++ b/DownKyi.Core/BiliApi/Bangumi/BangumiType.cs @@ -2,7 +2,7 @@ public static class BangumiType { - public static Dictionary Type = new Dictionary() + public static readonly Dictionary Type = new() { { 1, "Anime" }, { 2, "Movie" }, @@ -16,7 +16,7 @@ public static class BangumiType { 10, "Unknown" } }; - public static Dictionary TypeId = new Dictionary() + public static readonly Dictionary TypeId = new() { { 1, 13 }, { 2, 23 }, diff --git a/DownKyi.Core/BiliApi/BiliUtils/BvId.cs b/DownKyi.Core/BiliApi/BiliUtils/BvId.cs index bf63532..5cbaa88 100644 --- a/DownKyi.Core/BiliApi/BiliUtils/BvId.cs +++ b/DownKyi.Core/BiliApi/BiliUtils/BvId.cs @@ -2,13 +2,13 @@ public static class BvId { - private const string tableStr = "fZodR9XQDSUm21yCkr6zBqiveYah8bt4xsWpHnJE7jL5VG3guMTKNPAwcF"; //码表 - private static readonly char[] table = tableStr.ToCharArray(); + private const string TableStr = "fZodR9XQDSUm21yCkr6zBqiveYah8bt4xsWpHnJE7jL5VG3guMTKNPAwcF"; //码表 + private static readonly char[] Table = TableStr.ToCharArray(); - private static readonly char[] tr = new char[124]; //反查码表 + private static readonly char[] Tr = new char[124]; //反查码表 private const ulong Xor = 177451812; //固定异或值 - private const ulong add = 8728348608; //固定加法值 - private static readonly int[] s = { 11, 10, 3, 8, 4, 6 }; //位置编码表 + private const ulong Add = 8728348608; //固定加法值 + private static readonly int[] S = { 11, 10, 3, 8, 4, 6 }; //位置编码表 static BvId() { @@ -18,8 +18,8 @@ public static class BvId //初始化反查码表 private static void Tr_init() { - for (int i = 0; i < 58; i++) - tr[table[i]] = (char)i; + for (var i = 0; i < 58; i++) + Tr[Table[i]] = (char)i; } /// @@ -29,13 +29,13 @@ public static class BvId /// public static ulong Bv2Av(string bvid) { - char[] bv = bvid.ToCharArray(); + var bv = bvid.ToCharArray(); ulong r = 0; ulong av; - for (int i = 0; i < 6; i++) - r += tr[bv[s[i]]] * (ulong)Math.Pow(58, i); - av = (r - add) ^ Xor; + for (var i = 0; i < 6; i++) + r += Tr[bv[S[i]]] * (ulong)Math.Pow(58, i); + av = (r - Add) ^ Xor; return av; } @@ -47,13 +47,13 @@ public static class BvId public static string Av2Bv(ulong av) { //编码结果 - string res = "BV1 4 1 7 "; - char[] result = res.ToCharArray(); + const string res = "BV1 4 1 7 "; + var result = res.ToCharArray(); - av = (av ^ Xor) + add; - for (int i = 0; i < 6; i++) - result[s[i]] = table[av / (ulong)Math.Pow(58, i) % 58]; - string bv = new string(result); + av = (av ^ Xor) + Add; + for (var i = 0; i < 6; i++) + result[S[i]] = Table[av / (ulong)Math.Pow(58, i) % 58]; + var bv = new string(result); return bv; } } \ No newline at end of file diff --git a/DownKyi.Core/BiliApi/BiliUtils/DanmakuSender.cs b/DownKyi.Core/BiliApi/BiliUtils/DanmakuSender.cs index 0ede811..d873019 100644 --- a/DownKyi.Core/BiliApi/BiliUtils/DanmakuSender.cs +++ b/DownKyi.Core/BiliApi/BiliUtils/DanmakuSender.cs @@ -2,8 +2,8 @@ public static class DanmakuSender { - private const uint CRCPOLYNOMIAL = 0xEDB88320; - private static readonly uint[] crctable = new uint[256]; + private const uint Crcpolynomial = 0xEDB88320; + private static readonly uint[] Crctable = new uint[256]; static DanmakuSender() { @@ -12,15 +12,15 @@ public static class DanmakuSender private static void CreateTable() { - for (int i = 0; i < 256; i++) + for (var i = 0; i < 256; i++) { - uint crcreg = (uint)i; + var crcreg = (uint)i; - for (int j = 0; j < 8; j++) + for (var j = 0; j < 8; j++) { if ((crcreg & 1) != 0) { - crcreg = CRCPOLYNOMIAL ^ (crcreg >> 1); + crcreg = Crcpolynomial ^ (crcreg >> 1); } else { @@ -28,17 +28,16 @@ public static class DanmakuSender } } - crctable[i] = crcreg; + Crctable[i] = crcreg; } } private static uint Crc32(string userId) { - uint crcstart = 0xFFFFFFFF; - for (int i = 0; i < userId.Length; i++) + var crcstart = 0xFFFFFFFF; + foreach (var index in userId.Select(t => (uint)(crcstart ^ (int)t) & 255)) { - uint index = (uint)(crcstart ^ (int)userId[i]) & 255; - crcstart = (crcstart >> 8) ^ crctable[index]; + crcstart = (crcstart >> 8) ^ Crctable[index]; } return crcstart; @@ -47,11 +46,11 @@ public static class DanmakuSender private static uint Crc32LastIndex(string userId) { uint index = 0; - uint crcstart = 0xFFFFFFFF; - for (int i = 0; i < userId.Length; i++) + var crcstart = 0xFFFFFFFF; + foreach (var t in userId) { - index = (uint)((crcstart ^ (int)userId[i]) & 255); - crcstart = (crcstart >> 8) ^ crctable[index]; + index = (uint)((crcstart ^ (int)t) & 255); + crcstart = (crcstart >> 8) ^ Crctable[index]; } return index; @@ -59,9 +58,9 @@ public static class DanmakuSender private static int GetCrcIndex(long t) { - for (int i = 0; i < 256; i++) + for (var i = 0; i < 256; i++) { - if ((crctable[i] >> 24) == t) + if ((Crctable[i] >> 24) == t) { return i; } @@ -72,9 +71,9 @@ public static class DanmakuSender private static object[] DeepCheck(int i, int[] index) { - object[] resultArray = new object[2]; + var resultArray = new object[2]; - string result = ""; + var result = ""; uint tc; // = 0x00; var hashcode = Crc32(i.ToString()); tc = (uint)(hashcode & 0xff ^ index[2]); @@ -86,7 +85,7 @@ public static class DanmakuSender } result += (tc - 48).ToString(); - hashcode = crctable[index[2]] ^ (hashcode >> 8); + hashcode = Crctable[index[2]] ^ (hashcode >> 8); tc = (uint)(hashcode & 0xff ^ index[1]); if (!(tc <= 57 && tc >= 48)) @@ -96,7 +95,7 @@ public static class DanmakuSender } result += (tc - 48).ToString(); - hashcode = crctable[index[1]] ^ (hashcode >> 8); + hashcode = Crctable[index[1]] ^ (hashcode >> 8); tc = (uint)(hashcode & 0xff ^ index[0]); if (!(tc <= 57 && tc >= 48)) @@ -120,38 +119,31 @@ public static class DanmakuSender /// public static string FindDanmakuSender(string userId) { - object[] deepCheckData = new object[2]; + var deepCheckData = new object[2]; - int[] index = new int[4]; - uint ht = (uint)Convert.ToInt32($"0x{userId}", 16); + var index = new int[4]; + var ht = (uint)Convert.ToInt32($"0x{userId}", 16); ht ^= 0xffffffff; int i; for (i = 3; i > -1; i--) { index[3 - i] = GetCrcIndex(ht >> (i * 8)); - uint snum = crctable[index[3 - i]]; + var snum = Crctable[index[3 - i]]; ht ^= snum >> ((3 - i) * 8); } for (i = 0; i < 100000000; i++) { - uint lastindex = Crc32LastIndex(i.ToString()); - if (lastindex == index[3]) + var lastindex = Crc32LastIndex(i.ToString()); + if (lastindex != index[3]) continue; + deepCheckData = DeepCheck(i, index); + if ((int)deepCheckData[0] != 0) { - deepCheckData = DeepCheck(i, index); - if ((int)deepCheckData[0] != 0) - { - break; - } + break; } } - if (i == 100000000) - { - return "-1"; - } - - return $"{i}{deepCheckData[1]}"; + return i == 100000000 ? "-1" : $"{i}{deepCheckData[1]}"; } } \ No newline at end of file diff --git a/DownKyi.Core/BiliApi/BiliUtils/ParseEntrance.cs b/DownKyi.Core/BiliApi/BiliUtils/ParseEntrance.cs index 279572e..c2aaab9 100644 --- a/DownKyi.Core/BiliApi/BiliUtils/ParseEntrance.cs +++ b/DownKyi.Core/BiliApi/BiliUtils/ParseEntrance.cs @@ -140,7 +140,7 @@ public static class ParseEntrance /// public static bool IsBangumiSeasonUrl(string input) { - string id = GetBangumiId(input); + var id = GetBangumiId(input); return IsBangumiSeasonId(id); } @@ -155,14 +155,13 @@ public static class ParseEntrance { return Number.GetInt(input.Remove(0, 2)); } - else if (IsBangumiSeasonUrl(input)) + + if (IsBangumiSeasonUrl(input)) { return Number.GetInt(GetBangumiId(input).Remove(0, 2)); } - else - { - return -1; - } + + return -1; } /// @@ -182,7 +181,7 @@ public static class ParseEntrance /// public static bool IsBangumiEpisodeUrl(string input) { - string id = GetBangumiId(input); + var id = GetBangumiId(input); return IsBangumiEpisodeId(id); } @@ -197,14 +196,13 @@ public static class ParseEntrance { return Number.GetInt(input.Remove(0, 2)); } - else if (IsBangumiEpisodeUrl(input)) + + if (IsBangumiEpisodeUrl(input)) { return Number.GetInt(GetBangumiId(input).Remove(0, 2)); } - else - { - return -1; - } + + return -1; } /// @@ -224,7 +222,7 @@ public static class ParseEntrance /// public static bool IsBangumiMediaUrl(string input) { - string id = GetBangumiId(input); + var id = GetBangumiId(input); return IsBangumiMediaId(id); } @@ -239,14 +237,13 @@ public static class ParseEntrance { return Number.GetInt(input.Remove(0, 2)); } - else if (IsBangumiMediaUrl(input)) + + if (IsBangumiMediaUrl(input)) { return Number.GetInt(GetBangumiId(input).Remove(0, 2)); } - else - { - return -1; - } + + return -1; } #endregion @@ -397,14 +394,13 @@ public static class ParseEntrance { return Regex.IsMatch(input.Remove(0, 4), @"^\d+$"); } - else if (input.ToLower().StartsWith("uid")) + + if (input.ToLower().StartsWith("uid")) { return Regex.IsMatch(input.Remove(0, 3), @"^\d+$"); } - else - { - return false; - } + + return false; } /// @@ -440,11 +436,13 @@ public static class ParseEntrance { return Number.GetInt(input.Remove(0, 4)); } - else if (input.ToLower().StartsWith("uid")) + + if (input.ToLower().StartsWith("uid")) { return Number.GetInt(input.Remove(0, 3)); } - else if (IsUserUrl(input)) + + if (IsUserUrl(input)) { var url = EnableHttps(input); url = DeleteUrlParam(url); @@ -453,15 +451,11 @@ public static class ParseEntrance { return long.Parse(match.Value); } - else - { - return -1; - } - } - else - { + return -1; } + + return -1; } #endregion @@ -520,12 +514,7 @@ public static class ParseEntrance private static string GetBangumiId(string input) { var id = GetId(input, BangumiUrl); - if (id != "") - { - return id; - } - - return GetId(input, BangumiMediaUrl); + return id != "" ? id : GetId(input, BangumiMediaUrl); } /// @@ -546,12 +535,7 @@ public static class ParseEntrance /// private static bool IsIntId(string input, string prefix) { - if (input.ToLower().StartsWith(prefix)) - { - return Regex.IsMatch(input.Remove(0, 2), @"^\d+$"); - } - - return false; + return input.ToLower().StartsWith(prefix) && Regex.IsMatch(input.Remove(0, 2), @"^\d+$"); } /// @@ -582,11 +566,6 @@ public static class ParseEntrance url = url.Replace(ShortUrl, VideoUrl); } - if (!url.StartsWith(baseUrl)) - { - return ""; - } - - return url.Replace(baseUrl, ""); + return !url.StartsWith(baseUrl) ? "" : url.Replace(baseUrl, ""); } } \ No newline at end of file diff --git a/DownKyi.Core/BiliApi/Cheese/CheeseInfo.cs b/DownKyi.Core/BiliApi/Cheese/CheeseInfo.cs index 1b85dba..cb6ccb8 100644 --- a/DownKyi.Core/BiliApi/Cheese/CheeseInfo.cs +++ b/DownKyi.Core/BiliApi/Cheese/CheeseInfo.cs @@ -13,10 +13,10 @@ public static class CheeseInfo /// /// /// - public static CheeseView CheeseViewInfo(long seasonId = -1, long episodeId = -1) + public static CheeseView? CheeseViewInfo(long seasonId = -1, long episodeId = -1) { - string baseUrl = "https://api.bilibili.com/pugv/view/web/season"; - string referer = "https://www.bilibili.com"; + const string baseUrl = "https://api.bilibili.com/pugv/view/web/season"; + const string referer = "https://www.bilibili.com"; string url; if (seasonId > -1) { @@ -31,19 +31,12 @@ public static class CheeseInfo return null; } - string response = WebClient.RequestWeb(url, referer); + var response = WebClient.RequestWeb(url, referer); try { - CheeseViewOrigin cheese = JsonConvert.DeserializeObject(response); - if (cheese != null) - { - return cheese.Data; - } - else - { - return null; - } + var cheese = JsonConvert.DeserializeObject(response); + return cheese?.Data; } catch (Exception e) { @@ -60,23 +53,16 @@ public static class CheeseInfo /// /// /// - public static CheeseEpisodeList CheeseEpisodeList(long seasonId, int ps = 50, int pn = 1) + public static CheeseEpisodeList? CheeseEpisodeList(long seasonId, int ps = 50, int pn = 1) { - string url = $"https://api.bilibili.com/pugv/view/web/ep/list?season_id={seasonId}&pn={pn}&ps={ps}"; - string referer = "https://www.bilibili.com"; - string response = WebClient.RequestWeb(url, referer); + var url = $"https://api.bilibili.com/pugv/view/web/ep/list?season_id={seasonId}&pn={pn}&ps={ps}"; + const string referer = "https://www.bilibili.com"; + var response = WebClient.RequestWeb(url, referer); try { - CheeseEpisodeListOrigin cheese = JsonConvert.DeserializeObject(response); - if (cheese != null) - { - return cheese.Data; - } - else - { - return null; - } + var cheese = JsonConvert.DeserializeObject(response); + return cheese?.Data; } catch (Exception e) { diff --git a/DownKyi.Core/BiliApi/Favorites/FavoritesInfo.cs b/DownKyi.Core/BiliApi/Favorites/FavoritesInfo.cs index 6274e9b..500daf2 100644 --- a/DownKyi.Core/BiliApi/Favorites/FavoritesInfo.cs +++ b/DownKyi.Core/BiliApi/Favorites/FavoritesInfo.cs @@ -11,23 +11,16 @@ public static class FavoritesInfo /// 获取收藏夹元数据 /// /// - public static FavoritesMetaInfo GetFavoritesInfo(long mediaId) + public static FavoritesMetaInfo? GetFavoritesInfo(long mediaId) { - string url = $"https://api.bilibili.com/x/v3/fav/folder/info?media_id={mediaId}"; - string referer = "https://www.bilibili.com"; - string response = WebClient.RequestWeb(url, referer); + var url = $"https://api.bilibili.com/x/v3/fav/folder/info?media_id={mediaId}"; + const string referer = "https://www.bilibili.com"; + var response = WebClient.RequestWeb(url, referer); try { var info = JsonConvert.DeserializeObject(response); - if (info != null) - { - return info.Data; - } - else - { - return null; - } + return info?.Data; } catch (Exception e) { @@ -44,21 +37,17 @@ public static class FavoritesInfo /// 页码 /// 每页项数 /// - public static List GetCreatedFavorites(long mid, int pn, int ps) + public static List? GetCreatedFavorites(long mid, int pn, int ps) { - string url = $"https://api.bilibili.com/x/v3/fav/folder/created/list?up_mid={mid}&pn={pn}&ps={ps}"; - string referer = "https://www.bilibili.com"; - string response = WebClient.RequestWeb(url, referer); + var url = $"https://api.bilibili.com/x/v3/fav/folder/created/list?up_mid={mid}&pn={pn}&ps={ps}"; + const string referer = "https://www.bilibili.com"; + var response = WebClient.RequestWeb(url, referer); try { var favorites = JsonConvert.DeserializeObject(response); - if (favorites == null || favorites.Data == null || favorites.Data.List == null) - { - return null; - } - return favorites.Data.List; + return favorites?.Data.List; } catch (Exception e) { @@ -75,13 +64,13 @@ public static class FavoritesInfo /// public static List GetAllCreatedFavorites(long mid) { - List result = new List(); + var result = new List(); - int i = 0; + var i = 0; while (true) { i++; - int ps = 50; + const int ps = 50; var data = GetCreatedFavorites(mid, i, ps); if (data == null || data.Count == 0) @@ -102,11 +91,11 @@ public static class FavoritesInfo /// 页码 /// 每页项数 /// - public static List GetCollectedFavorites(long mid, int pn, int ps) + public static List? GetCollectedFavorites(long mid, int pn, int ps) { - string url = $"https://api.bilibili.com/x/v3/fav/folder/collected/list?up_mid={mid}&pn={pn}&ps={ps}"; - string referer = "https://www.bilibili.com"; - string response = WebClient.RequestWeb(url, referer); + var url = $"https://api.bilibili.com/x/v3/fav/folder/collected/list?up_mid={mid}&pn={pn}&ps={ps}"; + const string referer = "https://www.bilibili.com"; + var response = WebClient.RequestWeb(url, referer); try { @@ -133,13 +122,13 @@ public static class FavoritesInfo /// public static List GetAllCollectedFavorites(long mid) { - List result = new List(); + var result = new List(); - int i = 0; + var i = 0; while (true) { i++; - int ps = 50; + const int ps = 50; var data = GetCollectedFavorites(mid, i, ps); if (data == null || data.Count == 0) diff --git a/DownKyi.Core/BiliApi/Favorites/FavoritesResource.cs b/DownKyi.Core/BiliApi/Favorites/FavoritesResource.cs index 1142df3..50718c2 100644 --- a/DownKyi.Core/BiliApi/Favorites/FavoritesResource.cs +++ b/DownKyi.Core/BiliApi/Favorites/FavoritesResource.cs @@ -13,12 +13,11 @@ public static class FavoritesResource /// 页码 /// 每页项数 /// - public static List GetFavoritesMedia(long mediaId, int pn, int ps) + public static List? GetFavoritesMedia(long mediaId, int pn, int ps) { - string url = - $"https://api.bilibili.com/x/v3/fav/resource/list?media_id={mediaId}&pn={pn}&ps={ps}&platform=web"; - string referer = "https://www.bilibili.com"; - string response = WebClient.RequestWeb(url, referer); + var url = $"https://api.bilibili.com/x/v3/fav/resource/list?media_id={mediaId}&pn={pn}&ps={ps}&platform=web"; + const string referer = "https://www.bilibili.com"; + var response = WebClient.RequestWeb(url, referer); try { @@ -45,13 +44,13 @@ public static class FavoritesResource /// public static List GetAllFavoritesMedia(long mediaId) { - List result = new List(); + var result = new List(); - int i = 0; + var i = 0; while (true) { i++; - int ps = 20; + const int ps = 20; var data = GetFavoritesMedia(mediaId, i, ps); if (data == null || data.Count == 0) @@ -72,9 +71,9 @@ public static class FavoritesResource /// public static List GetFavoritesMediaId(long mediaId) { - string url = $"https://api.bilibili.com/x/v3/fav/resource/ids?media_id={mediaId}"; - string referer = "https://www.bilibili.com"; - string response = WebClient.RequestWeb(url, referer); + var url = $"https://api.bilibili.com/x/v3/fav/resource/ids?media_id={mediaId}"; + const string referer = "https://www.bilibili.com"; + var response = WebClient.RequestWeb(url, referer); try { diff --git a/DownKyi.Core/BiliApi/History/History.cs b/DownKyi.Core/BiliApi/History/History.cs index 1bfd2bd..db06168 100644 --- a/DownKyi.Core/BiliApi/History/History.cs +++ b/DownKyi.Core/BiliApi/History/History.cs @@ -1,7 +1,7 @@ using DownKyi.Core.BiliApi.History.Models; using DownKyi.Core.Logging; using Newtonsoft.Json; -using System; +using Console = DownKyi.Core.Utils.Debugging.Console; namespace DownKyi.Core.BiliApi.History { @@ -19,9 +19,9 @@ namespace DownKyi.Core.BiliApi.History /// 每页项数 /// 历史记录ID类型 /// - public static HistoryData GetHistory(long startId, long startTime, int ps = 30, HistoryBusiness business = HistoryBusiness.ARCHIVE) + public static HistoryData? GetHistory(long startId, long startTime, int ps = 30, HistoryBusiness business = HistoryBusiness.ARCHIVE) { - string businessStr = string.Empty; + var businessStr = string.Empty; switch (business) { case HistoryBusiness.ARCHIVE: @@ -41,9 +41,9 @@ namespace DownKyi.Core.BiliApi.History break; } - string url = $"https://api.bilibili.com/x/web-interface/history/cursor?max={startId}&view_at={startTime}&ps={ps}&business={businessStr}"; - string referer = "https://www.bilibili.com"; - string response = WebClient.RequestWeb(url, referer); + var url = $"https://api.bilibili.com/x/web-interface/history/cursor?max={startId}&view_at={startTime}&ps={ps}&business={businessStr}"; + const string referer = "https://www.bilibili.com"; + var response = WebClient.RequestWeb(url, referer); try { @@ -53,7 +53,7 @@ namespace DownKyi.Core.BiliApi.History } catch (Exception e) { - Utils.Debugging.Console.PrintLine("GetHistory()发生异常: {0}", e); + Console.PrintLine("GetHistory()发生异常: {0}", e); LogManager.Error("History", e); return null; } diff --git a/DownKyi.Core/BiliApi/History/ToView.cs b/DownKyi.Core/BiliApi/History/ToView.cs index 354569b..1c6871d 100644 --- a/DownKyi.Core/BiliApi/History/ToView.cs +++ b/DownKyi.Core/BiliApi/History/ToView.cs @@ -1,8 +1,7 @@ using DownKyi.Core.BiliApi.History.Models; using DownKyi.Core.Logging; using Newtonsoft.Json; -using System; -using System.Collections.Generic; +using Console = DownKyi.Core.Utils.Debugging.Console; namespace DownKyi.Core.BiliApi.History { @@ -15,11 +14,11 @@ namespace DownKyi.Core.BiliApi.History /// 获取稍后再看视频列表 /// /// - public static List GetToView() + public static List? GetToView() { - string url = "https://api.bilibili.com/x/v2/history/toview"; - string referer = "https://www.bilibili.com"; - string response = WebClient.RequestWeb(url, referer); + const string url = "https://api.bilibili.com/x/v2/history/toview"; + const string referer = "https://www.bilibili.com"; + var response = WebClient.RequestWeb(url, referer); try { @@ -29,10 +28,10 @@ namespace DownKyi.Core.BiliApi.History } catch (Exception e) { - Utils.Debugging.Console.PrintLine("GetToView()发生异常: {0}", e); + Console.PrintLine("GetToView()发生异常: {0}", e); LogManager.Error("ToView", e); return null; } } } -} +} \ No newline at end of file diff --git a/DownKyi.Core/BiliApi/Login/LoginHelper.cs b/DownKyi.Core/BiliApi/Login/LoginHelper.cs index d95c749..3688313 100644 --- a/DownKyi.Core/BiliApi/Login/LoginHelper.cs +++ b/DownKyi.Core/BiliApi/Login/LoginHelper.cs @@ -4,7 +4,6 @@ using DownKyi.Core.Settings; using DownKyi.Core.Settings.Models; using DownKyi.Core.Storage; using DownKyi.Core.Utils; -using DownKyi.Core.Utils.Encryptor; using Console = DownKyi.Core.Utils.Debugging.Console; namespace DownKyi.Core.BiliApi.Login @@ -12,7 +11,7 @@ namespace DownKyi.Core.BiliApi.Login public static class LoginHelper { // 本地位置 - private static readonly string LOCAL_LOGIN_INFO = StorageManager.GetLogin(); + private static readonly string LocalLoginInfo = StorageManager.GetLogin(); // 16位密码,ps:密码位数没有限制,可任意设置 private static readonly string SecretKey = "EsOat*^y1QR!&0J6"; @@ -24,10 +23,10 @@ namespace DownKyi.Core.BiliApi.Login /// public static bool SaveLoginInfoCookies(string url) { - string tempFile = LOCAL_LOGIN_INFO + "-" + Guid.NewGuid().ToString("N"); - CookieContainer cookieContainer = ObjectHelper.ParseCookie(url); + var tempFile = LocalLoginInfo + "-" + Guid.NewGuid().ToString("N"); + var cookieContainer = ObjectHelper.ParseCookie(url); - bool isSucceed = ObjectHelper.WriteCookiesToDisk(tempFile, cookieContainer); + var isSucceed = ObjectHelper.WriteCookiesToDisk(tempFile, cookieContainer); if (isSucceed) { // 加密密钥,增加机器码 @@ -35,7 +34,7 @@ namespace DownKyi.Core.BiliApi.Login try { - File.Copy(tempFile, LOCAL_LOGIN_INFO, true); + File.Copy(tempFile, LocalLoginInfo, true); // Encryptor.EncryptFile(tempFile, LOCAL_LOGIN_INFO, password); } catch (Exception e) @@ -61,13 +60,13 @@ namespace DownKyi.Core.BiliApi.Login /// public static CookieContainer? GetLoginInfoCookies() { - var tempFile = LOCAL_LOGIN_INFO + "-" + Guid.NewGuid().ToString("N"); + var tempFile = LocalLoginInfo + "-" + Guid.NewGuid().ToString("N"); - if (File.Exists(LOCAL_LOGIN_INFO)) + if (File.Exists(LocalLoginInfo)) { try { - File.Copy(LOCAL_LOGIN_INFO, tempFile, true); + File.Copy(LocalLoginInfo, tempFile, true); // 加密密钥,增加机器码 var password = SecretKey; // Encryptor.DecryptFile(LOCAL_LOGIN_INFO, tempFile, password); @@ -89,7 +88,7 @@ namespace DownKyi.Core.BiliApi.Login return null; } - CookieContainer cookies = ObjectHelper.ReadCookiesFromDisk(tempFile); + var cookies = ObjectHelper.ReadCookiesFromDisk(tempFile); if (File.Exists(tempFile)) { @@ -113,11 +112,7 @@ namespace DownKyi.Core.BiliApi.Login var cookies = ObjectHelper.GetAllCookies(cookieContainer); - string cookie = string.Empty; - foreach (var item in cookies) - { - cookie += item.ToString() + ";"; - } + var cookie = cookies.Aggregate(string.Empty, (current, item) => current + (item + ";")); return cookie.TrimEnd(';'); } @@ -128,30 +123,26 @@ namespace DownKyi.Core.BiliApi.Login /// public static bool Logout() { - if (File.Exists(LOCAL_LOGIN_INFO)) + if (!File.Exists(LocalLoginInfo)) return false; + try { - try - { - File.Delete(LOCAL_LOGIN_INFO); + File.Delete(LocalLoginInfo); - SettingsManager.GetInstance().SetUserInfo(new UserInfoSettings - { - Mid = -1, - Name = "", - IsLogin = false, - IsVip = false - }); - return true; - } - catch (IOException e) + SettingsManager.GetInstance().SetUserInfo(new UserInfoSettings { - Console.PrintLine("Logout()发生异常: {0}", e); - LogManager.Error(e); - return false; - } + Mid = -1, + Name = "", + IsLogin = false, + IsVip = false + }); + return true; + } + catch (IOException e) + { + Console.PrintLine("Logout()发生异常: {0}", e); + LogManager.Error(e); + return false; } - - return false; } } } \ No newline at end of file diff --git a/DownKyi.Core/BiliApi/Login/LoginQR.cs b/DownKyi.Core/BiliApi/Login/LoginQR.cs index 342f878..dd6bdd1 100644 --- a/DownKyi.Core/BiliApi/Login/LoginQR.cs +++ b/DownKyi.Core/BiliApi/Login/LoginQR.cs @@ -3,10 +3,11 @@ using DownKyi.Core.BiliApi.Login.Models; using DownKyi.Core.Logging; using DownKyi.Core.Utils; using Newtonsoft.Json; +using Console = DownKyi.Core.Utils.Debugging.Console; namespace DownKyi.Core.BiliApi.Login; -public static class LoginQR +public static class LoginQr { /// /// 申请二维码URL及扫码密钥(web端) @@ -14,16 +15,15 @@ public static class LoginQR /// public static LoginUrlOrigin? GetLoginUrl() { - string getLoginUrl = "https://passport.bilibili.com/x/passport-login/web/qrcode/generate"; - string response = WebClient.RequestWeb(getLoginUrl); - Console.Out.WriteLine(response); + const string getLoginUrl = "https://passport.bilibili.com/x/passport-login/web/qrcode/generate"; + var response = WebClient.RequestWeb(getLoginUrl); try { return JsonConvert.DeserializeObject(response); } catch (Exception e) { - Utils.Debugging.Console.PrintLine("GetLoginUrl()发生异常: {0}", e); + Console.PrintLine("GetLoginUrl()发生异常: {0}", e); LogManager.Error("LoginQR", e); return null; } @@ -33,13 +33,12 @@ public static class LoginQR /// 使用扫码登录(web端) /// /// - /// /// - public static LoginStatus? GetLoginStatus(string qrcodeKey, string goUrl = "https://www.bilibili.com") + public static LoginStatus? GetLoginStatus(string qrcodeKey) { - string url = "https://passport.bilibili.com/x/passport-login/web/qrcode/poll?qrcode_key=" + qrcodeKey; + var url = $"https://passport.bilibili.com/x/passport-login/web/qrcode/poll?qrcode_key={qrcodeKey}"; - string response = WebClient.RequestWeb(url); + var response = WebClient.RequestWeb(url); try { @@ -47,7 +46,7 @@ public static class LoginQR } catch (Exception e) { - Utils.Debugging.Console.PrintLine("GetLoginInfo()发生异常: {0}", e); + Console.PrintLine("GetLoginInfo()发生异常: {0}", e); LogManager.Error("LoginQR", e); return null; } @@ -57,16 +56,16 @@ public static class LoginQR /// 获得登录二维码 /// /// - public static Bitmap GetLoginQRCode() + public static Bitmap? GetLoginQrCode() { try { - string loginUrl = GetLoginUrl().Data.Url; - return GetLoginQRCode(loginUrl); + var loginUrl = GetLoginUrl()?.Data?.Url; + return GetLoginQrCode(loginUrl); } catch (Exception e) { - Utils.Debugging.Console.PrintLine("GetLoginQRCode()发生异常: {0}", e); + Console.PrintLine("GetLoginQrCode()发生异常: {0}", e); LogManager.Error("LoginQR", e); return null; } @@ -77,10 +76,11 @@ public static class LoginQR /// /// /// - public static Bitmap GetLoginQRCode(string url) + public static Bitmap? GetLoginQrCode(string? url) { + if (url == null) return null; // 设置的参数影响app能否成功扫码 - Bitmap qrCode = QRCode.EncodeQRCode(url, 11, 10, null, 0, 0, false); + var qrCode = QrCode.EncodeQrCode(url, 11, 10, null, 0, 0, false); return qrCode; } diff --git a/DownKyi.Core/BiliApi/Sign/WbiSign.cs b/DownKyi.Core/BiliApi/Sign/WbiSign.cs index 36369cc..ddd98f0 100644 --- a/DownKyi.Core/BiliApi/Sign/WbiSign.cs +++ b/DownKyi.Core/BiliApi/Sign/WbiSign.cs @@ -28,7 +28,7 @@ public static class WbiSign temp.Append(origin[i]); } - return temp.ToString().Substring(0, 32); + return temp.ToString()[..32]; } /// @@ -39,12 +39,7 @@ public static class WbiSign public static string ParametersToQuery(Dictionary parameters) { var keys = parameters.Keys.ToList(); - var queryList = new List(); - foreach (var item in keys) - { - var value = parameters[item]; - queryList.Add($"{item}={value}"); - } + var queryList = (from item in keys let value = parameters[item] select $"{item}={value}").ToList(); return string.Join("&", queryList); } @@ -54,7 +49,7 @@ public static class WbiSign /// /// /// - public static Dictionary EncodeWbi(Dictionary parameters) + public static Dictionary EncodeWbi(Dictionary parameters) { return EncWbi(parameters, GetKey().Item1, GetKey().Item2); } @@ -66,15 +61,16 @@ public static class WbiSign /// /// /// - private static Dictionary EncWbi(Dictionary parameters, string imgKey, - string subKey) + private static Dictionary EncWbi(Dictionary parameters, string imgKey, string subKey) { var paraStr = new Dictionary(); - foreach (var para in parameters) + foreach (var (key, value) in parameters) { - var key = para.Key; - var value = para.Value.ToString(); - paraStr.Add(key, value); + var val = value?.ToString(); + if (val != null) + { + paraStr.Add(key, val); + } } var mixinKey = GetMixinKey(imgKey + subKey); @@ -84,15 +80,11 @@ public static class WbiSign // 按照 key 重排参数 paraStr = paraStr.OrderBy(p => p.Key).ToDictionary(p => p.Key, p => p.Value); //过滤 value 中的 "!'()*" 字符 - paraStr = paraStr.ToDictionary( - kvp => kvp.Key, - kvp => new string(kvp.Value.Where(chr => !"!'()*".Contains(chr)).ToArray()) - ); + paraStr = paraStr.ToDictionary(kvp => kvp.Key, kvp => new string(kvp.Value.Where(chr => !"!'()*".Contains(chr)).ToArray())); // 序列化参数 var query = new FormUrlEncodedContent(paraStr).ReadAsStringAsync().Result; //计算 w_rid using var md5 = MD5.Create(); - //using MD5 md5 = MD5.Create(); var hashBytes = md5.ComputeHash(Encoding.UTF8.GetBytes(query + mixinKey)); var wbiSign = BitConverter.ToString(hashBytes).Replace("-", "").ToLower(); paraStr["w_rid"] = wbiSign; @@ -100,7 +92,7 @@ public static class WbiSign return paraStr; } - public static Tuple GetKey() + private static Tuple GetKey() { var user = SettingsManager.GetInstance().GetUserInfo(); diff --git a/DownKyi.Core/BiliApi/Users/Models/UserInfoForNavigation.cs b/DownKyi.Core/BiliApi/Users/Models/UserInfoForNavigation.cs index b6d8090..beeea09 100644 --- a/DownKyi.Core/BiliApi/Users/Models/UserInfoForNavigation.cs +++ b/DownKyi.Core/BiliApi/Users/Models/UserInfoForNavigation.cs @@ -22,7 +22,7 @@ public class UserInfoForNavigation : BaseModel //public int allowance_count { get; set; } //public int answer_status { get; set; } //public int email_verified { get; set; } - [JsonProperty("face")] public string Face { get; set; } + [JsonProperty("face")] public string? Face { get; set; } //public bool has_shop { get; set; } [JsonProperty("isLogin")] public bool IsLogin { get; set; } diff --git a/DownKyi.Core/BiliApi/Users/Nickname.cs b/DownKyi.Core/BiliApi/Users/Nickname.cs index bf24838..d0784a9 100644 --- a/DownKyi.Core/BiliApi/Users/Nickname.cs +++ b/DownKyi.Core/BiliApi/Users/Nickname.cs @@ -15,15 +15,15 @@ public class Nickname /// /// /// - public static NicknameStatus CheckNickname(string nickName) + public static NicknameStatus? CheckNickname(string nickName) { - string url = $"https://api.bilibili.com/x/relation/stat?nickName={nickName}"; - string referer = "https://www.bilibili.com"; - string response = WebClient.RequestWeb(url, referer); + var url = $"https://api.bilibili.com/x/relation/stat?nickName={nickName}"; + const string referer = "https://www.bilibili.com"; + var response = WebClient.RequestWeb(url, referer); try { - NicknameStatus nickname = JsonConvert.DeserializeObject(response); + var nickname = JsonConvert.DeserializeObject(response); return nickname; } catch (Exception e) diff --git a/DownKyi.Core/BiliApi/Users/UserInfo.cs b/DownKyi.Core/BiliApi/Users/UserInfo.cs index edf2ee6..89e513b 100644 --- a/DownKyi.Core/BiliApi/Users/UserInfo.cs +++ b/DownKyi.Core/BiliApi/Users/UserInfo.cs @@ -42,7 +42,7 @@ public static class UserInfo /// public static UserInfoForSpace? GetUserInfoForSpace(long mid) { - var parameters = new Dictionary + var parameters = new Dictionary { { "mid", mid } }; diff --git a/DownKyi.Core/BiliApi/Users/UserRelation.cs b/DownKyi.Core/BiliApi/Users/UserRelation.cs index 1a2b330..d214c44 100644 --- a/DownKyi.Core/BiliApi/Users/UserRelation.cs +++ b/DownKyi.Core/BiliApi/Users/UserRelation.cs @@ -17,15 +17,15 @@ public static class UserRelation /// 页码 /// 每页项数 /// - public static RelationFollow GetFollowers(long mid, int pn, int ps) + public static RelationFollow? GetFollowers(long mid, int pn, int ps) { - string url = $"https://api.bilibili.com/x/relation/followers?vmid={mid}&pn={pn}&ps={ps}"; - string referer = "https://www.bilibili.com"; - string response = WebClient.RequestWeb(url, referer); + var url = $"https://api.bilibili.com/x/relation/followers?vmid={mid}&pn={pn}&ps={ps}"; + const string referer = "https://www.bilibili.com"; + var response = WebClient.RequestWeb(url, referer); try { - RelationFollowOrigin relationFollower = JsonConvert.DeserializeObject(response); + var relationFollower = JsonConvert.DeserializeObject(response); if (relationFollower == null || relationFollower.Data == null) { return null; @@ -48,15 +48,15 @@ public static class UserRelation /// public static List GetAllFollowers(long mid) { - List result = new List(); + var result = new List(); - int i = 0; + var i = 0; while (true) { i++; - int ps = 50; + const int ps = 50; - RelationFollow data = GetFollowers(mid, i, ps); + var data = GetFollowers(mid, i, ps); if (data == null || data.List == null || data.List.Count == 0) { break; @@ -76,23 +76,21 @@ public static class UserRelation /// 每页项数 /// 排序方式 /// - public static RelationFollow GetFollowings(long mid, int pn, int ps, - FollowingOrder order = FollowingOrder.DEFAULT) + public static RelationFollow? GetFollowings(long mid, int pn, int ps, FollowingOrder order = FollowingOrder.DEFAULT) { - string orderType = ""; + var orderType = ""; if (order == FollowingOrder.ATTENTION) { orderType = "attention"; } - string url = - $"https://api.bilibili.com/x/relation/followings?vmid={mid}&pn={pn}&ps={ps}&order_type={orderType}"; - string referer = "https://www.bilibili.com"; - string response = WebClient.RequestWeb(url, referer); + var url = $"https://api.bilibili.com/x/relation/followings?vmid={mid}&pn={pn}&ps={ps}&order_type={orderType}"; + const string referer = "https://www.bilibili.com"; + var response = WebClient.RequestWeb(url, referer); try { - RelationFollowOrigin relationFollower = JsonConvert.DeserializeObject(response); + var relationFollower = JsonConvert.DeserializeObject(response); if (relationFollower == null || relationFollower.Data == null) { return null; @@ -116,15 +114,15 @@ public static class UserRelation /// public static List GetAllFollowings(long mid, FollowingOrder order = FollowingOrder.DEFAULT) { - List result = new List(); + var result = new List(); - int i = 0; + var i = 0; while (true) { i++; - int ps = 50; + const int ps = 50; - RelationFollow data = GetFollowings(mid, i, ps, order); + var data = GetFollowings(mid, i, ps, order); if (data == null || data.List == null || data.List.Count == 0) { break; @@ -142,15 +140,15 @@ public static class UserRelation /// 页码 /// 每页项数 /// - public static List GetWhispers(int pn, int ps) + public static List? GetWhispers(int pn, int ps) { - string url = $"https://api.bilibili.com/x/relation/whispers?pn={pn}&ps={ps}"; - string referer = "https://www.bilibili.com"; - string response = WebClient.RequestWeb(url, referer); + var url = $"https://api.bilibili.com/x/relation/whispers?pn={pn}&ps={ps}"; + const string referer = "https://www.bilibili.com"; + var response = WebClient.RequestWeb(url, referer); try { - RelationWhisper relationWhisper = JsonConvert.DeserializeObject(response); + var relationWhisper = JsonConvert.DeserializeObject(response); if (relationWhisper == null || relationWhisper.Data == null || relationWhisper.Data.List == null) { return null; @@ -172,15 +170,15 @@ public static class UserRelation /// 页码 /// 每页项数 /// - public static List GetBlacks(int pn, int ps) + public static List? GetBlacks(int pn, int ps) { - string url = $"https://api.bilibili.com/x/relation/blacks?pn={pn}&ps={ps}"; - string referer = "https://www.bilibili.com"; - string response = WebClient.RequestWeb(url, referer); + var url = $"https://api.bilibili.com/x/relation/blacks?pn={pn}&ps={ps}"; + const string referer = "https://www.bilibili.com"; + var response = WebClient.RequestWeb(url, referer); try { - RelationBlack relationBlack = JsonConvert.DeserializeObject(response); + var relationBlack = JsonConvert.DeserializeObject(response); if (relationBlack == null || relationBlack.Data == null) { return null; @@ -202,11 +200,11 @@ public static class UserRelation /// 查询关注分组列表 /// /// - public static List GetFollowingGroup() + public static List? GetFollowingGroup() { - string url = $"https://api.bilibili.com/x/relation/tags"; - string referer = "https://www.bilibili.com"; - string response = WebClient.RequestWeb(url, referer); + const string url = $"https://api.bilibili.com/x/relation/tags"; + const string referer = "https://www.bilibili.com"; + var response = WebClient.RequestWeb(url, referer); try { @@ -234,23 +232,23 @@ public static class UserRelation /// 每页项数 /// 排序方式 /// - public static List GetFollowingGroupContent(long tagId, int pn, int ps, + public static List? GetFollowingGroupContent(long tagId, int pn, int ps, FollowingOrder order = FollowingOrder.DEFAULT) { - string orderType = ""; + var orderType = ""; if (order == FollowingOrder.ATTENTION) { orderType = "attention"; } - string url = + var url = $"https://api.bilibili.com/x/relation/tag?tagid={tagId}&pn={pn}&ps={ps}&order_type={orderType}"; - string referer = "https://www.bilibili.com"; - string response = WebClient.RequestWeb(url, referer); + const string referer = "https://www.bilibili.com"; + var response = WebClient.RequestWeb(url, referer); try { - FollowingGroupContent content = JsonConvert.DeserializeObject(response); + var content = JsonConvert.DeserializeObject(response); if (content == null || content.Data == null) { return null; @@ -275,13 +273,13 @@ public static class UserRelation public static List GetAllFollowingGroupContent(int tagId, FollowingOrder order = FollowingOrder.DEFAULT) { - List result = new List(); + var result = new List(); - int i = 0; + var i = 0; while (true) { i++; - int ps = 50; + const int ps = 50; var data = GetFollowingGroupContent(tagId, i, ps, order); if (data == null || data.Count == 0) diff --git a/DownKyi.Core/BiliApi/Users/UserSpace.cs b/DownKyi.Core/BiliApi/Users/UserSpace.cs index f6b1550..d3f9337 100644 --- a/DownKyi.Core/BiliApi/Users/UserSpace.cs +++ b/DownKyi.Core/BiliApi/Users/UserSpace.cs @@ -43,7 +43,7 @@ public static class UserSpace /// /// 用户id /// - public static List GetPublicationType(long mid) + public static List? GetPublicationType(long mid) { const int pn = 1; const int ps = 1; @@ -54,22 +54,24 @@ public static class UserSpace /// /// 获取用户投稿视频的所有分区 /// - /// 用户id + /// /// - public static List GetPublicationType(SpacePublicationList? publication) + public static List? GetPublicationType(SpacePublicationList? publication) { if (publication?.Tlist == null) { return null; } - var result = new List(); + var result = new List(); var typeList = JObject.Parse(publication.Tlist.ToString("N")); foreach (KeyValuePair item in typeList) { var value = JsonConvert.DeserializeObject(item.Value.ToString()); - result.Add(value); + if (value != null) + result.Add(value); } + return result; } @@ -93,7 +95,9 @@ public static class UserSpace var data = GetPublication(mid, i, ps, tid, order, keyword); if (data?.Vlist == null || data.Vlist.Count == 0) - { break; } + { + break; + } result.AddRange(data.Vlist); } @@ -113,7 +117,7 @@ public static class UserSpace /// public static SpacePublicationList? GetPublication(long mid, int pn, int ps, long tid = 0, PublicationOrder order = PublicationOrder.PUBDATE, string keyword = "") { - var parameters = new Dictionary + var parameters = new Dictionary { { "mid", mid }, { "pn", pn }, @@ -134,8 +138,7 @@ public static class UserSpace { Error = (sender, args) => { - if (Equals(args.ErrorContext.Member, "play") && - args.ErrorContext.OriginalObject.GetType() == typeof(SpacePublicationListVideo)) + if (Equals(args.ErrorContext.Member, "play") && args.ErrorContext.OriginalObject?.GetType() == typeof(SpacePublicationListVideo)) { args.ErrorContext.Handled = true; } @@ -199,10 +202,13 @@ public static class UserSpace var data = GetChannelVideoList(mid, cid, i, ps); if (data?.Count == 0) - { break; } + { + break; + } result.AddRange(data); } + return result; } @@ -348,6 +354,7 @@ public static class UserSpace #endregion #region 课程 + /// /// 查询用户发布的课程列表 /// @@ -387,14 +394,17 @@ public static class UserSpace while (true) { i++; - var ps = 50; + const int ps = 50; var data = GetCheese(mid, i, ps); if (data == null || data.Count == 0) - { break; } + { + break; + } result.AddRange(data); } + return result; } @@ -447,13 +457,15 @@ public static class UserSpace var data = GetBangumiFollow(mid, type, i, ps); if (data?.List == null || data.List.Count == 0) - { break; } + { + break; + } result.AddRange(data.List); } + return result; } #endregion - } \ No newline at end of file diff --git a/DownKyi.Core/BiliApi/Users/UserStatus.cs b/DownKyi.Core/BiliApi/Users/UserStatus.cs index b17c4be..63d8145 100644 --- a/DownKyi.Core/BiliApi/Users/UserStatus.cs +++ b/DownKyi.Core/BiliApi/Users/UserStatus.cs @@ -15,16 +15,15 @@ public static class UserStatus /// /// /// - public static UserRelationStat GetUserRelationStat(long mid) + public static UserRelationStat? GetUserRelationStat(long mid) { - string url = $"https://api.bilibili.com/x/relation/stat?vmid={mid}"; - string referer = "https://www.bilibili.com"; - string response = WebClient.RequestWeb(url, referer); + var url = $"https://api.bilibili.com/x/relation/stat?vmid={mid}"; + const string referer = "https://www.bilibili.com"; + var response = WebClient.RequestWeb(url, referer); try { - UserRelationStatOrigin userRelationStat = - JsonConvert.DeserializeObject(response); + var userRelationStat = JsonConvert.DeserializeObject(response); if (userRelationStat == null || userRelationStat.Data == null) { return null; @@ -47,15 +46,15 @@ public static class UserStatus /// /// /// - public static UpStat GetUpStat(long mid) + public static UpStat? GetUpStat(long mid) { - string url = $"https://api.bilibili.com/x/space/upstat?mid={mid}"; - string referer = "https://www.bilibili.com"; - string response = WebClient.RequestWeb(url, referer); + var url = $"https://api.bilibili.com/x/space/upstat?mid={mid}"; + const string referer = "https://www.bilibili.com"; + var response = WebClient.RequestWeb(url, referer); try { - UpStatOrigin upStat = JsonConvert.DeserializeObject(response); + var upStat = JsonConvert.DeserializeObject(response); if (upStat == null || upStat.Data == null) { return null; diff --git a/DownKyi.Core/BiliApi/Video/Dynamic.cs b/DownKyi.Core/BiliApi/Video/Dynamic.cs index de1e076..be963f2 100644 --- a/DownKyi.Core/BiliApi/Video/Dynamic.cs +++ b/DownKyi.Core/BiliApi/Video/Dynamic.cs @@ -14,11 +14,11 @@ public static class Dynamic /// 页码 /// 每页项数(最大50) /// - public static List RegionDynamicList(int rid, int pn = 1, int ps = 5) + public static List? RegionDynamicList(int rid, int pn = 1, int ps = 5) { - string url = $"https://api.bilibili.com/x/web-interface/dynamic/region?rid={rid}&pn={pn}&ps={ps}"; - string referer = "https://www.bilibili.com"; - string response = WebClient.RequestWeb(url, referer); + var url = $"https://api.bilibili.com/x/web-interface/dynamic/region?rid={rid}&pn={pn}&ps={ps}"; + const string referer = "https://www.bilibili.com"; + var response = WebClient.RequestWeb(url, referer); try { @@ -27,10 +27,8 @@ public static class Dynamic { return dynamic.Data.Archives; } - else - { - return null; - } + + return null; } catch (Exception e) { diff --git a/DownKyi.Core/BiliApi/Video/Ranking.cs b/DownKyi.Core/BiliApi/Video/Ranking.cs index 98a43d6..69c15ee 100644 --- a/DownKyi.Core/BiliApi/Video/Ranking.cs +++ b/DownKyi.Core/BiliApi/Video/Ranking.cs @@ -14,11 +14,11 @@ public static class Ranking /// 3日榜或周榜(3/7) /// /// - public static List RegionRankingList(int rid, int day = 3, int original = 0) + public static List? RegionRankingList(int rid, int day = 3, int original = 0) { - string url = $"https://api.bilibili.com/x/web-interface/ranking/region?rid={rid}&day={day}&ps={original}"; - string referer = "https://www.bilibili.com"; - string response = WebClient.RequestWeb(url, referer); + var url = $"https://api.bilibili.com/x/web-interface/ranking/region?rid={rid}&day={day}&ps={original}"; + const string referer = "https://www.bilibili.com"; + var response = WebClient.RequestWeb(url, referer); try { @@ -27,10 +27,8 @@ public static class Ranking { return ranking.Data; } - else - { - return null; - } + + return null; } catch (Exception e) { diff --git a/DownKyi.Core/BiliApi/Video/VideoInfo.cs b/DownKyi.Core/BiliApi/Video/VideoInfo.cs index 1d11229..291cc55 100644 --- a/DownKyi.Core/BiliApi/Video/VideoInfo.cs +++ b/DownKyi.Core/BiliApi/Video/VideoInfo.cs @@ -18,7 +18,7 @@ public static class VideoInfo { // 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 - var parameters = new Dictionary(); + var parameters = new Dictionary(); if (bvid != null) { parameters.Add("bvid", bvid); diff --git a/DownKyi.Core/BiliApi/VideoStream/PlayStreamType.cs b/DownKyi.Core/BiliApi/VideoStream/PlayStreamType.cs index 0ed9ed6..322f151 100644 --- a/DownKyi.Core/BiliApi/VideoStream/PlayStreamType.cs +++ b/DownKyi.Core/BiliApi/VideoStream/PlayStreamType.cs @@ -2,7 +2,7 @@ public enum PlayStreamType { - VIDEO = 1, // 普通视频 - BANGUMI, // 番剧、电影、电视剧等 - CHEESE, // 课程 + Video = 1, // 普通视频 + Bangumi, // 番剧、电影、电视剧等 + Cheese, // 课程 } \ No newline at end of file diff --git a/DownKyi.Core/BiliApi/VideoStream/VideoStream.cs b/DownKyi.Core/BiliApi/VideoStream/VideoStream.cs index ca0156c..ab09e76 100644 --- a/DownKyi.Core/BiliApi/VideoStream/VideoStream.cs +++ b/DownKyi.Core/BiliApi/VideoStream/VideoStream.cs @@ -17,14 +17,24 @@ public static class VideoStream /// /// /// - public static PlayerV2 PlayerV2(long avid, string bvid, long cid) + public static PlayerV2? PlayerV2(long avid, string? bvid, long cid) { - var parameters = new Dictionary + var parameters = new Dictionary(); + + if (avid > 0) { - { "avid", avid }, - { "bvid", bvid }, - { "cid", cid }, - }; + parameters.Add("bvid", bvid); + } + + if (bvid != null) + { + parameters.Add("avid", avid); + } + else if (cid > 0) + { + parameters.Add("cid", cid); + } + var query = WbiSign.ParametersToQuery(WbiSign.EncodeWbi(parameters)); var url = $"https://api.bilibili.com/x/player/wbi/v2?{query}"; const string referer = "https://www.bilibili.com"; @@ -51,7 +61,7 @@ public static class VideoStream /// /// /// - public static List GetSubtitle(long avid, string bvid, long cid) + public static List? GetSubtitle(long avid, string? bvid, long cid) { var subRipTexts = new List(); @@ -107,7 +117,7 @@ public static class VideoStream /// public static PlayUrl GetVideoPlayUrl(long avid, string bvid, long cid, int quality = 125) { - var parameters = new Dictionary + var parameters = new Dictionary { { "fourk", 1 }, { "fnver", 0 }, @@ -242,11 +252,13 @@ public static class VideoStream { return null; } - else if (playUrl.Data != null) + + if (playUrl.Data != null) { return playUrl.Data; } - else if (playUrl.Result != null) + + if (playUrl.Result != null) { return playUrl.Result; } @@ -287,18 +299,18 @@ public static class VideoStream { return null; } - else if (playUrl.Data != null) + + if (playUrl.Data != null) { return playUrl.Data; } - else if (playUrl.Result != null) + + if (playUrl.Result != null) { return playUrl.Result; } - else - { - return null; - } + + return null; } catch (Exception e) { diff --git a/DownKyi.Core/BiliApi/WebClient.cs b/DownKyi.Core/BiliApi/WebClient.cs index 04398b5..cc4bd3a 100644 --- a/DownKyi.Core/BiliApi/WebClient.cs +++ b/DownKyi.Core/BiliApi/WebClient.cs @@ -1,10 +1,11 @@ using System.IO.Compression; using System.Net; using System.Text; +using System.Text.Json; +using System.Text.Json.Serialization; using DownKyi.Core.BiliApi.Login; using DownKyi.Core.Logging; using DownKyi.Core.Settings; -using Newtonsoft.Json; namespace DownKyi.Core.BiliApi; @@ -12,15 +13,15 @@ internal static class WebClient { internal class SpiOrigin { - [JsonProperty("data")] public Spi? Data { get; set; } - public int Code { get; set; } - public string? Message { get; set; } + [JsonPropertyName("data")] public Spi? Data { get; init; } + public int Code { get; init; } + public string? Message { get; init; } } internal class Spi { - [JsonProperty("b_3")] public string? Bvuid3 { get; set; } - [JsonProperty("b_4")] public string? Bvuid4 { get; set; } + [JsonPropertyName("b_3")] public string? Bvuid3 { get; set; } + [JsonPropertyName("b_4")] public string? Bvuid4 { get; set; } } private static string? _bvuid3 = string.Empty; @@ -44,7 +45,7 @@ internal static class WebClient { const string url = "https://api.bilibili.com/x/frontend/finger/spi"; var response = RequestWeb(url); - var spi = JsonConvert.DeserializeObject(response); + var spi = JsonSerializer.Deserialize(response); _bvuid3 = spi?.Data?.Bvuid3; _bvuid4 = spi?.Data?.Bvuid4; } diff --git a/DownKyi.Core/BiliApi/Zone/VideoZone.cs b/DownKyi.Core/BiliApi/Zone/VideoZone.cs index e0d0a56..1424be7 100644 --- a/DownKyi.Core/BiliApi/Zone/VideoZone.cs +++ b/DownKyi.Core/BiliApi/Zone/VideoZone.cs @@ -1,11 +1,9 @@ -using System.Collections.Generic; - -namespace DownKyi.Core.BiliApi.Zone; +namespace DownKyi.Core.BiliApi.Zone; public class VideoZone { - private static VideoZone that; - private readonly List zones = new(); + private static VideoZone? _that; + private readonly List _zones = new(); /// /// 使用单例模式获取分区,注意未搜索到的分区需要额外处理 @@ -13,17 +11,12 @@ public class VideoZone /// public static VideoZone Instance() { - if (that == null) - { - that = new VideoZone(); - } - - return that; + return _that ??= new VideoZone(); } public List GetZones() { - return zones; + return _zones; } private VideoZone() @@ -31,185 +24,180 @@ public class VideoZone // SpacePublicationListType类需要同步更新 //动画 - zones.Add(new ZoneAttr(1, "douga", "动画")); // 主分区 - zones.Add(new ZoneAttr(24, "mad", "MAD·AMV", 1)); // 具有一定制作程度的动画或静画的二次创作视频 - zones.Add(new ZoneAttr(25, "mmd", "MMD·3D", 1)); // 使用MMD(MikuMikuDance)和其他3D建模类软件制作的视频 - zones.Add(new ZoneAttr(47, "voice", "短片·手书·配音", 1)); // 追求个人特色和创意表达的自制动画短片、手书(绘)及ACGN相关配音 - zones.Add(new ZoneAttr(210, "garage_kit", "手办·模玩", 1)); // 手办模玩的测评、改造或其他衍生内容 - zones.Add(new ZoneAttr(86, "tokusatsu", "特摄", 1)); // 特摄相关衍生视频 - zones.Add(new ZoneAttr(253, "acgntalks", "动漫杂谈", 1)); // 以谈话形式对ACGN文化圈进行的鉴赏、吐槽、评点、解说、推荐、科普等内容 - zones.Add(new ZoneAttr(27, "other", "综合", 1)); // 以动画及动画相关内容为素材,包括但不仅限于音频替换、恶搞改编、排行榜等内容 + _zones.Add(new ZoneAttr(1, "douga", "动画")); // 主分区 + _zones.Add(new ZoneAttr(24, "mad", "MAD·AMV", 1)); // 具有一定制作程度的动画或静画的二次创作视频 + _zones.Add(new ZoneAttr(25, "mmd", "MMD·3D", 1)); // 使用MMD(MikuMikuDance)和其他3D建模类软件制作的视频 + _zones.Add(new ZoneAttr(47, "voice", "短片·手书·配音", 1)); // 追求个人特色和创意表达的自制动画短片、手书(绘)及ACGN相关配音 + _zones.Add(new ZoneAttr(210, "garage_kit", "手办·模玩", 1)); // 手办模玩的测评、改造或其他衍生内容 + _zones.Add(new ZoneAttr(86, "tokusatsu", "特摄", 1)); // 特摄相关衍生视频 + _zones.Add(new ZoneAttr(253, "acgntalks", "动漫杂谈", 1)); // 以谈话形式对ACGN文化圈进行的鉴赏、吐槽、评点、解说、推荐、科普等内容 + _zones.Add(new ZoneAttr(27, "other", "综合", 1)); // 以动画及动画相关内容为素材,包括但不仅限于音频替换、恶搞改编、排行榜等内容 //番剧 - zones.Add(new ZoneAttr(13, "anime", "番剧")); // 主分区 - zones.Add(new ZoneAttr(33, "serial", "连载动画", 13)); // 当季连载的动画番剧 - zones.Add(new ZoneAttr(32, "finish", "完结动画", 13)); // 已完结的动画番剧合集 - zones.Add(new ZoneAttr(51, "information", "资讯", 13)); // 动画番剧相关资讯视频 - zones.Add(new ZoneAttr(152, "offical", "官方延伸", 13)); // 动画番剧为主题的宣传节目、采访视频,及声优相关视频 + _zones.Add(new ZoneAttr(13, "anime", "番剧")); // 主分区 + _zones.Add(new ZoneAttr(33, "serial", "连载动画", 13)); // 当季连载的动画番剧 + _zones.Add(new ZoneAttr(32, "finish", "完结动画", 13)); // 已完结的动画番剧合集 + _zones.Add(new ZoneAttr(51, "information", "资讯", 13)); // 动画番剧相关资讯视频 + _zones.Add(new ZoneAttr(152, "offical", "官方延伸", 13)); // 动画番剧为主题的宣传节目、采访视频,及声优相关视频 //国创 - zones.Add(new ZoneAttr(167, "guochuang", "国创")); // 主分区 - zones.Add(new ZoneAttr(153, "chinese", "国产动画", 167)); // 我国出品的PGC动画 - zones.Add(new ZoneAttr(168, "original", "国产原创相关", 167)); // - zones.Add(new ZoneAttr(169, "puppetry", "布袋戏", 167)); // - zones.Add(new ZoneAttr(195, "motioncomic", "动态漫·广播剧", 167)); // - zones.Add(new ZoneAttr(170, "information", "资讯", 167)); // + _zones.Add(new ZoneAttr(167, "guochuang", "国创")); // 主分区 + _zones.Add(new ZoneAttr(153, "chinese", "国产动画", 167)); // 我国出品的PGC动画 + _zones.Add(new ZoneAttr(168, "original", "国产原创相关", 167)); // + _zones.Add(new ZoneAttr(169, "puppetry", "布袋戏", 167)); // + _zones.Add(new ZoneAttr(195, "motioncomic", "动态漫·广播剧", 167)); // + _zones.Add(new ZoneAttr(170, "information", "资讯", 167)); // //音乐 - zones.Add(new ZoneAttr(3, "music", "音乐")); // 主分区 - zones.Add(new ZoneAttr(28, "original", "原创音乐", 3)); // 原创歌曲及纯音乐,包括改编、重编曲及remix - zones.Add(new ZoneAttr(31, "cover", "翻唱", 3)); // 对曲目的人声再演绎视频 - zones.Add(new ZoneAttr(59, "perform", "演奏", 3)); // 乐器和非传统乐器器材的演奏作品 - zones.Add(new ZoneAttr(30, "vocaloid", "VOCALOID·UTAU", 3)); // 以VOCALOID等歌声合成引擎为基础,运用各类音源进行的创作 - zones.Add(new ZoneAttr(29, "live", "音乐现场", 3)); // 音乐表演的实况视频,包括官方/个人拍摄的综艺节目、音乐剧、音乐节、演唱会等 - zones.Add(new ZoneAttr(193, "mv", "MV", 3)); // 为音乐作品配合拍摄或制作的音乐录影带(Music Video),以及自制拍摄、剪辑、翻拍MV - zones.Add(new ZoneAttr(243, "commentary", "乐评盘点", 3)); // 音乐类新闻、盘点、点评、reaction、榜单、采访、幕后故事、唱片开箱等 - zones.Add(new ZoneAttr(244, "tutorial", "音乐教学", 3)); // 以音乐教学为目的的内容 - zones.Add(new ZoneAttr(130, "other", "音乐综合", 3)); // 所有无法被收纳到其他音乐二级分区的音乐类视频 + _zones.Add(new ZoneAttr(3, "music", "音乐")); // 主分区 + _zones.Add(new ZoneAttr(28, "original", "原创音乐", 3)); // 原创歌曲及纯音乐,包括改编、重编曲及remix + _zones.Add(new ZoneAttr(31, "cover", "翻唱", 3)); // 对曲目的人声再演绎视频 + _zones.Add(new ZoneAttr(59, "perform", "演奏", 3)); // 乐器和非传统乐器器材的演奏作品 + _zones.Add(new ZoneAttr(30, "vocaloid", "VOCALOID·UTAU", 3)); // 以VOCALOID等歌声合成引擎为基础,运用各类音源进行的创作 + _zones.Add(new ZoneAttr(29, "live", "音乐现场", 3)); // 音乐表演的实况视频,包括官方/个人拍摄的综艺节目、音乐剧、音乐节、演唱会等 + _zones.Add(new ZoneAttr(193, "mv", "MV", 3)); // 为音乐作品配合拍摄或制作的音乐录影带(Music Video),以及自制拍摄、剪辑、翻拍MV + _zones.Add(new ZoneAttr(243, "commentary", "乐评盘点", 3)); // 音乐类新闻、盘点、点评、reaction、榜单、采访、幕后故事、唱片开箱等 + _zones.Add(new ZoneAttr(244, "tutorial", "音乐教学", 3)); // 以音乐教学为目的的内容 + _zones.Add(new ZoneAttr(130, "other", "音乐综合", 3)); // 所有无法被收纳到其他音乐二级分区的音乐类视频 //舞蹈 - zones.Add(new ZoneAttr(129, "dance", "舞蹈")); // 主分区 - zones.Add(new ZoneAttr(20, "otaku", "宅舞", 129)); // 与ACG相关的翻跳、原创舞蹈 - zones.Add(new ZoneAttr(198, "hiphop", "街舞", 129)); // 收录街舞相关内容,包括赛事现场、舞室作品、个人翻跳、FREESTYLE等 - zones.Add(new ZoneAttr(199, "star", "明星舞蹈", 129)); // 国内外明星发布的官方舞蹈及其翻跳内容 - zones.Add(new ZoneAttr(200, "china", "中国舞", 129)); // 传承中国艺术文化的舞蹈内容,包括古典舞、民族民间舞、汉唐舞、古风舞等 - zones.Add(new ZoneAttr(154, "three_d", "舞蹈综合", 129)); // 收录无法定义到其他舞蹈子分区的舞蹈视频 - zones.Add(new ZoneAttr(156, "demo", "舞蹈教程", 129)); // 镜面慢速,动作分解,基础教程等具有教学意义的舞蹈视频 + _zones.Add(new ZoneAttr(129, "dance", "舞蹈")); // 主分区 + _zones.Add(new ZoneAttr(20, "otaku", "宅舞", 129)); // 与ACG相关的翻跳、原创舞蹈 + _zones.Add(new ZoneAttr(198, "hiphop", "街舞", 129)); // 收录街舞相关内容,包括赛事现场、舞室作品、个人翻跳、FREESTYLE等 + _zones.Add(new ZoneAttr(199, "star", "明星舞蹈", 129)); // 国内外明星发布的官方舞蹈及其翻跳内容 + _zones.Add(new ZoneAttr(200, "china", "中国舞", 129)); // 传承中国艺术文化的舞蹈内容,包括古典舞、民族民间舞、汉唐舞、古风舞等 + _zones.Add(new ZoneAttr(154, "three_d", "舞蹈综合", 129)); // 收录无法定义到其他舞蹈子分区的舞蹈视频 + _zones.Add(new ZoneAttr(156, "demo", "舞蹈教程", 129)); // 镜面慢速,动作分解,基础教程等具有教学意义的舞蹈视频 //游戏 - zones.Add(new ZoneAttr(4, "game", "游戏")); // 主分区 - zones.Add(new ZoneAttr(17, "stand_alone", "单机游戏", - 4)); // 以所有平台(PC、主机、移动端)的单机或联机游戏为主的视频内容,包括游戏预告、CG、实况解说及相关的评测、杂谈与视频剪辑等 - zones.Add(new ZoneAttr(171, "esports", "电子竞技", 4)); // 具有高对抗性的电子竞技游戏项目,其相关的赛事、实况、攻略、解说、短剧等视频。 - zones.Add(new ZoneAttr(172, "mobile", "手机游戏", 4)); // 以手机及平板设备为主要平台的游戏,其相关的实况、攻略、解说、短剧、演示等视频。 - zones.Add(new ZoneAttr(65, "online", "网络游戏", 4)); // 由网络运营商运营的多人在线游戏,以及电子竞技的相关游戏内容。包括赛事、攻略、实况、解说等相关视频 - zones.Add(new ZoneAttr(173, "board", "桌游棋牌", 4)); // 桌游、棋牌、卡牌对战等及其相关电子版游戏的实况、攻略、解说、演示等视频。 - zones.Add(new ZoneAttr(121, "gmv", "GMV", 4)); // 由游戏素材制作的MV视频。以游戏内容或CG为主制作的,具有一定创作程度的MV类型的视频 - zones.Add(new ZoneAttr(136, "music", "音游", 4)); // 各个平台上,通过配合音乐与节奏而进行的音乐类游戏视频 - zones.Add(new ZoneAttr(19, "mugen", "Mugen", 4)); // 以Mugen引擎为平台制作、或与Mugen相关的游戏视频 + _zones.Add(new ZoneAttr(4, "game", "游戏")); // 主分区 + _zones.Add(new ZoneAttr(17, "stand_alone", "单机游戏", 4)); // 以所有平台(PC、主机、移动端)的单机或联机游戏为主的视频内容,包括游戏预告、CG、实况解说及相关的评测、杂谈与视频剪辑等 + _zones.Add(new ZoneAttr(171, "esports", "电子竞技", 4)); // 具有高对抗性的电子竞技游戏项目,其相关的赛事、实况、攻略、解说、短剧等视频。 + _zones.Add(new ZoneAttr(172, "mobile", "手机游戏", 4)); // 以手机及平板设备为主要平台的游戏,其相关的实况、攻略、解说、短剧、演示等视频。 + _zones.Add(new ZoneAttr(65, "online", "网络游戏", 4)); // 由网络运营商运营的多人在线游戏,以及电子竞技的相关游戏内容。包括赛事、攻略、实况、解说等相关视频 + _zones.Add(new ZoneAttr(173, "board", "桌游棋牌", 4)); // 桌游、棋牌、卡牌对战等及其相关电子版游戏的实况、攻略、解说、演示等视频。 + _zones.Add(new ZoneAttr(121, "gmv", "GMV", 4)); // 由游戏素材制作的MV视频。以游戏内容或CG为主制作的,具有一定创作程度的MV类型的视频 + _zones.Add(new ZoneAttr(136, "music", "音游", 4)); // 各个平台上,通过配合音乐与节奏而进行的音乐类游戏视频 + _zones.Add(new ZoneAttr(19, "mugen", "Mugen", 4)); // 以Mugen引擎为平台制作、或与Mugen相关的游戏视频 //知识 - zones.Add(new ZoneAttr(36, "knowledge", "知识")); // 主分区 - zones.Add(new ZoneAttr(201, "science", "科学科普", 36)); // 回答你的十万个为什么 - zones.Add(new ZoneAttr(124, "social_science", "社科·法律·心理", 36)); // 基于社会科学、法学、心理学展开或个人观点输出的知识视频 - zones.Add(new ZoneAttr(228, "humanity_history", "人文历史", 36)); // 看看古今人物,聊聊历史过往,品品文学典籍 - zones.Add(new ZoneAttr(207, "business", "财经商业", 36)); // 说金融市场,谈宏观经济,一起畅聊商业故事 - zones.Add(new ZoneAttr(208, "campus", "校园学习", 36)); // 老师很有趣,学生也有才,我们一起搞学习 - zones.Add(new ZoneAttr(209, "career", "职业职场", 36)); // 职业分享、升级指南,一起成为最有料的职场人 - zones.Add(new ZoneAttr(229, "design", "设计·创意", 36)); // 天马行空,创意设计,都在这里 - zones.Add(new ZoneAttr(122, "skill", "野生技能协会", 36)); // 技能党集合,是时候展示真正的技术了 + _zones.Add(new ZoneAttr(36, "knowledge", "知识")); // 主分区 + _zones.Add(new ZoneAttr(201, "science", "科学科普", 36)); // 回答你的十万个为什么 + _zones.Add(new ZoneAttr(124, "social_science", "社科·法律·心理", 36)); // 基于社会科学、法学、心理学展开或个人观点输出的知识视频 + _zones.Add(new ZoneAttr(228, "humanity_history", "人文历史", 36)); // 看看古今人物,聊聊历史过往,品品文学典籍 + _zones.Add(new ZoneAttr(207, "business", "财经商业", 36)); // 说金融市场,谈宏观经济,一起畅聊商业故事 + _zones.Add(new ZoneAttr(208, "campus", "校园学习", 36)); // 老师很有趣,学生也有才,我们一起搞学习 + _zones.Add(new ZoneAttr(209, "career", "职业职场", 36)); // 职业分享、升级指南,一起成为最有料的职场人 + _zones.Add(new ZoneAttr(229, "design", "设计·创意", 36)); // 天马行空,创意设计,都在这里 + _zones.Add(new ZoneAttr(122, "skill", "野生技能协会", 36)); // 技能党集合,是时候展示真正的技术了 //科技 - zones.Add(new ZoneAttr(188, "tech", "科技")); // 主分区 - zones.Add(new ZoneAttr(95, "digital", "数码", 188)); // 科技数码产品大全,一起来做发烧友 - zones.Add(new ZoneAttr(230, "application", "软件应用", 188)); // 超全软件应用指南 - zones.Add(new ZoneAttr(231, "computer_tech", "计算机技术", 188)); // 研究分析、教学演示、经验分享......有关计算机技术的都在这里 - zones.Add(new ZoneAttr(232, "industry", "科工机械", 188)); // 从小芯片到大工程,一起见证科工力量 - zones.Add(new ZoneAttr(233, "diy", "极客DIY", 188)); // 炫酷技能,极客文化,硬核技巧,准备好你的惊讶 + _zones.Add(new ZoneAttr(188, "tech", "科技")); // 主分区 + _zones.Add(new ZoneAttr(95, "digital", "数码", 188)); // 科技数码产品大全,一起来做发烧友 + _zones.Add(new ZoneAttr(230, "application", "软件应用", 188)); // 超全软件应用指南 + _zones.Add(new ZoneAttr(231, "computer_tech", "计算机技术", 188)); // 研究分析、教学演示、经验分享......有关计算机技术的都在这里 + _zones.Add(new ZoneAttr(232, "industry", "科工机械", 188)); // 从小芯片到大工程,一起见证科工力量 + _zones.Add(new ZoneAttr(233, "diy", "极客DIY", 188)); // 炫酷技能,极客文化,硬核技巧,准备好你的惊讶 //运动 - zones.Add(new ZoneAttr(234, "sports", "运动")); // 主分区 - zones.Add(new ZoneAttr(235, "basketball", "篮球", 234)); // 与篮球相关的视频,包括但不限于篮球赛事、教学、评述、剪辑、剧情等相关内容 - zones.Add(new ZoneAttr(249, "football", "足球", 234)); // 与足球相关的视频,包括但不限于足球赛事、教学、评述、剪辑、剧情等相关内容 - zones.Add(new ZoneAttr(164, "aerobics", "健身", 234)); // 与健身相关的视频,包括但不限于瑜伽、CrossFit、健美、力量举、普拉提、街健等相关内容 - zones.Add(new ZoneAttr(236, "athletic", "竞技体育", - 234)); // 与竞技体育相关的视频,包括但不限于乒乓、羽毛球、排球、赛车等竞技项目的赛事、评述、剪辑、剧情等相关内容 - zones.Add(new ZoneAttr(237, "culture", "运动文化", - 234)); // 与运动文化相关的视频,包络但不限于球鞋、球衣、球星卡等运动衍生品的分享、解读,体育产业的分析、科普等相关内容 - zones.Add(new ZoneAttr(238, "comprehensive", "运动综合", 234)); // 与运动综合相关的视频,包括但不限于钓鱼、骑行、滑板等日常运动分享、教学、Vlog等相关内容 + _zones.Add(new ZoneAttr(234, "sports", "运动")); // 主分区 + _zones.Add(new ZoneAttr(235, "basketball", "篮球", 234)); // 与篮球相关的视频,包括但不限于篮球赛事、教学、评述、剪辑、剧情等相关内容 + _zones.Add(new ZoneAttr(249, "football", "足球", 234)); // 与足球相关的视频,包括但不限于足球赛事、教学、评述、剪辑、剧情等相关内容 + _zones.Add(new ZoneAttr(164, "aerobics", "健身", 234)); // 与健身相关的视频,包括但不限于瑜伽、CrossFit、健美、力量举、普拉提、街健等相关内容 + _zones.Add(new ZoneAttr(236, "athletic", "竞技体育", 234)); // 与竞技体育相关的视频,包括但不限于乒乓、羽毛球、排球、赛车等竞技项目的赛事、评述、剪辑、剧情等相关内容 + _zones.Add(new ZoneAttr(237, "culture", "运动文化", 234)); // 与运动文化相关的视频,包络但不限于球鞋、球衣、球星卡等运动衍生品的分享、解读,体育产业的分析、科普等相关内容 + _zones.Add(new ZoneAttr(238, "comprehensive", "运动综合", 234)); // 与运动综合相关的视频,包括但不限于钓鱼、骑行、滑板等日常运动分享、教学、Vlog等相关内容 //汽车 - zones.Add(new ZoneAttr(223, "car", "汽车")); // 主分区 - zones.Add(new ZoneAttr(245, "racing", "赛车", 223)); // F1等汽车运动相关 - zones.Add(new ZoneAttr(246, "modifiedvehicle", "改装玩车", 223)); // 汽车文化及改装车相关内容,包括改装车、老车修复介绍、汽车聚会分享等内容 - zones.Add(new ZoneAttr(247, "newenergyvehicle", "新能源车", - 223)); // 新能源汽车相关内容,包括电动汽车、混合动力汽车等车型种类,包含不限于新车资讯、试驾体验、专业评测、技术解读、知识科普等内容 - zones.Add(new ZoneAttr(248, "touringcar", "房车", 223)); // 房车及营地相关内容,包括不限于产品介绍、驾驶体验、房车生活和房车旅行等内容 - zones.Add(new ZoneAttr(240, "motorcycle", "摩托车", 223)); // 骑士们集合啦 - zones.Add(new ZoneAttr(227, "strategy", "购车攻略", 223)); // 丰富详实的购车建议和新车体验 - zones.Add(new ZoneAttr(176, "life", "汽车生活", 223)); // 分享汽车及出行相关的生活体验类视频 + _zones.Add(new ZoneAttr(223, "car", "汽车")); // 主分区 + _zones.Add(new ZoneAttr(245, "racing", "赛车", 223)); // F1等汽车运动相关 + _zones.Add(new ZoneAttr(246, "modifiedvehicle", "改装玩车", 223)); // 汽车文化及改装车相关内容,包括改装车、老车修复介绍、汽车聚会分享等内容 + _zones.Add(new ZoneAttr(247, "newenergyvehicle", "新能源车", 223)); // 新能源汽车相关内容,包括电动汽车、混合动力汽车等车型种类,包含不限于新车资讯、试驾体验、专业评测、技术解读、知识科普等内容 + _zones.Add(new ZoneAttr(248, "touringcar", "房车", 223)); // 房车及营地相关内容,包括不限于产品介绍、驾驶体验、房车生活和房车旅行等内容 + _zones.Add(new ZoneAttr(240, "motorcycle", "摩托车", 223)); // 骑士们集合啦 + _zones.Add(new ZoneAttr(227, "strategy", "购车攻略", 223)); // 丰富详实的购车建议和新车体验 + _zones.Add(new ZoneAttr(176, "life", "汽车生活", 223)); // 分享汽车及出行相关的生活体验类视频 //生活 - zones.Add(new ZoneAttr(160, "life", "生活")); // 主分区 - zones.Add(new ZoneAttr(138, "funny", "搞笑", 160)); // 各种沙雕有趣的搞笑剪辑,挑战,表演,配音等视频 - zones.Add(new ZoneAttr(250, "travel", "Energy", 160)); // 为达到观光游览、休闲娱乐为目的的远途旅行、中近途户外生活、本地探店 - zones.Add(new ZoneAttr(251, "rurallife", "三农", 160)); // 分享美好农村生活 - zones.Add(new ZoneAttr(239, "home", "家居房产", 160)); // 与买房、装修、居家生活相关的分享 - zones.Add(new ZoneAttr(161, "handmake", "手工", 160)); // 手工制品的制作过程或成品展示、教程、测评类视频 - zones.Add(new ZoneAttr(162, "painting", "绘画", 160)); // 绘画过程或绘画教程,以及绘画相关的所有视频 - zones.Add(new ZoneAttr(21, "daily", "日常", 160)); // 记录日常生活,分享生活故事 + _zones.Add(new ZoneAttr(160, "life", "生活")); // 主分区 + _zones.Add(new ZoneAttr(138, "funny", "搞笑", 160)); // 各种沙雕有趣的搞笑剪辑,挑战,表演,配音等视频 + _zones.Add(new ZoneAttr(250, "travel", "Energy", 160)); // 为达到观光游览、休闲娱乐为目的的远途旅行、中近途户外生活、本地探店 + _zones.Add(new ZoneAttr(251, "rurallife", "三农", 160)); // 分享美好农村生活 + _zones.Add(new ZoneAttr(239, "home", "家居房产", 160)); // 与买房、装修、居家生活相关的分享 + _zones.Add(new ZoneAttr(161, "handmake", "手工", 160)); // 手工制品的制作过程或成品展示、教程、测评类视频 + _zones.Add(new ZoneAttr(162, "painting", "绘画", 160)); // 绘画过程或绘画教程,以及绘画相关的所有视频 + _zones.Add(new ZoneAttr(21, "daily", "日常", 160)); // 记录日常生活,分享生活故事 //美食 - zones.Add(new ZoneAttr(211, "food", "美食")); // 主分区 - zones.Add(new ZoneAttr(76, "make", "美食制作", 211)); // 学做人间美味,展示精湛厨艺 - zones.Add(new ZoneAttr(212, "detective", "美食侦探", 211)); // 寻找美味餐厅,发现街头美食 - zones.Add(new ZoneAttr(213, "measurement", "美食测评", 211)); // 吃货世界,品尝世间美味 - zones.Add(new ZoneAttr(214, "rural", "田园美食", 211)); // 品味乡野美食,寻找山与海的味道 - zones.Add(new ZoneAttr(215, "record", "美食记录", 211)); // 记录一日三餐,给生活添一点幸福感 + _zones.Add(new ZoneAttr(211, "food", "美食")); // 主分区 + _zones.Add(new ZoneAttr(76, "make", "美食制作", 211)); // 学做人间美味,展示精湛厨艺 + _zones.Add(new ZoneAttr(212, "detective", "美食侦探", 211)); // 寻找美味餐厅,发现街头美食 + _zones.Add(new ZoneAttr(213, "measurement", "美食测评", 211)); // 吃货世界,品尝世间美味 + _zones.Add(new ZoneAttr(214, "rural", "田园美食", 211)); // 品味乡野美食,寻找山与海的味道 + _zones.Add(new ZoneAttr(215, "record", "美食记录", 211)); // 记录一日三餐,给生活添一点幸福感 //动物圈 - zones.Add(new ZoneAttr(217, "animal", "动物圈")); // 主分区 - zones.Add(new ZoneAttr(218, "cat", "喵星人", 217)); // 喵喵喵喵喵 - zones.Add(new ZoneAttr(219, "dog", "汪星人", 217)); // 汪汪汪汪汪 - zones.Add(new ZoneAttr(220, "panda", "大熊猫", 217)); // 芝麻汤圆营业中 - zones.Add(new ZoneAttr(221, "wild_animal", "野生动物", 217)); // 内有“猛兽”出没 - zones.Add(new ZoneAttr(222, "reptiles", "爬宠", 217)); // 鳞甲有灵 - zones.Add(new ZoneAttr(75, "animal_composite", "动物综合", 217)); // 收录除上述子分区外,其余动物相关视频以及非动物主体或多个动物主体的动物相关延伸内容 + _zones.Add(new ZoneAttr(217, "animal", "动物圈")); // 主分区 + _zones.Add(new ZoneAttr(218, "cat", "喵星人", 217)); // 喵喵喵喵喵 + _zones.Add(new ZoneAttr(219, "dog", "汪星人", 217)); // 汪汪汪汪汪 + _zones.Add(new ZoneAttr(220, "panda", "大熊猫", 217)); // 芝麻汤圆营业中 + _zones.Add(new ZoneAttr(221, "wild_animal", "野生动物", 217)); // 内有“猛兽”出没 + _zones.Add(new ZoneAttr(222, "reptiles", "爬宠", 217)); // 鳞甲有灵 + _zones.Add(new ZoneAttr(75, "animal_composite", "动物综合", 217)); // 收录除上述子分区外,其余动物相关视频以及非动物主体或多个动物主体的动物相关延伸内容 //鬼畜 - zones.Add(new ZoneAttr(119, "kichiku", "鬼畜")); // 主分区 - zones.Add(new ZoneAttr(22, "guide", "鬼畜调教", 119)); // 使用素材在音频、画面上做一定处理,达到与BGM一定的同步感 - zones.Add(new ZoneAttr(26, "mad", "音MAD", 119)); // 使用素材音频进行一定的二次创作来达到还原原曲的非商业性质稿件 - zones.Add(new ZoneAttr(126, "manual_vocaloid", "人力VOCALOID", - 119)); // 将人物或者角色的无伴奏素材进行人工调音,使其就像VOCALOID一样歌唱的技术 - zones.Add(new ZoneAttr(216, "theatre", "鬼畜剧场", 119)); // 使用素材进行人工剪辑编排的有剧情的作品 - zones.Add(new ZoneAttr(127, "course", "教程演示", 119)); // 鬼畜相关的教程演示 + _zones.Add(new ZoneAttr(119, "kichiku", "鬼畜")); // 主分区 + _zones.Add(new ZoneAttr(22, "guide", "鬼畜调教", 119)); // 使用素材在音频、画面上做一定处理,达到与BGM一定的同步感 + _zones.Add(new ZoneAttr(26, "mad", "音MAD", 119)); // 使用素材音频进行一定的二次创作来达到还原原曲的非商业性质稿件 + _zones.Add(new ZoneAttr(126, "manual_vocaloid", "人力VOCALOID", 119)); // 将人物或者角色的无伴奏素材进行人工调音,使其就像VOCALOID一样歌唱的技术 + _zones.Add(new ZoneAttr(216, "theatre", "鬼畜剧场", 119)); // 使用素材进行人工剪辑编排的有剧情的作品 + _zones.Add(new ZoneAttr(127, "course", "教程演示", 119)); // 鬼畜相关的教程演示 //时尚 - zones.Add(new ZoneAttr(155, "fashion", "时尚")); // 主分区 - zones.Add(new ZoneAttr(157, "makeup", "美妆护肤", 155)); // 彩妆护肤、美甲美发、仿妆、医美相关内容分享或产品测评 - zones.Add(new ZoneAttr(252, "cos", "仿妆cos", 155)); // 对二次元、三次元人物角色进行模仿、还原、展示、演绎的内容 - zones.Add(new ZoneAttr(158, "clothing", "穿搭", 155)); // 穿搭风格、穿搭技巧的展示分享,涵盖衣服、鞋靴、箱包配件、配饰(帽子、钟表、珠宝首饰)等 - zones.Add(new ZoneAttr(159, "trend", "时尚潮流", 155)); // 时尚街拍、时装周、时尚大片,时尚品牌、潮流等行业相关记录及知识科普 + _zones.Add(new ZoneAttr(155, "fashion", "时尚")); // 主分区 + _zones.Add(new ZoneAttr(157, "makeup", "美妆护肤", 155)); // 彩妆护肤、美甲美发、仿妆、医美相关内容分享或产品测评 + _zones.Add(new ZoneAttr(252, "cos", "仿妆cos", 155)); // 对二次元、三次元人物角色进行模仿、还原、展示、演绎的内容 + _zones.Add(new ZoneAttr(158, "clothing", "穿搭", 155)); // 穿搭风格、穿搭技巧的展示分享,涵盖衣服、鞋靴、箱包配件、配饰(帽子、钟表、珠宝首饰)等 + _zones.Add(new ZoneAttr(159, "trend", "时尚潮流", 155)); // 时尚街拍、时装周、时尚大片,时尚品牌、潮流等行业相关记录及知识科普 //资讯 - zones.Add(new ZoneAttr(202, "information", "资讯")); // 主分区 - zones.Add(new ZoneAttr(203, "hotspot", "热点", 202)); // 全民关注的时政热门资讯 - zones.Add(new ZoneAttr(204, "global", "环球", 202)); // 全球范围内发生的具有重大影响力的事件动态 - zones.Add(new ZoneAttr(205, "social", "社会", 202)); // 日常生活的社会事件、社会问题、社会风貌的报道 - zones.Add(new ZoneAttr(206, "multiple", "综合", 202)); // 除上述领域外其它垂直领域的综合资讯 + _zones.Add(new ZoneAttr(202, "information", "资讯")); // 主分区 + _zones.Add(new ZoneAttr(203, "hotspot", "热点", 202)); // 全民关注的时政热门资讯 + _zones.Add(new ZoneAttr(204, "global", "环球", 202)); // 全球范围内发生的具有重大影响力的事件动态 + _zones.Add(new ZoneAttr(205, "social", "社会", 202)); // 日常生活的社会事件、社会问题、社会风貌的报道 + _zones.Add(new ZoneAttr(206, "multiple", "综合", 202)); // 除上述领域外其它垂直领域的综合资讯 //娱乐 - zones.Add(new ZoneAttr(5, "ent", "娱乐")); // 主分区 - zones.Add(new ZoneAttr(71, "variety", "综艺", 5)); // 所有综艺相关,全部一手掌握! - zones.Add(new ZoneAttr(241, "talker", "娱乐杂谈", 5)); // 娱乐人物解读、娱乐热点点评、娱乐行业分析 - zones.Add(new ZoneAttr(242, "fans", "粉丝创作", 5)); // 粉丝向创作视频 - zones.Add(new ZoneAttr(137, "celebrity", "明星综合", 5)); // 娱乐圈动态、明星资讯相关 + _zones.Add(new ZoneAttr(5, "ent", "娱乐")); // 主分区 + _zones.Add(new ZoneAttr(71, "variety", "综艺", 5)); // 所有综艺相关,全部一手掌握! + _zones.Add(new ZoneAttr(241, "talker", "娱乐杂谈", 5)); // 娱乐人物解读、娱乐热点点评、娱乐行业分析 + _zones.Add(new ZoneAttr(242, "fans", "粉丝创作", 5)); // 粉丝向创作视频 + _zones.Add(new ZoneAttr(137, "celebrity", "明星综合", 5)); // 娱乐圈动态、明星资讯相关 //影视 - zones.Add(new ZoneAttr(181, "cinephile", "影视")); // 主分区 - zones.Add(new ZoneAttr(182, "cinecism", "影视杂谈", 181)); // 影视评论、解说、吐槽、科普等 - zones.Add(new ZoneAttr(183, "montage", "影视剪辑", 181)); // 对影视素材进行剪辑再创作的视频 - zones.Add(new ZoneAttr(85, "shortfilm", "小剧场", 181)); // 有场景、有剧情的演绎类内容 - zones.Add(new ZoneAttr(184, "trailer_info", "预告·资讯", 181)); // 影视类相关资讯,预告,花絮等视频 + _zones.Add(new ZoneAttr(181, "cinephile", "影视")); // 主分区 + _zones.Add(new ZoneAttr(182, "cinecism", "影视杂谈", 181)); // 影视评论、解说、吐槽、科普等 + _zones.Add(new ZoneAttr(183, "montage", "影视剪辑", 181)); // 对影视素材进行剪辑再创作的视频 + _zones.Add(new ZoneAttr(85, "shortfilm", "小剧场", 181)); // 有场景、有剧情的演绎类内容 + _zones.Add(new ZoneAttr(184, "trailer_info", "预告·资讯", 181)); // 影视类相关资讯,预告,花絮等视频 //纪录片 - zones.Add(new ZoneAttr(177, "documentary", "纪录片")); // 主分区 - zones.Add(new ZoneAttr(37, "history", "人文·历史", 177)); // - zones.Add(new ZoneAttr(178, "science", "科学·探索·自然", 177)); // - zones.Add(new ZoneAttr(179, "military", "军事", 177)); // - zones.Add(new ZoneAttr(180, "travel", "社会·美食·旅行", 177)); // + _zones.Add(new ZoneAttr(177, "documentary", "纪录片")); // 主分区 + _zones.Add(new ZoneAttr(37, "history", "人文·历史", 177)); // + _zones.Add(new ZoneAttr(178, "science", "科学·探索·自然", 177)); // + _zones.Add(new ZoneAttr(179, "military", "军事", 177)); // + _zones.Add(new ZoneAttr(180, "travel", "社会·美食·旅行", 177)); // //电影 - zones.Add(new ZoneAttr(23, "movie", "电影")); // 主分区 - zones.Add(new ZoneAttr(147, "chinese", "华语电影", 23)); // - zones.Add(new ZoneAttr(145, "west", "欧美电影", 23)); // - zones.Add(new ZoneAttr(146, "japan", "日本电影", 23)); // - zones.Add(new ZoneAttr(83, "movie", "其他国家", 23)); // + _zones.Add(new ZoneAttr(23, "movie", "电影")); // 主分区 + _zones.Add(new ZoneAttr(147, "chinese", "华语电影", 23)); // + _zones.Add(new ZoneAttr(145, "west", "欧美电影", 23)); // + _zones.Add(new ZoneAttr(146, "japan", "日本电影", 23)); // + _zones.Add(new ZoneAttr(83, "movie", "其他国家", 23)); // //电视剧 - zones.Add(new ZoneAttr(11, "tv", "电视剧")); // 主分区 - zones.Add(new ZoneAttr(185, "mainland", "国产剧", 11)); // - zones.Add(new ZoneAttr(187, "overseas", "海外剧", 11)); // + _zones.Add(new ZoneAttr(11, "tv", "电视剧")); // 主分区 + _zones.Add(new ZoneAttr(185, "mainland", "国产剧", 11)); // + _zones.Add(new ZoneAttr(187, "overseas", "海外剧", 11)); // } } \ No newline at end of file diff --git a/DownKyi.Core/BiliApi/Zone/VideoZoneIcon.cs b/DownKyi.Core/BiliApi/Zone/VideoZoneIcon.cs index 15c3c32..b5c3853 100644 --- a/DownKyi.Core/BiliApi/Zone/VideoZoneIcon.cs +++ b/DownKyi.Core/BiliApi/Zone/VideoZoneIcon.cs @@ -5,7 +5,7 @@ /// public class VideoZoneIcon { - private static VideoZoneIcon instance; + private static VideoZoneIcon? _instance; /// /// 获取VideoZoneIcon实例 @@ -13,12 +13,7 @@ public class VideoZoneIcon /// public static VideoZoneIcon Instance() { - if (instance == null) - { - instance = new VideoZoneIcon(); - } - - return instance; + return _instance ??= new VideoZoneIcon(); } /// @@ -35,55 +30,32 @@ public class VideoZoneIcon /// public string GetZoneImageKey(int tid) { - switch (tid) + return tid switch { // 课堂 - case -10: - return "Zone.cheeseDrawingImage"; - case 1: - return "Zone.dougaDrawingImage"; - case 13: - return "Zone.animeDrawingImage"; - case 167: - return "Zone.guochuangDrawingImage"; - case 3: - return "Zone.musicDrawingImage"; - case 129: - return "Zone.danceDrawingImage"; - case 4: - return "Zone.gameDrawingImage"; - case 36: - return "Zone.techDrawingImage"; - case 188: - return "Zone.digitalDrawingImage"; - case 234: - return "Zone.sportsDrawingImage"; - case 223: - return "Zone.carDrawingImage"; - case 160: - return "Zone.lifeDrawingImage"; - case 211: - return "Zone.foodDrawingImage"; - case 217: - return "Zone.animalDrawingImage"; - case 119: - return "Zone.kichikuDrawingImage"; - case 155: - return "Zone.fashionDrawingImage"; - case 202: - return "Zone.informationDrawingImage"; - case 5: - return "Zone.entDrawingImage"; - case 181: - return "Zone.cinephileDrawingImage"; - case 177: - return "Zone.documentaryDrawingImage"; - case 23: - return "Zone.movieDrawingImage"; - case 11: - return "Zone.teleplayDrawingImage"; - default: - return "videoUpDrawingImage"; - } + -10 => "Zone.cheeseDrawingImage", + 1 => "Zone.dougaDrawingImage", + 3 => "Zone.musicDrawingImage", + 4 => "Zone.gameDrawingImage", + 5 => "Zone.entDrawingImage", + 11 => "Zone.teleplayDrawingImage", + 13 => "Zone.animeDrawingImage", + 23 => "Zone.movieDrawingImage", + 36 => "Zone.techDrawingImage", + 119 => "Zone.kichikuDrawingImage", + 129 => "Zone.danceDrawingImage", + 155 => "Zone.fashionDrawingImage", + 160 => "Zone.lifeDrawingImage", + 167 => "Zone.guochuangDrawingImage", + 177 => "Zone.documentaryDrawingImage", + 181 => "Zone.cinephileDrawingImage", + 188 => "Zone.digitalDrawingImage", + 202 => "Zone.informationDrawingImage", + 211 => "Zone.foodDrawingImage", + 217 => "Zone.animalDrawingImage", + 223 => "Zone.carDrawingImage", + 234 => "Zone.sportsDrawingImage", + _ => "videoUpDrawingImage" + }; } } \ No newline at end of file diff --git a/DownKyi.Core/Danmaku2Ass/Bilibili.cs b/DownKyi.Core/Danmaku2Ass/Bilibili.cs index 2f525d1..26e15f8 100644 --- a/DownKyi.Core/Danmaku2Ass/Bilibili.cs +++ b/DownKyi.Core/Danmaku2Ass/Bilibili.cs @@ -114,7 +114,7 @@ public class Bilibili } // 弹幕预处理 - Producer producer = new Producer(config, danmakus); + var producer = new Producer(config, danmakus); producer.StartHandle(); // 字幕生成 diff --git a/DownKyi.Core/Danmaku2Ass/Collision.cs b/DownKyi.Core/Danmaku2Ass/Collision.cs index 4e5c966..e06505b 100644 --- a/DownKyi.Core/Danmaku2Ass/Collision.cs +++ b/DownKyi.Core/Danmaku2Ass/Collision.cs @@ -17,7 +17,7 @@ public class Collision private List Leaves() { var ret = new List(lineCount); - for (int i = 0; i < lineCount; i++) ret.Add(0); + for (var i = 0; i < lineCount; i++) ret.Add(0); return ret; } @@ -29,10 +29,10 @@ public class Collision /// public Tuple Detect(Display display) { - List beyonds = new List(); - for (int i = 0; i < leaves.Count; i++) + var beyonds = new List(); + for (var i = 0; i < leaves.Count; i++) { - float beyond = display.Danmaku.Start - leaves[i]; + var beyond = display.Danmaku.Start - leaves[i]; // 某一行有足够空间,直接返回行号和 0 偏移 if (beyond >= 0) { @@ -43,9 +43,9 @@ public class Collision } // 所有行都没有空间了,那么找出哪一行能在最短时间内让出空间 - float soon = beyonds.Max(); - int lineIndex = beyonds.IndexOf(soon); - float offset = -soon; + var soon = beyonds.Max(); + var lineIndex = beyonds.IndexOf(soon); + var offset = -soon; return Tuple.Create(lineIndex, offset); } diff --git a/DownKyi.Core/Danmaku2Ass/Creater.cs b/DownKyi.Core/Danmaku2Ass/Creater.cs index fe739ef..d8c863b 100644 --- a/DownKyi.Core/Danmaku2Ass/Creater.cs +++ b/DownKyi.Core/Danmaku2Ass/Creater.cs @@ -22,14 +22,14 @@ public class Creater { var scroll = new Collision(Config.LineCount); var stayed = new Collision(Config.LineCount); - Dictionary collisions = new Dictionary + var collisions = new Dictionary { { "scroll", scroll }, { "top", stayed }, { "bottom", stayed } }; - List subtitles = new List(); + var subtitles = new List(); foreach (var danmaku in Danmakus) { // 丢弃不支持的 @@ -41,9 +41,7 @@ public class Creater // 创建显示方式对象 var display = Display.Factory(Config, danmaku); var collision = collisions[danmaku.Style]; - var detect = collision.Detect(display); - int lineIndex = detect.Item1; - float waitingOffset = detect.Item2; + var (lineIndex, waitingOffset) = collision.Detect(display); // 超过容忍的偏移量,丢弃掉此条弹幕 if (waitingOffset > Config.DropOffset) @@ -56,8 +54,8 @@ public class Creater collision.Update(display.Leave, lineIndex, waitingOffset); // 再加上自定义偏移 - float offset = waitingOffset + Config.CustomOffset; - Subtitle subtitle = new Subtitle(danmaku, display, offset); + var offset = waitingOffset + Config.CustomOffset; + var subtitle = new Subtitle(danmaku, display, offset); subtitles.Add(subtitle); } @@ -67,18 +65,14 @@ public class Creater protected string SetText() { - string header = Config.HeaderTemplate + var header = Config.HeaderTemplate .Replace("{title}", Config.Title) .Replace("{width}", Config.ScreenWidth.ToString()) .Replace("{height}", Config.ScreenHeight.ToString()) .Replace("{fontname}", Config.FontName) .Replace("{fontsize}", Config.BaseFontSize.ToString()); - string events = string.Empty; - foreach (var subtitle in Subtitles) - { - events += "\n" + subtitle.Text; - } + var events = Subtitles.Aggregate(string.Empty, (current, subtitle) => current + "\n" + subtitle.Text); return header + events; } diff --git a/DownKyi.Core/Danmaku2Ass/Display.cs b/DownKyi.Core/Danmaku2Ass/Display.cs index 84440ea..6d892ef 100644 --- a/DownKyi.Core/Danmaku2Ass/Display.cs +++ b/DownKyi.Core/Danmaku2Ass/Display.cs @@ -52,7 +52,7 @@ public class Display /// public static Display Factory(Config config, Danmaku danmaku) { - Dictionary dict = new Dictionary + var dict = new Dictionary { { "scroll", new ScrollDisplay(config, danmaku) }, { "top", new TopDisplay(config, danmaku) }, @@ -92,18 +92,9 @@ public class Display /// protected int SetMaxLength() { - string[] lines = Danmaku.Content.Split('\n'); - int maxLength = 0; - foreach (string line in lines) - { - int length = Utils.DisplayLength(line); - if (maxLength < length) - { - maxLength = length; - } - } + var lines = Danmaku.Content.Split('\n'); - return maxLength; + return lines.Select(Utils.DisplayLength).Prepend(0).Max(); } /// @@ -122,7 +113,7 @@ public class Display /// protected int SetHeight() { - int lineCount = Danmaku.Content.Split('\n').Length; + var lineCount = Danmaku.Content.Split('\n').Length; return lineCount * FontSize; } @@ -133,7 +124,7 @@ public class Display /// protected virtual Tuple SetHorizontal() { - int x = (int)Math.Floor(Config.ScreenWidth / 2.0); + var x = (int)Math.Floor(Config.ScreenWidth / 2.0); return Tuple.Create(x, x); } @@ -144,7 +135,7 @@ public class Display /// protected virtual Tuple SetVertical() { - int y = (int)Math.Floor(Config.ScreenHeight / 2.0); + var y = (int)Math.Floor(Config.ScreenHeight / 2.0); return Tuple.Create(y, y); } @@ -154,7 +145,7 @@ public class Display /// protected virtual int SetDuration() { - int baseDuration = 3 + Config.TuneDuration; + var baseDuration = 3 + Config.TuneDuration; if (baseDuration <= 0) { baseDuration = 0; @@ -217,7 +208,7 @@ public class TopDisplay : Display protected override Tuple SetVertical() { // 这里 y 坐标为 0 就是最顶行了 - int y = LineIndex * Config.BaseFontSize; + var y = LineIndex * Config.BaseFontSize; return Tuple.Create(y, y); } } @@ -239,7 +230,7 @@ public class BottomDisplay : Display protected override Tuple SetVertical() { // 要让字幕不超出底部,减去高度 - int y = Config.ScreenHeight - (LineIndex * Config.BaseFontSize) - Height; + var y = Config.ScreenHeight - (LineIndex * Config.BaseFontSize) - Height; // 再减去自定义的底部边距 y -= Config.BottomMargin; return Tuple.Create(y, y); @@ -284,17 +275,17 @@ public class ScrollDisplay : Display /// protected override Tuple SetHorizontal() { - int x1 = Config.ScreenWidth + (int)Math.Floor(Width / 2.0); - int x2 = 0 - (int)Math.Floor(Width / 2.0); + var x1 = Config.ScreenWidth + (int)Math.Floor(Width / 2.0); + var x2 = 0 - (int)Math.Floor(Width / 2.0); return Tuple.Create(x1, x2); } protected override Tuple SetVertical() { - int baseFontSize = Config.BaseFontSize; + var baseFontSize = Config.BaseFontSize; // 垂直位置,按基准字体大小算每一行的高度 - int y = (LineIndex + 1) * baseFontSize; + var y = (LineIndex + 1) * baseFontSize; // 个别弹幕可能字体比基准要大,所以最上的一行还要避免挤出顶部屏幕 // 坐标不能小于字体大小 @@ -312,7 +303,7 @@ public class ScrollDisplay : Display /// protected int SetDistance() { - Tuple x = Horizontal; + var x = Horizontal; return x.Item1 - x.Item2; } @@ -324,7 +315,7 @@ public class ScrollDisplay : Display { // 基准时间,就是每个字的移动时间 // 12 秒加上用户自定义的微调 - int baseDuration = 12 + Config.TuneDuration; + var baseDuration = 12 + Config.TuneDuration; if (baseDuration <= 0) { baseDuration = 1; @@ -350,7 +341,7 @@ public class ScrollDisplay : Display /// public int AsyncDuration() { - int baseDuration = 6 + Config.TuneDuration; + var baseDuration = 6 + Config.TuneDuration; if (baseDuration <= 0) { baseDuration = 0; @@ -385,9 +376,9 @@ public class ScrollDisplay : Display /// protected override int SetDuration() { - string methodName = Config.LayoutAlgorithm.Substring(0, 1).ToUpper() + Config.LayoutAlgorithm.Substring(1); + var methodName = Config.LayoutAlgorithm.Substring(0, 1).ToUpper() + Config.LayoutAlgorithm.Substring(1); methodName += "Duration"; - MethodInfo method = typeof(ScrollDisplay).GetMethod(methodName); + var method = typeof(ScrollDisplay).GetMethod(methodName); if (method != null) { return (int)method.Invoke(this, null); @@ -405,7 +396,7 @@ public class ScrollDisplay : Display // 对于滚动样式弹幕来说,就是最后一个字符离开最右边缘的时间 // 坐标是字幕中点,在屏幕外和内各有半个字幕宽度 // 也就是跑过一个字幕宽度的路程 - float duration = Width / Speed; + var duration = Width / Speed; return (int)(Danmaku.Start + duration); } } \ No newline at end of file diff --git a/DownKyi.Core/Danmaku2Ass/Filter.cs b/DownKyi.Core/Danmaku2Ass/Filter.cs index 06cd011..e7ff713 100644 --- a/DownKyi.Core/Danmaku2Ass/Filter.cs +++ b/DownKyi.Core/Danmaku2Ass/Filter.cs @@ -18,18 +18,7 @@ public class TopFilter : Filter { public override List DoFilter(List danmakus) { - List keep = new List(); - foreach (var danmaku in danmakus) - { - if (danmaku.Style == "top") - { - continue; - } - - keep.Add(danmaku); - } - - return keep; + return danmakus.Where(danmaku => danmaku.Style != "top").ToList(); } } @@ -40,18 +29,7 @@ public class BottomFilter : Filter { public override List DoFilter(List danmakus) { - List keep = new List(); - foreach (var danmaku in danmakus) - { - if (danmaku.Style == "bottom") - { - continue; - } - - keep.Add(danmaku); - } - - return keep; + return danmakus.Where(danmaku => danmaku.Style != "bottom").ToList(); } } @@ -62,18 +40,7 @@ public class ScrollFilter : Filter { public override List DoFilter(List danmakus) { - List keep = new List(); - foreach (var danmaku in danmakus) - { - if (danmaku.Style == "scroll") - { - continue; - } - - keep.Add(danmaku); - } - - return keep; + return danmakus.Where(danmaku => danmaku.Style != "scroll").ToList(); } } diff --git a/DownKyi.Core/Danmaku2Ass/Producer.cs b/DownKyi.Core/Danmaku2Ass/Producer.cs index 9d05017..6623269 100644 --- a/DownKyi.Core/Danmaku2Ass/Producer.cs +++ b/DownKyi.Core/Danmaku2Ass/Producer.cs @@ -45,7 +45,7 @@ public class Producer public void ApplyFilter() { - Dictionary filterDetail = new Dictionary() + var filterDetail = new Dictionary() { { "top_filter", 0 }, { "bottom_filter", 0 }, @@ -53,10 +53,10 @@ public class Producer //{ "custom_filter",0} }; - List danmakus = Danmakus; + var danmakus = Danmakus; //string[] orders = { "top_filter", "bottom_filter", "scroll_filter", "custom_filter" }; string[] orders = { "top_filter", "bottom_filter", "scroll_filter" }; - foreach (string name in orders) + foreach (var name in orders) { Filter filter; try @@ -69,7 +69,7 @@ public class Producer continue; } - int count = danmakus.Count; + var count = danmakus.Count; danmakus = filter.DoFilter(danmakus); filterDetail[name] = count - danmakus.Count; } @@ -80,16 +80,12 @@ public class Producer public Dictionary Report() { - int blockedCount = 0; - foreach (int count in FilterDetail.Values) - { - blockedCount += count; - } + var blockedCount = FilterDetail.Values.Sum(); - int passedCount = KeepedDanmakus.Count; - int totalCount = blockedCount + passedCount; + var passedCount = KeepedDanmakus.Count; + var totalCount = blockedCount + passedCount; - Dictionary ret = new Dictionary + var ret = new Dictionary { { "blocked", blockedCount }, { "passed", passedCount }, diff --git a/DownKyi.Core/Danmaku2Ass/Studio.cs b/DownKyi.Core/Danmaku2Ass/Studio.cs index b53c43f..bf48bbf 100644 --- a/DownKyi.Core/Danmaku2Ass/Studio.cs +++ b/DownKyi.Core/Danmaku2Ass/Studio.cs @@ -40,7 +40,7 @@ public class Studio /// protected int SetKeepedCount() { - return Creater.Subtitles.Count(); + return Creater.Subtitles.Count; } /// @@ -74,7 +74,7 @@ public class Studio public Dictionary Report() { - return new Dictionary() + return new Dictionary { { "total", Danmakus.Count }, { "droped", DropedCount }, diff --git a/DownKyi.Core/Danmaku2Ass/Subtitle.cs b/DownKyi.Core/Danmaku2Ass/Subtitle.cs index bfd80f5..80942d1 100644 --- a/DownKyi.Core/Danmaku2Ass/Subtitle.cs +++ b/DownKyi.Core/Danmaku2Ass/Subtitle.cs @@ -103,47 +103,30 @@ public class Subtitle //return "\\3c&HFFFFFF"; return "\\3c&H000000"; } - else - { - return "\\3c&H000000"; - } + + return "\\3c&H000000"; //return ""; } protected string SetFontSizeMarkup() { - if (Display.IsScaled) - { - return $"\\fs{Display.FontSize}"; - } - - return ""; + return Display.IsScaled ? $"\\fs{Display.FontSize}" : ""; } protected string SetStyleMarkup() { - if (Danmaku.Style == "scroll") - { - return $"\\move({Position["x1"]}, {Position["y1"]}, {Position["x2"]}, {Position["y2"]})"; - } - - return $"\\a6\\pos({Position["x1"]}, {Position["y1"]})"; + return Danmaku.Style == "scroll" ? $"\\move({Position["x1"]}, {Position["y1"]}, {Position["x2"]}, {Position["y2"]})" : $"\\a6\\pos({Position["x1"]}, {Position["y1"]})"; } protected string SetLayerMarkup() { - if (Danmaku.Style != "scroll") - { - return "-2"; - } - - return "-1"; + return Danmaku.Style != "scroll" ? "-2" : "-1"; } protected string SetContentMarkup() { - string markup = StyleMarkup + ColorMarkup + BorderMarkup + FontSizeMarkup; - string content = Utils.CorrectTypos(Danmaku.Content); + var markup = StyleMarkup + ColorMarkup + BorderMarkup + FontSizeMarkup; + var content = Utils.CorrectTypos(Danmaku.Content); return $"{{{markup}}}{content}"; } diff --git a/DownKyi.Core/Danmaku2Ass/Utils.cs b/DownKyi.Core/Danmaku2Ass/Utils.cs index df45a86..3cf043d 100644 --- a/DownKyi.Core/Danmaku2Ass/Utils.cs +++ b/DownKyi.Core/Danmaku2Ass/Utils.cs @@ -50,17 +50,17 @@ internal static class Utils return "0:00:00.00"; } - int i = (int)Math.Floor(seconds / 1.0); - int dec = (int)(Math.Round(seconds % 1.0f, 2) * 100); + var i = (int)Math.Floor(seconds / 1.0); + var dec = (int)(Math.Round(seconds % 1.0f, 2) * 100); if (dec >= 100) { dec = 99; } - int min = (int)Math.Floor(i / 60.0); - int second = (int)(i % 60.0f); + var min = (int)Math.Floor(i / 60.0); + var second = (int)(i % 60.0f); - int hour = (int)Math.Floor(min / 60.0); + var hour = (int)Math.Floor(min / 60.0); min = (int)Math.Floor(min % 60.0f); return $"{hour:D}:{min:D2}:{second:D2}.{dec:D2}"; @@ -73,15 +73,9 @@ internal static class Utils /// public static float Hms2second(string hms) { - string[] numbers = hms.Split(':'); - float seconds = 0; + var numbers = hms.Split(':'); - for (int i = 0; i < numbers.Length; i++) - { - seconds += (float)(float.Parse(numbers[numbers.Length - i - 1]) * Math.Pow(60, i)); - } - - return seconds; + return numbers.Select((t, i) => (float)(float.Parse(numbers[numbers.Length - i - 1]) * Math.Pow(60, i))).Sum(); } /// @@ -92,14 +86,9 @@ internal static class Utils /// public static float Xhms2second(string xhms) { - string[] args = xhms.Replace("+", " +").Replace("-", " -").Split(' '); - float result = 0; - foreach (string hms in args) - { - result += Hms2second(hms); - } + var args = xhms.Replace("+", " +").Replace("-", " -").Split(' '); - return result; + return args.Sum(Hms2second); } /// @@ -110,7 +99,6 @@ internal static class Utils public static string Int2rgb(int integer) { return integer.ToString("X").PadLeft(6, '0'); - ; } /// @@ -120,8 +108,8 @@ internal static class Utils /// public static string Int2bgr(int integer) { - string rgb = Int2rgb(integer); - string bgr = rgb.Substring(4, 2) + rgb.Substring(2, 2) + rgb.Substring(0, 2); + var rgb = Int2rgb(integer); + var bgr = rgb.Substring(4, 2) + rgb.Substring(2, 2) + rgb.Substring(0, 2); return bgr; } @@ -132,7 +120,7 @@ internal static class Utils /// public static float[] Int2hls(int integer) { - string rgb = Int2rgb(integer); + var rgb = Int2rgb(integer); int[] rgb_decimals = { 0, 0, 0 }; rgb_decimals[0] = int.Parse(rgb.Substring(0, 2), NumberStyles.HexNumber); rgb_decimals[1] = int.Parse(rgb.Substring(2, 2), NumberStyles.HexNumber); @@ -142,7 +130,7 @@ internal static class Utils rgb_coordinates[0] = (int)Math.Floor(rgb_decimals[0] / 255.0); rgb_coordinates[1] = (int)Math.Floor(rgb_decimals[1] / 255.0); rgb_coordinates[2] = (int)Math.Floor(rgb_decimals[2] / 255.0); - float[] hls_corrdinates = Rgb2hls(rgb_coordinates); + var hls_corrdinates = Rgb2hls(rgb_coordinates); float[] hls = { 0, 0, 0 }; hls[0] = hls_corrdinates[0] * 360; @@ -162,8 +150,8 @@ internal static class Utils private static float[] Rgb2hls(int[] rgb) { float[] hls = { 0, 0, 0 }; - int maxc = rgb.Max(); - int minc = rgb.Min(); + var maxc = rgb.Max(); + var minc = rgb.Min(); hls[1] = (minc + maxc) / 2.0f; if (minc == maxc) { @@ -195,7 +183,7 @@ internal static class Utils hls[0] = 4.0f + gc - rc; } - hls[0] = (hls[0] / 6.0f) % 1.0f; + hls[0] = hls[0] / 6.0f % 1.0f; return hls; } @@ -211,23 +199,20 @@ internal static class Utils return true; } - float[] hls = Int2hls(integer); - float hue = hls[0]; - float lightness = hls[1]; + var hls = Int2hls(integer); + var hue = hls[0]; + var lightness = hls[1]; - // HSL 色轮见 - // http://zh.wikipedia.org/zh-cn/HSL和HSV色彩空间 - // 以下的数值都是我的主观判断认为是暗色 - if ((hue > 30 && hue < 210) && lightness < 33) + switch (hue) { - return true; + // HSL 色轮见 + // http://zh.wikipedia.org/zh-cn/HSL和HSV色彩空间 + // 以下的数值都是我的主观判断认为是暗色 + case > 30 and < 210 when lightness < 33: + case < 30 or > 210 when lightness < 66: + return true; + default: + return false; } - - if ((hue < 30 || hue > 210) && lightness < 66) - { - return true; - } - - return false; } } \ No newline at end of file diff --git a/DownKyi.Core/DownKyi.Core.csproj b/DownKyi.Core/DownKyi.Core.csproj index 3cb67b2..93ec1e7 100644 --- a/DownKyi.Core/DownKyi.Core.csproj +++ b/DownKyi.Core/DownKyi.Core.csproj @@ -7,13 +7,13 @@ $([System.Runtime.InteropServices.RuntimeInformation]::RuntimeIdentifier) - - + + - + - + diff --git a/DownKyi.Core/Downloader/MultiThreadDownloader.cs b/DownKyi.Core/Downloader/MultiThreadDownloader.cs deleted file mode 100644 index 8d33614..0000000 --- a/DownKyi.Core/Downloader/MultiThreadDownloader.cs +++ /dev/null @@ -1,448 +0,0 @@ -using System.ComponentModel; -using System.Net; - -namespace DownKyi.Core.Downloader; - -/// -/// 文件合并改变事件 -/// -/// -/// -public delegate void FileMergeProgressChangedEventHandler(object sender, int e); - -/// -/// 多线程下载器 -/// -public class MultiThreadDownloader -{ - #region 属性 - - private string _url; - private bool _rangeAllowed; - private readonly HttpWebRequest _request; - - private Action _requestConfigure = req => - req.UserAgent = - "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.122 Safari/537.36"; - - #endregion 属性 - - #region 公共属性 - - /// - /// RangeAllowed - /// - public bool RangeAllowed - { - get => _rangeAllowed; - set => _rangeAllowed = value; - } - - /// - /// 临时文件夹 - /// - public string TempFileDirectory { get; set; } - - /// - /// url地址 - /// - public string Url - { - get => _url; - set => _url = value; - } - - /// - /// 第几部分 - /// - public int NumberOfParts { get; set; } - - /// - /// 已接收字节数 - /// - public long TotalBytesReceived - { - get - { - try - { - lock (this) - { - return PartialDownloaderList.Where(t => t != null).Sum(t => t.TotalBytesRead); - } - } - catch - { - return 0; - } - } - } - - /// - /// 总进度 - /// - public float TotalProgress { get; private set; } - - /// - /// 文件大小 - /// - public long Size { get; private set; } - - /// - /// 下载速度 - /// - public float TotalSpeedInBytes - { - get - { - lock (this) - { - return PartialDownloaderList.Sum(t => t.SpeedInBytes); - } - } - } - - /// - /// 下载块 - /// - public List PartialDownloaderList { get; } - - /// - /// 文件路径 - /// - public string FilePath { get; set; } - - #endregion 公共属性 - - #region 变量 - - /// - /// 总下载进度更新事件 - /// - public event EventHandler TotalProgressChanged; - - /// - /// 文件合并完成事件 - /// - public event EventHandler FileMergedComplete; - - /// - /// 文件合并事件 - /// - public event FileMergeProgressChangedEventHandler FileMergeProgressChanged; - - private readonly AsyncOperation _aop; - - #endregion 变量 - - #region 下载管理器 - - /// - /// 多线程下载管理器 - /// - /// - /// - /// - /// - public MultiThreadDownloader(string sourceUrl, string tempDir, string savePath, int numOfParts) - { - _url = sourceUrl; - NumberOfParts = numOfParts; - TempFileDirectory = tempDir; - PartialDownloaderList = new List(); - _aop = AsyncOperationManager.CreateOperation(null); - FilePath = savePath; - _request = WebRequest.Create(sourceUrl) as HttpWebRequest; - } - - /// - /// 多线程下载管理器 - /// - /// - /// - /// - public MultiThreadDownloader(string sourceUrl, string savePath, int numOfParts) : this(sourceUrl, null, - savePath, numOfParts) - { - TempFileDirectory = Path.Combine(Path.GetTempPath(), "DownKyi"); - } - - /// - /// 多线程下载管理器 - /// - /// - /// - public MultiThreadDownloader(string sourceUrl, int numOfParts) : this(sourceUrl, null, numOfParts) - { - } - - #endregion 下载管理器 - - #region 事件 - - private void temp_DownloadPartCompleted(object sender, EventArgs e) - { - WaitOrResumeAll(PartialDownloaderList, true); - - if (TotalBytesReceived == Size) - { - UpdateProgress(); - MergeParts(); - return; - } - - PartialDownloaderList.Sort((x, y) => (int)(y.RemainingBytes - x.RemainingBytes)); - var rem = PartialDownloaderList[0].RemainingBytes; - if (rem < 50 * 1024) - { - WaitOrResumeAll(PartialDownloaderList, false); - return; - } - - var from = PartialDownloaderList[0].CurrentPosition + rem / 2; - var to = PartialDownloaderList[0].To; - if (from > to) - { - WaitOrResumeAll(PartialDownloaderList, false); - return; - } - - PartialDownloaderList[0].To = from - 1; - WaitOrResumeAll(PartialDownloaderList, false); - var temp = new PartialDownloader(_url, TempFileDirectory, Guid.NewGuid().ToString(), from, to, true); - temp.DownloadPartCompleted += temp_DownloadPartCompleted; - temp.DownloadPartProgressChanged += temp_DownloadPartProgressChanged; - lock (this) - { - PartialDownloaderList.Add(temp); - } - - temp.Start(_requestConfigure); - } - - private void temp_DownloadPartProgressChanged(object sender, EventArgs e) - { - UpdateProgress(); - } - - private void UpdateProgress() - { - int pr = (int)(TotalBytesReceived * 1d / Size * 100); - if (TotalProgress != pr) - { - TotalProgress = pr; - if (TotalProgressChanged != null) - { - _aop.Post(state => TotalProgressChanged(this, EventArgs.Empty), null); - } - } - } - - #endregion 事件 - - #region 方法 - - private void CreateFirstPartitions() - { - Size = GetContentLength(ref _rangeAllowed, ref _url); - int maximumPart = (int)(Size / (25 * 1024)); - maximumPart = maximumPart == 0 ? 1 : maximumPart; - if (!_rangeAllowed) - { - NumberOfParts = 1; - } - else if (NumberOfParts > maximumPart) - { - NumberOfParts = maximumPart; - } - - for (int i = 0; i < NumberOfParts; i++) - { - var temp = CreateNew(i, NumberOfParts, Size); - temp.DownloadPartProgressChanged += temp_DownloadPartProgressChanged; - temp.DownloadPartCompleted += temp_DownloadPartCompleted; - lock (this) - { - PartialDownloaderList.Add(temp); - } - - temp.Start(_requestConfigure); - } - } - - private void MergeParts() - { - var mergeOrderedList = PartialDownloaderList.OrderBy(x => x.From); - var dir = new FileInfo(FilePath).DirectoryName; - Directory.CreateDirectory(dir); - - - using (var fs = File.OpenWrite(FilePath)) - { - long totalBytesWrite = 0; - int mergeProgress = 0; - foreach (var item in mergeOrderedList) - { - using (var pdi = File.OpenRead(item.FullPath)) - { - byte[] buffer = new byte[4096]; - int read; - while ((read = pdi.Read(buffer, 0, buffer.Length)) > 0) - { - fs.Write(buffer, 0, read); - totalBytesWrite += read; - int temp = (int)(totalBytesWrite * 1d / Size * 100); - if (temp != mergeProgress && FileMergeProgressChanged != null) - { - mergeProgress = temp; - _aop.Post(state => FileMergeProgressChanged(this, temp), null); - } - } - } - - try - { - File.Delete(item.FullPath); - } - catch - { - // ignored - } - } - } - - if (FileMergedComplete != null) - { - _aop.Post(state => FileMergedComplete(state, EventArgs.Empty), this); - } - } - - private PartialDownloader CreateNew(int order, int parts, long contentLength) - { - var division = contentLength / parts; - var remaining = contentLength % parts; - var start = division * order; - var end = start + division - 1; - end += order == parts - 1 ? remaining : 0; - return new PartialDownloader(_url, TempFileDirectory, Guid.NewGuid().ToString("N"), start, end, true); - } - - /// - /// 暂停或继续 - /// - /// - /// - public static void WaitOrResumeAll(List list, bool wait) - { - for (var index = 0; index < list.Count; index++) - { - if (wait) - { - list[index].Wait(); - } - else - { - list[index].ResumeAfterWait(); - } - } - } - - /// - /// 配置请求头 - /// - /// - public void Configure(Action config) - { - _requestConfigure = config; - } - - /// - /// 获取内容长度 - /// - /// - /// - /// - public long GetContentLength(ref bool rangeAllowed, ref string redirectedUrl) - { - _request.UserAgent = - "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.122 Safari/537.36"; - _request.ServicePoint.ConnectionLimit = 4; - _requestConfigure(_request); - - using (var resp = _request.GetResponse() as HttpWebResponse) - { - redirectedUrl = resp.ResponseUri.OriginalString; - var ctl = resp.ContentLength; - rangeAllowed = resp.Headers.AllKeys.Select((v, i) => new - { - HeaderName = v, - HeaderValue = resp.Headers[i] - }).Any(k => k.HeaderName.ToLower().Contains("range") && k.HeaderValue.ToLower().Contains("byte")); - _request.Abort(); - return ctl; - } - } - - #endregion 方法 - - #region 公共方法 - - /// - /// 暂停下载 - /// - public void Pause() - { - lock (this) - { - foreach (var t in PartialDownloaderList.Where(t => !t.Completed)) - { - t.Stop(); - } - } - - Thread.Sleep(200); - } - - /// - /// 开始下载 - /// - public void Start() - { - Task th = new Task(CreateFirstPartitions); - th.Start(); - } - - /// - /// 唤醒下载 - /// - public void Resume() - { - int count = PartialDownloaderList.Count; - for (int i = 0; i < count; i++) - { - if (PartialDownloaderList[i].Stopped) - { - var from = PartialDownloaderList[i].CurrentPosition + 1; - var to = PartialDownloaderList[i].To; - if (from > to) - { - continue; - } - - var temp = new PartialDownloader(_url, TempFileDirectory, Guid.NewGuid().ToString(), from, to, - _rangeAllowed); - temp.DownloadPartProgressChanged += temp_DownloadPartProgressChanged; - temp.DownloadPartCompleted += temp_DownloadPartCompleted; - lock (this) - { - PartialDownloaderList.Add(temp); - } - - PartialDownloaderList[i].To = PartialDownloaderList[i].CurrentPosition; - temp.Start(_requestConfigure); - } - } - } - - #endregion 公共方法 -} \ No newline at end of file diff --git a/DownKyi.Core/Downloader/PartialDownloader.cs b/DownKyi.Core/Downloader/PartialDownloader.cs deleted file mode 100644 index 284248d..0000000 --- a/DownKyi.Core/Downloader/PartialDownloader.cs +++ /dev/null @@ -1,263 +0,0 @@ -using System.ComponentModel; -using System.Diagnostics; -using System.Net; - -namespace DownKyi.Core.Downloader; - -/// -/// 部分下载器 -/// -public class PartialDownloader -{ - /// - /// 这部分完成事件 - /// - public event EventHandler DownloadPartCompleted; - - /// - /// 部分下载进度改变事件 - /// - public event EventHandler DownloadPartProgressChanged; - - /// - /// 部分下载停止事件 - /// - public event EventHandler DownloadPartStopped; - - private readonly AsyncOperation _aop = AsyncOperationManager.CreateOperation(null); - private readonly int[] _lastSpeeds; - private long _counter; - private long _to; - private long _totalBytesRead; - private bool _wait; - - /// - /// 下载已停止 - /// - public bool Stopped { get; private set; } - - /// - /// 下载已完成 - /// - public bool Completed { get; private set; } - - /// - /// 下载进度 - /// - public int Progress { get; private set; } - - /// - /// 下载目录 - /// - public string Directory { get; } - - /// - /// 文件名 - /// - public string FileName { get; } - - /// - /// 已读字节数 - /// - public long TotalBytesRead => _totalBytesRead; - - /// - /// 内容长度 - /// - public long ContentLength { get; private set; } - - /// - /// RangeAllowed - /// - public bool RangeAllowed { get; } - - /// - /// url - /// - public string Url { get; } - - /// - /// to - /// - public long To - { - get => _to; - set - { - _to = value; - ContentLength = _to - From + 1; - } - } - - /// - /// from - /// - public long From { get; } - - /// - /// 当前位置 - /// - public long CurrentPosition => From + _totalBytesRead - 1; - - /// - /// 剩余字节数 - /// - public long RemainingBytes => ContentLength - _totalBytesRead; - - /// - /// 完整路径 - /// - public string FullPath => Path.Combine(Directory, FileName); - - /// - /// 下载速度 - /// - public int SpeedInBytes - { - get - { - if (Completed) - { - return 0; - } - - int totalSpeeds = _lastSpeeds.Sum(); - return totalSpeeds / 10; - } - } - - /// - /// 部分块下载 - /// - /// - /// - /// - /// - /// - /// - public PartialDownloader(string url, string dir, string fileGuid, long from, long to, bool rangeAllowed) - { - From = from; - _to = to; - Url = url; - RangeAllowed = rangeAllowed; - FileName = fileGuid; - Directory = dir; - _lastSpeeds = new int[10]; - } - - private void DownloadProcedure(Action config) - { - using (var file = new FileStream(FullPath, FileMode.Create, FileAccess.ReadWrite, FileShare.Delete)) - { - var sw = new Stopwatch(); - if (WebRequest.Create(Url) is HttpWebRequest req) - { - req.UserAgent = - "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.122 Safari/537.36"; - req.AllowAutoRedirect = true; - req.MaximumAutomaticRedirections = 5; - req.ServicePoint.ConnectionLimit += 1; - req.ServicePoint.Expect100Continue = true; - req.ProtocolVersion = HttpVersion.Version11; - req.Proxy = WebRequest.GetSystemWebProxy(); - config(req); - if (RangeAllowed) - { - req.AddRange(From, _to); - } - - if (req.GetResponse() is HttpWebResponse resp) - { - ContentLength = resp.ContentLength; - if (ContentLength <= 0 || (RangeAllowed && ContentLength != _to - From + 1)) - { - throw new Exception("Invalid response content"); - } - - using (var tempStream = resp.GetResponseStream()) - { - int bytesRead; - byte[] buffer = new byte[4096]; - sw.Start(); - while ((bytesRead = tempStream.Read(buffer, 0, buffer.Length)) > 0) - { - if (_totalBytesRead + bytesRead > ContentLength) - { - bytesRead = (int)(ContentLength - _totalBytesRead); - } - - file.Write(buffer, 0, bytesRead); - _totalBytesRead += bytesRead; - _lastSpeeds[_counter] = (int)(_totalBytesRead / Math.Ceiling(sw.Elapsed.TotalSeconds)); - _counter = (_counter >= 9) ? 0 : _counter + 1; - int tempProgress = (int)(_totalBytesRead * 100 / ContentLength); - if (Progress != tempProgress) - { - Progress = tempProgress; - _aop.Post(state => { DownloadPartProgressChanged?.Invoke(this, EventArgs.Empty); }, - null); - } - - if (Stopped || (RangeAllowed && _totalBytesRead == ContentLength)) - { - break; - } - } - } - } - - req.Abort(); - } - - sw.Stop(); - if (!Stopped && DownloadPartCompleted != null) - { - _aop.Post(state => - { - Completed = true; - DownloadPartCompleted(this, EventArgs.Empty); - }, null); - } - - if (Stopped && DownloadPartStopped != null) - { - _aop.Post(state => DownloadPartStopped(this, EventArgs.Empty), null); - } - } - } - - /// - /// 启动下载 - /// - public void Start(Action config) - { - Stopped = false; - var procThread = new Thread(_ => DownloadProcedure(config)); - procThread.Start(); - } - - /// - /// 下载停止 - /// - public void Stop() - { - Stopped = true; - } - - /// - /// 暂停等待下载 - /// - public void Wait() - { - _wait = true; - } - - /// - /// 稍后唤醒 - /// - public void ResumeAfterWait() - { - _wait = false; - } -} \ No newline at end of file diff --git a/DownKyi.Core/FFMpeg/FFMpeg.cs b/DownKyi.Core/FFMpeg/FFMpeg.cs index b24fd04..6b1b974 100644 --- a/DownKyi.Core/FFMpeg/FFMpeg.cs +++ b/DownKyi.Core/FFMpeg/FFMpeg.cs @@ -17,8 +17,7 @@ public class FFMpeg private FFMpeg() { - GlobalFFOptions.Configure(new FFOptions - { BinaryFolder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "ffmpeg") }); + GlobalFFOptions.Configure(new FFOptions { BinaryFolder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "ffmpeg") }); FFMpegHelper.VerifyFFMpegExists(GlobalFFOptions.Current); } @@ -54,7 +53,7 @@ public class FFMpeg if (video == null || !File.Exists(video)) { - if (SettingsManager.GetInstance().IsTranscodingAacToMp3() == AllowStatus.YES) + if (SettingsManager.GetInstance().GetIsTranscodingAacToMp3() == AllowStatus.Yes) { arguments = FFMpegArguments.FromFileInput(audio).OutputToFile( destVideo, diff --git a/DownKyi.Core/FileName/FileName.cs b/DownKyi.Core/FileName/FileName.cs index aa5c518..4c335d9 100644 --- a/DownKyi.Core/FileName/FileName.cs +++ b/DownKyi.Core/FileName/FileName.cs @@ -4,28 +4,28 @@ namespace DownKyi.Core.FileName; public class FileName { - private readonly List nameParts; - private string order = "ORDER"; - private string section = "SECTION"; - private string mainTitle = "MAIN_TITLE"; - private string pageTitle = "PAGE_TITLE"; - private string videoZone = "VIDEO_ZONE"; - private string audioQuality = "AUDIO_QUALITY"; - private string videoQuality = "VIDEO_QUALITY"; - private string videoCodec = "VIDEO_CODEC"; + private readonly List _nameParts; + private string _order = "ORDER"; + private string _section = "SECTION"; + private string _mainTitle = "MAIN_TITLE"; + private string _pageTitle = "PAGE_TITLE"; + private string _videoZone = "VIDEO_ZONE"; + private string _audioQuality = "AUDIO_QUALITY"; + private string _videoQuality = "VIDEO_QUALITY"; + private string _videoCodec = "VIDEO_CODEC"; - private string videoPublishTime = "VIDEO_PUBLISH_TIME"; + private string _videoPublishTime = "VIDEO_PUBLISH_TIME"; - private long avid = -1; - private string bvid = "BVID"; - private long cid = -1; + private long _avid = -1; + private string _bvid = "BVID"; + private long _cid = -1; - private long upMid = -1; - private string upName = "UP_NAME"; + private long _upMid = -1; + private string _upName = "UP_NAME"; private FileName(List nameParts) { - this.nameParts = nameParts; + this._nameParts = nameParts; } public static FileName Builder(List nameParts) @@ -35,149 +35,149 @@ public class FileName public FileName SetOrder(int order) { - this.order = order.ToString(); + _order = order.ToString(); return this; } public FileName SetOrder(int order, int count) { - int length = Math.Abs(count).ToString().Length; - this.order = order.ToString("D" + length); + var length = Math.Abs(count).ToString().Length; + _order = order.ToString("D" + length); return this; } public FileName SetSection(string section) { - this.section = section; + _section = section; return this; } public FileName SetMainTitle(string mainTitle) { - this.mainTitle = mainTitle; + _mainTitle = mainTitle; return this; } public FileName SetPageTitle(string pageTitle) { - this.pageTitle = pageTitle; + _pageTitle = pageTitle; return this; } public FileName SetVideoZone(string videoZone) { - this.videoZone = videoZone; + _videoZone = videoZone; return this; } public FileName SetAudioQuality(string audioQuality) { - this.audioQuality = audioQuality; + _audioQuality = audioQuality; return this; } public FileName SetVideoQuality(string videoQuality) { - this.videoQuality = videoQuality; + _videoQuality = videoQuality; return this; } public FileName SetVideoCodec(string videoCodec) { - this.videoCodec = videoCodec; + _videoCodec = videoCodec; return this; } public FileName SetVideoPublishTime(string videoPublishTime) { - this.videoPublishTime = videoPublishTime; + _videoPublishTime = videoPublishTime; return this; } public FileName SetAvid(long avid) { - this.avid = avid; + _avid = avid; return this; } public FileName SetBvid(string bvid) { - this.bvid = bvid; + _bvid = bvid; return this; } public FileName SetCid(long cid) { - this.cid = cid; + _cid = cid; return this; } public FileName SetUpMid(long upMid) { - this.upMid = upMid; + _upMid = upMid; return this; } public FileName SetUpName(string upName) { - this.upName = upName; + _upName = upName; return this; } public string RelativePath() { - string path = string.Empty; + var path = string.Empty; - foreach (FileNamePart part in nameParts) + foreach (var part in _nameParts) { switch (part) { - case FileNamePart.ORDER: - path += order; + case FileNamePart.Order: + path += _order; break; - case FileNamePart.SECTION: - path += section; + case FileNamePart.Section: + path += _section; break; - case FileNamePart.MAIN_TITLE: - path += mainTitle; + case FileNamePart.MainTitle: + path += _mainTitle; break; - case FileNamePart.PAGE_TITLE: - path += pageTitle; + case FileNamePart.PageTitle: + path += _pageTitle; break; - case FileNamePart.VIDEO_ZONE: - path += videoZone; + case FileNamePart.VideoZone: + path += _videoZone; break; - case FileNamePart.AUDIO_QUALITY: - path += audioQuality; + case FileNamePart.AudioQuality: + path += _audioQuality; break; - case FileNamePart.VIDEO_QUALITY: - path += videoQuality; + case FileNamePart.VideoQuality: + path += _videoQuality; break; - case FileNamePart.VIDEO_CODEC: - path += videoCodec; + case FileNamePart.VideoCodec: + path += _videoCodec; break; - case FileNamePart.VIDEO_PUBLISH_TIME: - path += videoPublishTime; + case FileNamePart.VideoPublishTime: + path += _videoPublishTime; break; - case FileNamePart.AVID: - path += $"av{avid}"; + case FileNamePart.Avid: + path += $"av{_avid}"; break; - case FileNamePart.BVID: - path += bvid; + case FileNamePart.Bvid: + path += _bvid; break; - case FileNamePart.CID: - path += cid; + case FileNamePart.Cid: + path += _cid; break; - case FileNamePart.UP_MID: - path += upMid; + case FileNamePart.UpMid: + path += _upMid; break; - case FileNamePart.UP_NAME: - path += upName; + case FileNamePart.UpName: + path += _upName; break; } - if (((int)part) >= 100) + if ((int)part >= 100) { path += HyphenSeparated.Hyphen[(int)part]; } diff --git a/DownKyi.Core/FileName/FileNamePart.cs b/DownKyi.Core/FileName/FileNamePart.cs index a0f152d..001e5e7 100644 --- a/DownKyi.Core/FileName/FileNamePart.cs +++ b/DownKyi.Core/FileName/FileNamePart.cs @@ -3,40 +3,40 @@ public enum FileNamePart { // Video - ORDER = 1, - SECTION, - MAIN_TITLE, - PAGE_TITLE, - VIDEO_ZONE, - AUDIO_QUALITY, - VIDEO_QUALITY, - VIDEO_CODEC, + Order = 1, + Section, + MainTitle, + PageTitle, + VideoZone, + AudioQuality, + VideoQuality, + VideoCodec, - VIDEO_PUBLISH_TIME, + VideoPublishTime, - AVID, - BVID, - CID, + Avid, + Bvid, + Cid, - UP_MID, - UP_NAME, + UpMid, + UpName, // 斜杠 - SLASH = 100, + Slash = 100, // HyphenSeparated - UNDERSCORE = 101, // 下划线 - HYPHEN, // 连字符 - PLUS, // 加号 - COMMA, // 逗号 - PERIOD, // 句号 - AND, // and - NUMBER, // # - OPEN_PAREN, // 左圆括号 - CLOSE_PAREN, // 右圆括号 - OPEN_BRACKET, // 左方括号 - CLOSE_BRACKET, // 右方括号 - OPEN_BRACE, // 左花括号 - CLOSE_brace, // 右花括号 - BLANK, // 空白符 + Underscore = 101, // 下划线 + Hyphen, // 连字符 + Plus, // 加号 + Comma, // 逗号 + Period, // 句号 + And, // and + Number, // # + OpenParen, // 左圆括号 + CloseParen, // 右圆括号 + OpenBracket, // 左方括号 + CloseBracket, // 右方括号 + OpenBrace, // 左花括号 + CloseBrace, // 右花括号 + Blank, // 空白符 } \ No newline at end of file diff --git a/DownKyi.Core/FileName/HyphenSeparated.cs b/DownKyi.Core/FileName/HyphenSeparated.cs index aad9b2f..7fbe72a 100644 --- a/DownKyi.Core/FileName/HyphenSeparated.cs +++ b/DownKyi.Core/FileName/HyphenSeparated.cs @@ -6,7 +6,7 @@ public static class HyphenSeparated { // 文件名的分隔符 - public static Dictionary Hyphen = new Dictionary() + public static readonly Dictionary Hyphen = new() { { 100, "/" }, { 101, "_" }, diff --git a/DownKyi.Core/Logging/LogManager.cs b/DownKyi.Core/Logging/LogManager.cs index d47c43d..cd1ae1b 100644 --- a/DownKyi.Core/Logging/LogManager.cs +++ b/DownKyi.Core/Logging/LogManager.cs @@ -2,6 +2,7 @@ using System.Text.RegularExpressions; using DownKyi.Core.Storage; using static System.DateTime; +using static System.Threading.Thread; namespace DownKyi.Core.Logging; @@ -10,29 +11,28 @@ namespace DownKyi.Core.Logging; /// public class LogManager { - private static readonly ConcurrentQueue> LogQueue = - new ConcurrentQueue>(); + private static readonly ConcurrentQueue> LogQueue = new(); /// /// 自定义事件 /// - public static event Action Event; + public static event Action? Event; static LogManager() { var writeTask = new Task(obj => { + var temp = new List(); while (true) { Pause.WaitOne(1000, true); - List temp = new List(); foreach (var logItem in LogQueue) { - string logPath = logItem.Item1; - string logMergeContent = string.Concat(logItem.Item2, Environment.NewLine, + var logPath = logItem.Item1; + var logMergeContent = string.Concat(logItem.Item2, Environment.NewLine, "----------------------------------------------------------------------------------------------------------------------", Environment.NewLine); - string[] logArr = temp.FirstOrDefault(d => d[0].Equals(logPath)); + var logArr = temp.FirstOrDefault(d => d[0].Equals(logPath)); if (logArr != null) { logArr[1] = string.Concat(logArr[1], logMergeContent); @@ -59,7 +59,7 @@ public class LogManager writeTask.Start(); } - private static AutoResetEvent Pause => new AutoResetEvent(false); + private static AutoResetEvent Pause => new(false); /// /// 日志存放目录,windows默认日志放在当前应用程序运行目录下的Logs文件夹中,macOS、linux存放于applicationData目录下 @@ -72,14 +72,13 @@ public class LogManager /// public static void Info(string info) { - LogQueue.Enqueue(new Tuple(GetLogPath(), - $"{Now} [{Thread.CurrentThread.ManagedThreadId}] {nameof(info).ToUpper()} {info}")); - var log = new LogInfo() + LogQueue.Enqueue(new Tuple(GetLogPath(), $"{Now} [{Environment.CurrentManagedThreadId}] {nameof(info).ToUpper()} {info}")); + var log = new LogInfo { LogLevel = LogLevel.Info, Message = info, Time = Now, - ThreadId = Thread.CurrentThread.ManagedThreadId + ThreadId = Environment.CurrentManagedThreadId }; Event?.Invoke(log); } @@ -91,14 +90,13 @@ public class LogManager /// public static void Info(string source, string info) { - LogQueue.Enqueue(new Tuple(GetLogPath(), - $"{Now} [{Thread.CurrentThread.ManagedThreadId}] {nameof(info).ToUpper()} {source} {info}")); - LogInfo log = new LogInfo() + LogQueue.Enqueue(new Tuple(GetLogPath(), $"{Now} [{Environment.CurrentManagedThreadId}] {nameof(info).ToUpper()} {source} {info}")); + var log = new LogInfo { LogLevel = LogLevel.Info, Message = info, Time = Now, - ThreadId = Thread.CurrentThread.ManagedThreadId, + ThreadId = Environment.CurrentManagedThreadId, Source = source }; Event?.Invoke(log); @@ -112,13 +110,13 @@ public class LogManager public static void Info(Type source, string info) { LogQueue.Enqueue(new Tuple(GetLogPath(), - $"{Now} [{Thread.CurrentThread.ManagedThreadId}] {nameof(info).ToUpper()} {source.FullName} {info}")); - LogInfo log = new LogInfo() + $"{Now} [{Environment.CurrentManagedThreadId}] {nameof(info).ToUpper()} {source.FullName} {info}")); + var log = new LogInfo { LogLevel = LogLevel.Info, Message = info, Time = Now, - ThreadId = Thread.CurrentThread.ManagedThreadId, + ThreadId = Environment.CurrentManagedThreadId, Source = source.FullName }; Event?.Invoke(log); @@ -130,14 +128,13 @@ public class LogManager /// 异常对象 public static void Debug(string debug) { - LogQueue.Enqueue(new Tuple(GetLogPath(), - $"{Now} [{Thread.CurrentThread.ManagedThreadId}] {nameof(debug).ToUpper()} {debug}")); - LogInfo log = new LogInfo() + LogQueue.Enqueue(new Tuple(GetLogPath(), $"{Now} [{Environment.CurrentManagedThreadId}] {nameof(debug).ToUpper()} {debug}")); + var log = new LogInfo { LogLevel = LogLevel.Debug, Message = debug, Time = Now, - ThreadId = Thread.CurrentThread.ManagedThreadId + ThreadId = Environment.CurrentManagedThreadId }; Event?.Invoke(log); } @@ -149,14 +146,13 @@ public class LogManager /// 异常对象 public static void Debug(string source, string debug) { - LogQueue.Enqueue(new Tuple(GetLogPath(), - $"{Now} [{Thread.CurrentThread.ManagedThreadId}] {nameof(debug).ToUpper()} {source} {debug}")); - LogInfo log = new LogInfo() + LogQueue.Enqueue(new Tuple(GetLogPath(), $"{Now} [{Environment.CurrentManagedThreadId}] {nameof(debug).ToUpper()} {source} {debug}")); + var log = new LogInfo { LogLevel = LogLevel.Debug, Message = debug, Time = Now, - ThreadId = Thread.CurrentThread.ManagedThreadId, + ThreadId = Environment.CurrentManagedThreadId, Source = source }; Event?.Invoke(log); @@ -169,14 +165,13 @@ public class LogManager /// 异常对象 public static void Debug(Type source, string debug) { - LogQueue.Enqueue(new Tuple(GetLogPath(), - $"{Now} [{Thread.CurrentThread.ManagedThreadId}] {nameof(debug).ToUpper()} {source.FullName} {debug}")); - LogInfo log = new LogInfo() + LogQueue.Enqueue(new Tuple(GetLogPath(), $"{Now} [{Environment.CurrentManagedThreadId}] {nameof(debug).ToUpper()} {source.FullName} {debug}")); + var log = new LogInfo { LogLevel = LogLevel.Debug, Message = debug, Time = Now, - ThreadId = Thread.CurrentThread.ManagedThreadId, + ThreadId = Environment.CurrentManagedThreadId, Source = source.FullName }; Event?.Invoke(log); @@ -189,13 +184,13 @@ public class LogManager public static void Error(Exception error) { LogQueue.Enqueue(new Tuple(GetLogPath(), - $"{Now} [{Thread.CurrentThread.ManagedThreadId}] {nameof(error).ToUpper()} {error.Source} {error.Message}{Environment.NewLine}{error.StackTrace}")); - LogInfo log = new LogInfo() + $"{Now} [{Environment.CurrentManagedThreadId}] {nameof(error).ToUpper()} {error.Source} {error.Message}{Environment.NewLine}{error.StackTrace}")); + var log = new LogInfo { LogLevel = LogLevel.Error, Message = error.Message, Time = Now, - ThreadId = Thread.CurrentThread.ManagedThreadId, + ThreadId = Environment.CurrentManagedThreadId, Source = error.Source, Exception = error, ExceptionType = error.GetType().Name @@ -211,13 +206,13 @@ public class LogManager public static void Error(Type source, Exception error) { LogQueue.Enqueue(new Tuple(GetLogPath(), - $"{Now} [{Thread.CurrentThread.ManagedThreadId}] {nameof(error).ToUpper()} {source.FullName} {error.Message}{Environment.NewLine}{error.StackTrace}")); - LogInfo log = new LogInfo() + $"{Now} [{Environment.CurrentManagedThreadId}] {nameof(error).ToUpper()} {source.FullName} {error.Message}{Environment.NewLine}{error.StackTrace}")); + var log = new LogInfo { LogLevel = LogLevel.Error, Message = error.Message, Time = Now, - ThreadId = Thread.CurrentThread.ManagedThreadId, + ThreadId = Environment.CurrentManagedThreadId, Source = source.FullName, Exception = error, ExceptionType = error.GetType().Name @@ -232,14 +227,13 @@ public class LogManager /// 异常信息 public static void Error(Type source, string error) { - LogQueue.Enqueue(new Tuple(GetLogPath(), - $"{Now} [{Thread.CurrentThread.ManagedThreadId}] {nameof(error).ToUpper()} {source.FullName} {error}")); - LogInfo log = new LogInfo() + LogQueue.Enqueue(new Tuple(GetLogPath(), $"{Now} [{Environment.CurrentManagedThreadId}] {nameof(error).ToUpper()} {source.FullName} {error}")); + var log = new LogInfo { LogLevel = LogLevel.Error, Message = error, Time = Now, - ThreadId = Thread.CurrentThread.ManagedThreadId, + ThreadId = Environment.CurrentManagedThreadId, Source = source.FullName, //Exception = error, ExceptionType = error.GetType().Name @@ -255,13 +249,13 @@ public class LogManager public static void Error(string source, Exception error) { LogQueue.Enqueue(new Tuple(GetLogPath(), - $"{Now} [{Thread.CurrentThread.ManagedThreadId}] {nameof(error).ToUpper()} {source} {error.Message}{Environment.NewLine}{error.StackTrace}")); - LogInfo log = new LogInfo() + $"{Now} [{Environment.CurrentManagedThreadId}] {nameof(error).ToUpper()} {source} {error.Message}{Environment.NewLine}{error.StackTrace}")); + var log = new LogInfo { LogLevel = LogLevel.Error, Message = error.Message, Time = Now, - ThreadId = Thread.CurrentThread.ManagedThreadId, + ThreadId = Environment.CurrentManagedThreadId, Source = source, Exception = error, ExceptionType = error.GetType().Name @@ -276,14 +270,13 @@ public class LogManager /// 异常信息 public static void Error(string source, string error) { - LogQueue.Enqueue(new Tuple(GetLogPath(), - $"{Now} [{Thread.CurrentThread.ManagedThreadId}] {nameof(error).ToUpper()} {source} {error}")); - LogInfo log = new LogInfo() + LogQueue.Enqueue(new Tuple(GetLogPath(), $"{Now} [{Environment.CurrentManagedThreadId}] {nameof(error).ToUpper()} {source} {error}")); + var log = new LogInfo { LogLevel = LogLevel.Error, Message = error, Time = Now, - ThreadId = Thread.CurrentThread.ManagedThreadId, + ThreadId = Environment.CurrentManagedThreadId, Source = source, //Exception = error, ExceptionType = error.GetType().Name @@ -298,13 +291,13 @@ public class LogManager public static void Fatal(Exception fatal) { LogQueue.Enqueue(new Tuple(GetLogPath(), - $"{Now} [{Thread.CurrentThread.ManagedThreadId}] {nameof(fatal).ToUpper()} {fatal.Source} {fatal.Message}{Environment.NewLine}{fatal.StackTrace}")); - LogInfo log = new LogInfo() + $"{Now} [{Environment.CurrentManagedThreadId}] {nameof(fatal).ToUpper()} {fatal.Source} {fatal.Message}{Environment.NewLine}{fatal.StackTrace}")); + LogInfo log = new LogInfo { LogLevel = LogLevel.Fatal, Message = fatal.Message, Time = Now, - ThreadId = Thread.CurrentThread.ManagedThreadId, + ThreadId = Environment.CurrentManagedThreadId, Source = fatal.Source, Exception = fatal, ExceptionType = fatal.GetType().Name @@ -320,13 +313,13 @@ public class LogManager public static void Fatal(Type source, Exception fatal) { LogQueue.Enqueue(new Tuple(GetLogPath(), - $"{Now} [{Thread.CurrentThread.ManagedThreadId}] {nameof(fatal).ToUpper()} {source.FullName} {fatal.Message}{Environment.NewLine}{fatal.StackTrace}")); - LogInfo log = new LogInfo() + $"{Now} [{Environment.CurrentManagedThreadId}] {nameof(fatal).ToUpper()} {source.FullName} {fatal.Message}{Environment.NewLine}{fatal.StackTrace}")); + var log = new LogInfo { LogLevel = LogLevel.Fatal, Message = fatal.Message, Time = Now, - ThreadId = Thread.CurrentThread.ManagedThreadId, + ThreadId = Environment.CurrentManagedThreadId, Source = source.FullName, Exception = fatal, ExceptionType = fatal.GetType().Name @@ -341,14 +334,13 @@ public class LogManager /// 异常对象 public static void Fatal(Type source, string fatal) { - LogQueue.Enqueue(new Tuple(GetLogPath(), - $"{Now} [{Thread.CurrentThread.ManagedThreadId}] {nameof(fatal).ToUpper()} {source.FullName} {fatal}")); - LogInfo log = new LogInfo() + LogQueue.Enqueue(new Tuple(GetLogPath(), $"{Now} [{Environment.CurrentManagedThreadId}] {nameof(fatal).ToUpper()} {source.FullName} {fatal}")); + var log = new LogInfo { LogLevel = LogLevel.Fatal, Message = fatal, Time = Now, - ThreadId = Thread.CurrentThread.ManagedThreadId, + ThreadId = Environment.CurrentManagedThreadId, Source = source.FullName, //Exception = fatal, ExceptionType = fatal.GetType().Name @@ -364,13 +356,13 @@ public class LogManager public static void Fatal(string source, Exception fatal) { LogQueue.Enqueue(new Tuple(GetLogPath(), - $"{Now} [{Thread.CurrentThread.ManagedThreadId}] {nameof(fatal).ToUpper()} {source} {fatal.Message}{Environment.NewLine}{fatal.StackTrace}")); - LogInfo log = new LogInfo() + $"{Now} [{Environment.CurrentManagedThreadId}] {nameof(fatal).ToUpper()} {source} {fatal.Message}{Environment.NewLine}{fatal.StackTrace}")); + var log = new LogInfo { LogLevel = LogLevel.Fatal, Message = fatal.Message, Time = Now, - ThreadId = Thread.CurrentThread.ManagedThreadId, + ThreadId = Environment.CurrentManagedThreadId, Source = source, Exception = fatal, ExceptionType = fatal.GetType().Name @@ -385,14 +377,13 @@ public class LogManager /// 异常对象 public static void Fatal(string source, string fatal) { - LogQueue.Enqueue(new Tuple(GetLogPath(), - $"{Now} [{Thread.CurrentThread.ManagedThreadId}] {nameof(fatal).ToUpper()} {source} {fatal}")); - LogInfo log = new LogInfo() + LogQueue.Enqueue(new Tuple(GetLogPath(), $"{Now} [{Environment.CurrentManagedThreadId}] {nameof(fatal).ToUpper()} {source} {fatal}")); + var log = new LogInfo { LogLevel = LogLevel.Fatal, Message = fatal, Time = Now, - ThreadId = Thread.CurrentThread.ManagedThreadId, + ThreadId = Environment.CurrentManagedThreadId, Source = source, ExceptionType = fatal.GetType().Name }; @@ -402,21 +393,18 @@ public class LogManager private static string GetLogPath() { string newFilePath; - var logDir = string.IsNullOrEmpty(LogDirectory) - ? Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "logs") - : LogDirectory; + var logDir = string.IsNullOrEmpty(LogDirectory) ? Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "logs") : LogDirectory; Directory.CreateDirectory(logDir); - string extension = ".log"; - string fileNameNotExt = Now.ToString("yyyyMMdd"); - string fileNamePattern = string.Concat(fileNameNotExt, "(*)", extension); - List filePaths = Directory.GetFiles(logDir, fileNamePattern, SearchOption.TopDirectoryOnly).ToList(); + const string extension = ".log"; + var fileNameNotExt = Now.ToString("yyyyMMdd"); + var fileNamePattern = string.Concat(fileNameNotExt, "(*)", extension); + var filePaths = Directory.GetFiles(logDir, fileNamePattern, SearchOption.TopDirectoryOnly).ToList(); if (filePaths.Count > 0) { - int fileMaxLen = filePaths.Max(d => d.Length); - string lastFilePath = - filePaths.Where(d => d.Length == fileMaxLen).OrderByDescending(d => d).FirstOrDefault(); - if (new FileInfo(lastFilePath).Length > 1 * 1024 * 1024) + var fileMaxLen = filePaths.Max(d => d.Length); + var lastFilePath = filePaths.Where(d => d.Length == fileMaxLen).OrderByDescending(d => d).FirstOrDefault(); + if (lastFilePath != null && new FileInfo(lastFilePath).Length > 1 * 1024 * 1024) { var no = new Regex(@"(?is)(?<=\()(.*)(?=\))").Match(Path.GetFileName(lastFilePath)).Value; var parse = int.TryParse(no, out int tempno); @@ -447,10 +435,8 @@ public class LogManager File.CreateText(logPath).Close(); } - using (var sw = File.AppendText(logPath)) - { - sw.Write(logContent); - } + using var sw = File.AppendText(logPath); + sw.Write(logContent); } catch (Exception) { diff --git a/DownKyi.Core/Settings/AfterDownloadOperation.cs b/DownKyi.Core/Settings/AfterDownloadOperation.cs index 3f56728..daad9a4 100644 --- a/DownKyi.Core/Settings/AfterDownloadOperation.cs +++ b/DownKyi.Core/Settings/AfterDownloadOperation.cs @@ -2,9 +2,9 @@ public enum AfterDownloadOperation { - NOT_SET = 0, - NONE = 1, - OPEN_FOLDER, - CLOSE_APP, - CLOSE_SYSTEM + NotSet = 0, + None = 1, + OpenFolder, + CloseApp, + CloseSystem } \ No newline at end of file diff --git a/DownKyi.Core/Settings/AllowStatus.cs b/DownKyi.Core/Settings/AllowStatus.cs index d39f642..408511c 100644 --- a/DownKyi.Core/Settings/AllowStatus.cs +++ b/DownKyi.Core/Settings/AllowStatus.cs @@ -2,7 +2,7 @@ public enum AllowStatus { - NONE = 0, - NO, - YES + None = 0, + No, + Yes } \ No newline at end of file diff --git a/DownKyi.Core/Settings/DanmakuLayoutAlgorithm.cs b/DownKyi.Core/Settings/DanmakuLayoutAlgorithm.cs index d06f005..714d9c3 100644 --- a/DownKyi.Core/Settings/DanmakuLayoutAlgorithm.cs +++ b/DownKyi.Core/Settings/DanmakuLayoutAlgorithm.cs @@ -2,7 +2,7 @@ public enum DanmakuLayoutAlgorithm { - NONE = 0, - ASYNC, - SYNC + None = 0, + Async, + Sync } \ No newline at end of file diff --git a/DownKyi.Core/Settings/Downloader.cs b/DownKyi.Core/Settings/Downloader.cs index 809b962..6d0ec30 100644 --- a/DownKyi.Core/Settings/Downloader.cs +++ b/DownKyi.Core/Settings/Downloader.cs @@ -2,8 +2,8 @@ public enum Downloader { - NOT_SET = 0, - BUILT_IN, - ARIA, - CUSTOM_ARIA, + NotSet = 0, + BuiltIn, + Aria, + CustomAria, } \ No newline at end of file diff --git a/DownKyi.Core/Settings/Models/AboutSettings.cs b/DownKyi.Core/Settings/Models/AboutSettings.cs index 817ded0..8bcd4fc 100644 --- a/DownKyi.Core/Settings/Models/AboutSettings.cs +++ b/DownKyi.Core/Settings/Models/AboutSettings.cs @@ -5,6 +5,6 @@ /// public class AboutSettings { - public AllowStatus IsReceiveBetaVersion { get; set; } = AllowStatus.NONE; - public AllowStatus AutoUpdateWhenLaunch { get; set; } = AllowStatus.NONE; + public AllowStatus IsReceiveBetaVersion { get; set; } = AllowStatus.None; + public AllowStatus AutoUpdateWhenLaunch { get; set; } = AllowStatus.None; } \ No newline at end of file diff --git a/DownKyi.Core/Settings/Models/BasicSettings.cs b/DownKyi.Core/Settings/Models/BasicSettings.cs index 2e20f83..ac022ec 100644 --- a/DownKyi.Core/Settings/Models/BasicSettings.cs +++ b/DownKyi.Core/Settings/Models/BasicSettings.cs @@ -6,12 +6,12 @@ public class BasicSettings { public ThemeMode ThemeMode { get; set; } = ThemeMode.Default; - public AfterDownloadOperation AfterDownload { get; set; } = AfterDownloadOperation.NOT_SET; - public AllowStatus IsListenClipboard { get; set; } = AllowStatus.NONE; - public AllowStatus IsAutoParseVideo { get; set; } = AllowStatus.NONE; - public ParseScope ParseScope { get; set; } = ParseScope.NOT_SET; - public AllowStatus IsAutoDownloadAll { get; set; } = AllowStatus.NONE; + public AfterDownloadOperation AfterDownload { get; set; } = AfterDownloadOperation.NotSet; + public AllowStatus IsListenClipboard { get; set; } = AllowStatus.None; + public AllowStatus IsAutoParseVideo { get; set; } = AllowStatus.None; + public ParseScope ParseScope { get; set; } = ParseScope.NotSet; + public AllowStatus IsAutoDownloadAll { get; set; } = AllowStatus.None; public DownloadFinishedSort DownloadFinishedSort { get; set; } = DownloadFinishedSort.NotSet; public RepeatDownloadStrategy RepeatDownloadStrategy { get; set; } = RepeatDownloadStrategy.Ask; - public bool RepeatFileAutoAddNumberSuffix { get; set; } = false; + public bool RepeatFileAutoAddNumberSuffix { get; set; } } \ No newline at end of file diff --git a/DownKyi.Core/Settings/Models/DanmakuSettings.cs b/DownKyi.Core/Settings/Models/DanmakuSettings.cs index f145761..313f69b 100644 --- a/DownKyi.Core/Settings/Models/DanmakuSettings.cs +++ b/DownKyi.Core/Settings/Models/DanmakuSettings.cs @@ -5,14 +5,14 @@ /// public class DanmakuSettings { - public AllowStatus DanmakuTopFilter { get; set; } = AllowStatus.NONE; - public AllowStatus DanmakuBottomFilter { get; set; } = AllowStatus.NONE; - public AllowStatus DanmakuScrollFilter { get; set; } = AllowStatus.NONE; - public AllowStatus IsCustomDanmakuResolution { get; set; } = AllowStatus.NONE; + public AllowStatus DanmakuTopFilter { get; set; } = AllowStatus.None; + public AllowStatus DanmakuBottomFilter { get; set; } = AllowStatus.None; + public AllowStatus DanmakuScrollFilter { get; set; } = AllowStatus.None; + public AllowStatus IsCustomDanmakuResolution { get; set; } = AllowStatus.None; public int DanmakuScreenWidth { get; set; } = -1; public int DanmakuScreenHeight { get; set; } = -1; - public string DanmakuFontName { get; set; } = null; + public string? DanmakuFontName { get; set; } public int DanmakuFontSize { get; set; } = -1; public int DanmakuLineCount { get; set; } = -1; - public DanmakuLayoutAlgorithm DanmakuLayoutAlgorithm { get; set; } = DanmakuLayoutAlgorithm.NONE; + public DanmakuLayoutAlgorithm DanmakuLayoutAlgorithm { get; set; } = DanmakuLayoutAlgorithm.None; } \ No newline at end of file diff --git a/DownKyi.Core/Settings/Models/NetworkSettings.cs b/DownKyi.Core/Settings/Models/NetworkSettings.cs index ca8545a..fc72671 100644 --- a/DownKyi.Core/Settings/Models/NetworkSettings.cs +++ b/DownKyi.Core/Settings/Models/NetworkSettings.cs @@ -7,27 +7,27 @@ namespace DownKyi.Core.Settings.Models; /// public class NetworkSettings { - public AllowStatus IsLiftingOfRegion { get; set; } = AllowStatus.NONE; + public AllowStatus IsLiftingOfRegion { get; set; } = AllowStatus.None; - public AllowStatus UseSSL { get; set; } = AllowStatus.NONE; + public AllowStatus UseSsl { get; set; } = AllowStatus.None; public string UserAgent { get; set; } = string.Empty; - public Downloader Downloader { get; set; } = Downloader.NOT_SET; + public Downloader Downloader { get; set; } = Downloader.NotSet; public int MaxCurrentDownloads { get; set; } = -1; #region built-in public int Split { get; set; } = -1; - public AllowStatus IsHttpProxy { get; set; } = AllowStatus.NONE; - public string HttpProxy { get; set; } = null; + public AllowStatus IsHttpProxy { get; set; } = AllowStatus.None; + public string? HttpProxy { get; set; } public int HttpProxyListenPort { get; set; } = -1; #endregion #region Aria - public string AriaToken { get; set; } = null; - public string AriaHost { get; set; } = null; + public string? AriaToken { get; set; } + public string? AriaHost { get; set; } public int AriaListenPort { get; set; } = -1; @@ -37,8 +37,8 @@ public class NetworkSettings public int AriaMaxDownloadLimit { get; set; } = -1; public AriaConfigFileAllocation AriaFileAllocation { get; set; } = AriaConfigFileAllocation.NOT_SET; - public AllowStatus IsAriaHttpProxy { get; set; } = AllowStatus.NONE; - public string AriaHttpProxy { get; set; } = null; + public AllowStatus IsAriaHttpProxy { get; set; } = AllowStatus.None; + public string? AriaHttpProxy { get; set; } public int AriaHttpProxyListenPort { get; set; } = -1; #endregion diff --git a/DownKyi.Core/Settings/Models/VideoSettings.cs b/DownKyi.Core/Settings/Models/VideoSettings.cs index ab461cb..127913b 100644 --- a/DownKyi.Core/Settings/Models/VideoSettings.cs +++ b/DownKyi.Core/Settings/Models/VideoSettings.cs @@ -11,13 +11,13 @@ public class VideoSettings public int Quality { get; set; } = -1; // 画质 public int AudioQuality { get; set; } = -1; // 音质 public int VideoParseType { get; set; } = 1; // 视频解析类型 - public AllowStatus IsTranscodingFlvToMp4 { get; set; } = AllowStatus.NONE; // 是否将flv转为mp4 - public AllowStatus IsTranscodingAacToMp3 { get; set; } = AllowStatus.NONE; // 是否将aac转为mp3 - public string SaveVideoRootPath { get; set; } = null; // 视频保存路径 - public List HistoryVideoRootPaths { get; set; } = null; // 历史视频保存路径 - public AllowStatus IsUseSaveVideoRootPath { get; set; } = AllowStatus.NONE; // 是否使用默认视频保存路径 - public VideoContentSettings VideoContent { get; set; } = null; // 下载内容 - public List FileNameParts { get; set; } = null; // 文件命名格式 - public string FileNamePartTimeFormat { get; set; } = null; // 文件命名中的时间格式 - public OrderFormat OrderFormat { get; set; } = OrderFormat.NOT_SET; // 文件命名中的序号格式 + public AllowStatus IsTranscodingFlvToMp4 { get; set; } = AllowStatus.None; // 是否将flv转为mp4 + public AllowStatus IsTranscodingAacToMp3 { get; set; } = AllowStatus.None; // 是否将aac转为mp3 + public string? SaveVideoRootPath { get; set; } // 视频保存路径 + public List? HistoryVideoRootPaths { get; set; } // 历史视频保存路径 + public AllowStatus IsUseSaveVideoRootPath { get; set; } = AllowStatus.None; // 是否使用默认视频保存路径 + public VideoContentSettings? VideoContent { get; set; } // 下载内容 + public List? FileNameParts { get; set; } // 文件命名格式 + public string? FileNamePartTimeFormat { get; set; } // 文件命名中的时间格式 + public OrderFormat OrderFormat { get; set; } = OrderFormat.NotSet; // 文件命名中的序号格式 } \ No newline at end of file diff --git a/DownKyi.Core/Settings/OrderFormat.cs b/DownKyi.Core/Settings/OrderFormat.cs index 102cad8..627f8a3 100644 --- a/DownKyi.Core/Settings/OrderFormat.cs +++ b/DownKyi.Core/Settings/OrderFormat.cs @@ -2,7 +2,7 @@ public enum OrderFormat { - NOT_SET = 0, - NATURAL, // 自然数 - LEADING_ZEROS, // 前导零填充 + NotSet = 0, + Natural, // 自然数 + LeadingZeros, // 前导零填充 } \ No newline at end of file diff --git a/DownKyi.Core/Settings/ParseScope.cs b/DownKyi.Core/Settings/ParseScope.cs index 837a7ea..22660eb 100644 --- a/DownKyi.Core/Settings/ParseScope.cs +++ b/DownKyi.Core/Settings/ParseScope.cs @@ -2,9 +2,9 @@ public enum ParseScope { - NOT_SET = 0, - NONE = 1, - SELECTED_ITEM, - CURRENT_SECTION, - ALL + NotSet = 0, + None = 1, + SelectedItem, + CurrentSection, + All } \ No newline at end of file diff --git a/DownKyi.Core/Settings/SettingsManager.About.cs b/DownKyi.Core/Settings/SettingsManager.About.cs index f795387..feb7323 100644 --- a/DownKyi.Core/Settings/SettingsManager.About.cs +++ b/DownKyi.Core/Settings/SettingsManager.About.cs @@ -3,26 +3,26 @@ public partial class SettingsManager { // 是否接收测试版更新 - private readonly AllowStatus isReceiveBetaVersion = AllowStatus.NO; + private const AllowStatus IsReceiveBetaVersion = AllowStatus.No; // 是否在启动时自动检查更新 - private readonly AllowStatus autoUpdateWhenLaunch = AllowStatus.YES; + private const AllowStatus AutoUpdateWhenLaunch = AllowStatus.Yes; /// /// 获取是否接收测试版更新 /// /// - public AllowStatus IsReceiveBetaVersion() + public AllowStatus GetIsReceiveBetaVersion() { - appSettings = GetSettings(); - if (appSettings.About.IsReceiveBetaVersion == AllowStatus.NONE) + _appSettings = GetSettings(); + if (_appSettings.About.IsReceiveBetaVersion == AllowStatus.None) { // 第一次获取,先设置默认值 - IsReceiveBetaVersion(isReceiveBetaVersion); - return isReceiveBetaVersion; + SetIsReceiveBetaVersion(IsReceiveBetaVersion); + return IsReceiveBetaVersion; } - return appSettings.About.IsReceiveBetaVersion; + return _appSettings.About.IsReceiveBetaVersion; } /// @@ -30,9 +30,9 @@ public partial class SettingsManager /// /// /// - public bool IsReceiveBetaVersion(AllowStatus isReceiveBetaVersion) + public bool SetIsReceiveBetaVersion(AllowStatus isReceiveBetaVersion) { - appSettings.About.IsReceiveBetaVersion = isReceiveBetaVersion; + _appSettings.About.IsReceiveBetaVersion = isReceiveBetaVersion; return SetSettings(); } @@ -42,15 +42,15 @@ public partial class SettingsManager /// public AllowStatus GetAutoUpdateWhenLaunch() { - appSettings = GetSettings(); - if (appSettings.About.AutoUpdateWhenLaunch == AllowStatus.NONE) + _appSettings = GetSettings(); + if (_appSettings.About.AutoUpdateWhenLaunch == AllowStatus.None) { // 第一次获取,先设置默认值 - SetAutoUpdateWhenLaunch(autoUpdateWhenLaunch); - return autoUpdateWhenLaunch; + SetAutoUpdateWhenLaunch(AutoUpdateWhenLaunch); + return AutoUpdateWhenLaunch; } - return appSettings.About.AutoUpdateWhenLaunch; + return _appSettings.About.AutoUpdateWhenLaunch; } /// @@ -60,7 +60,7 @@ public partial class SettingsManager /// public bool SetAutoUpdateWhenLaunch(AllowStatus autoUpdateWhenLaunch) { - appSettings.About.AutoUpdateWhenLaunch = autoUpdateWhenLaunch; + _appSettings.About.AutoUpdateWhenLaunch = autoUpdateWhenLaunch; return SetSettings(); } } \ No newline at end of file diff --git a/DownKyi.Core/Settings/SettingsManager.Basic.cs b/DownKyi.Core/Settings/SettingsManager.Basic.cs index 4ea2af8..41bdb05 100644 --- a/DownKyi.Core/Settings/SettingsManager.Basic.cs +++ b/DownKyi.Core/Settings/SettingsManager.Basic.cs @@ -3,45 +3,45 @@ public partial class SettingsManager { // 默认下载完成后的操作 - private readonly AfterDownloadOperation _afterDownload = AfterDownloadOperation.NONE; + private const AfterDownloadOperation AfterDownload = AfterDownloadOperation.None; // 是否监听剪贴板 - private readonly AllowStatus _isListenClipboard = AllowStatus.YES; + private const AllowStatus IsListenClipboard = AllowStatus.Yes; // 视频详情页面是否自动解析 - private readonly AllowStatus _isAutoParseVideo = AllowStatus.NO; + private const AllowStatus IsAutoParseVideo = AllowStatus.No; // 默认的视频解析项 - private readonly ParseScope _parseScope = ParseScope.NONE; + private const ParseScope ParseScope = Settings.ParseScope.None; // 解析后自动下载解析视频 - private readonly AllowStatus _isAutoDownloadAll = AllowStatus.NO; + private const AllowStatus IsAutoDownloadAll = AllowStatus.No; // 下载完成列表排序 - private readonly DownloadFinishedSort _finishedSort = DownloadFinishedSort.DownloadAsc; + private const DownloadFinishedSort FinishedSort = DownloadFinishedSort.DownloadAsc; // 重复下载策略 - private readonly RepeatDownloadStrategy _repeatDownloadStrategy = RepeatDownloadStrategy.Ask; + private const RepeatDownloadStrategy RepeatDownloadStrategy = Settings.RepeatDownloadStrategy.Ask; // 重复文件自动添加数字后缀 - private readonly bool _repeatFileAutoAddNumberSuffix = false; - + private const bool RepeatFileAutoAddNumberSuffix = false; + public ThemeMode GetThemeMode() { - appSettings = GetSettings(); - if (appSettings.Basic.ThemeMode == ThemeMode.Default) + _appSettings = GetSettings(); + if (_appSettings.Basic.ThemeMode == ThemeMode.Default) { // 第一次获取,先设置默认值 SetThemeMode(ThemeMode.Default); return ThemeMode.Default; } - return appSettings.Basic.ThemeMode; + return _appSettings.Basic.ThemeMode; } - + public bool SetThemeMode(ThemeMode themeMode) { - appSettings.Basic.ThemeMode = themeMode; + _appSettings.Basic.ThemeMode = themeMode; return SetSettings(); } @@ -51,15 +51,15 @@ public partial class SettingsManager /// public AfterDownloadOperation GetAfterDownloadOperation() { - appSettings = GetSettings(); - if (appSettings.Basic.AfterDownload == AfterDownloadOperation.NOT_SET) + _appSettings = GetSettings(); + if (_appSettings.Basic.AfterDownload == AfterDownloadOperation.NotSet) { // 第一次获取,先设置默认值 - SetAfterDownloadOperation(_afterDownload); - return _afterDownload; + SetAfterDownloadOperation(AfterDownload); + return AfterDownload; } - return appSettings.Basic.AfterDownload; + return _appSettings.Basic.AfterDownload; } /// @@ -69,7 +69,7 @@ public partial class SettingsManager /// public bool SetAfterDownloadOperation(AfterDownloadOperation afterDownload) { - appSettings.Basic.AfterDownload = afterDownload; + _appSettings.Basic.AfterDownload = afterDownload; return SetSettings(); } @@ -77,17 +77,17 @@ public partial class SettingsManager /// 是否监听剪贴板 /// /// - public AllowStatus IsListenClipboard() + public AllowStatus GetIsListenClipboard() { - appSettings = GetSettings(); - if (appSettings.Basic.IsListenClipboard == AllowStatus.NONE) + _appSettings = GetSettings(); + if (_appSettings.Basic.IsListenClipboard == AllowStatus.None) { // 第一次获取,先设置默认值 - IsListenClipboard(_isListenClipboard); - return _isListenClipboard; + SetIsListenClipboard(IsListenClipboard); + return IsListenClipboard; } - return appSettings.Basic.IsListenClipboard; + return _appSettings.Basic.IsListenClipboard; } /// @@ -95,9 +95,9 @@ public partial class SettingsManager /// /// /// - public bool IsListenClipboard(AllowStatus isListen) + public bool SetIsListenClipboard(AllowStatus isListen) { - appSettings.Basic.IsListenClipboard = isListen; + _appSettings.Basic.IsListenClipboard = isListen; return SetSettings(); } @@ -105,27 +105,27 @@ public partial class SettingsManager /// 视频详情页面是否自动解析 /// /// - public AllowStatus IsAutoParseVideo() + public AllowStatus GetIsAutoParseVideo() { - appSettings = GetSettings(); - if (appSettings.Basic.IsAutoParseVideo == AllowStatus.NONE) + _appSettings = GetSettings(); + if (_appSettings.Basic.IsAutoParseVideo == AllowStatus.None) { // 第一次获取,先设置默认值 - IsAutoParseVideo(_isAutoParseVideo); - return _isAutoParseVideo; + SetIsAutoParseVideo(IsAutoParseVideo); + return IsAutoParseVideo; } - return appSettings.Basic.IsAutoParseVideo; + return _appSettings.Basic.IsAutoParseVideo; } /// /// 视频详情页面是否自动解析 /// - /// + /// /// - public bool IsAutoParseVideo(AllowStatus IsAuto) + public bool SetIsAutoParseVideo(AllowStatus isAuto) { - appSettings.Basic.IsAutoParseVideo = IsAuto; + _appSettings.Basic.IsAutoParseVideo = isAuto; return SetSettings(); } @@ -135,15 +135,15 @@ public partial class SettingsManager /// public ParseScope GetParseScope() { - appSettings = GetSettings(); - if (appSettings.Basic.ParseScope == ParseScope.NOT_SET) + _appSettings = GetSettings(); + if (_appSettings.Basic.ParseScope == ParseScope.NotSet) { // 第一次获取,先设置默认值 - SetParseScope(_parseScope); - return _parseScope; + SetParseScope(ParseScope); + return ParseScope; } - return appSettings.Basic.ParseScope; + return _appSettings.Basic.ParseScope; } /// @@ -153,7 +153,7 @@ public partial class SettingsManager /// public bool SetParseScope(ParseScope parseScope) { - appSettings.Basic.ParseScope = parseScope; + _appSettings.Basic.ParseScope = parseScope; return SetSettings(); } @@ -161,17 +161,17 @@ public partial class SettingsManager /// 解析后是否自动下载解析视频 /// /// - public AllowStatus IsAutoDownloadAll() + public AllowStatus GetIsAutoDownloadAll() { - appSettings = GetSettings(); - if (appSettings.Basic.IsAutoDownloadAll == AllowStatus.NONE) + _appSettings = GetSettings(); + if (_appSettings.Basic.IsAutoDownloadAll == AllowStatus.None) { // 第一次获取,先设置默认值 - IsAutoDownloadAll(_isAutoDownloadAll); - return _isAutoDownloadAll; + SetIsAutoDownloadAll(IsAutoDownloadAll); + return IsAutoDownloadAll; } - return appSettings.Basic.IsAutoDownloadAll; + return _appSettings.Basic.IsAutoDownloadAll; } /// @@ -179,9 +179,9 @@ public partial class SettingsManager /// /// /// - public bool IsAutoDownloadAll(AllowStatus isAutoDownloadAll) + public bool SetIsAutoDownloadAll(AllowStatus isAutoDownloadAll) { - appSettings.Basic.IsAutoDownloadAll = isAutoDownloadAll; + _appSettings.Basic.IsAutoDownloadAll = isAutoDownloadAll; return SetSettings(); } @@ -191,15 +191,15 @@ public partial class SettingsManager /// public DownloadFinishedSort GetDownloadFinishedSort() { - appSettings = GetSettings(); - if (appSettings.Basic.DownloadFinishedSort == DownloadFinishedSort.NotSet) + _appSettings = GetSettings(); + if (_appSettings.Basic.DownloadFinishedSort == DownloadFinishedSort.NotSet) { // 第一次获取,先设置默认值 - SetDownloadFinishedSort(_finishedSort); - return _finishedSort; + SetDownloadFinishedSort(FinishedSort); + return FinishedSort; } - return appSettings.Basic.DownloadFinishedSort; + return _appSettings.Basic.DownloadFinishedSort; } /// @@ -209,7 +209,7 @@ public partial class SettingsManager /// public bool SetDownloadFinishedSort(DownloadFinishedSort finishedSort) { - appSettings.Basic.DownloadFinishedSort = finishedSort; + _appSettings.Basic.DownloadFinishedSort = finishedSort; return SetSettings(); } @@ -219,15 +219,15 @@ public partial class SettingsManager /// public RepeatDownloadStrategy GetRepeatDownloadStrategy() { - appSettings = GetSettings(); - if (appSettings.Basic.RepeatDownloadStrategy == RepeatDownloadStrategy.Ask) + _appSettings = GetSettings(); + if (_appSettings.Basic.RepeatDownloadStrategy == RepeatDownloadStrategy.Ask) { // 第一次获取,先设置默认值 - SetRepeatDownloadStrategy(_repeatDownloadStrategy); - return _repeatDownloadStrategy; + SetRepeatDownloadStrategy(RepeatDownloadStrategy); + return RepeatDownloadStrategy; } - return appSettings.Basic.RepeatDownloadStrategy; + return _appSettings.Basic.RepeatDownloadStrategy; } /// @@ -237,7 +237,7 @@ public partial class SettingsManager /// public bool SetRepeatDownloadStrategy(RepeatDownloadStrategy repeatDownloadStrategy) { - appSettings.Basic.RepeatDownloadStrategy = repeatDownloadStrategy; + _appSettings.Basic.RepeatDownloadStrategy = repeatDownloadStrategy; return SetSettings(); } @@ -247,15 +247,15 @@ public partial class SettingsManager /// public bool IsRepeatFileAutoAddNumberSuffix() { - appSettings = GetSettings(); - if (appSettings.Basic.RepeatFileAutoAddNumberSuffix == false) + _appSettings = GetSettings(); + if (_appSettings.Basic.RepeatFileAutoAddNumberSuffix == false) { // 第一次获取,先设置默认值 - IsRepeatFileAutoAddNumberSuffix(_repeatFileAutoAddNumberSuffix); - return _repeatFileAutoAddNumberSuffix; + IsRepeatFileAutoAddNumberSuffix(RepeatFileAutoAddNumberSuffix); + return RepeatFileAutoAddNumberSuffix; } - return appSettings.Basic.RepeatFileAutoAddNumberSuffix; + return _appSettings.Basic.RepeatFileAutoAddNumberSuffix; } /// @@ -266,7 +266,7 @@ public partial class SettingsManager /// public bool IsRepeatFileAutoAddNumberSuffix(bool repeatFileAutoAddNumberSuffix) { - appSettings.Basic.RepeatFileAutoAddNumberSuffix = repeatFileAutoAddNumberSuffix; + _appSettings.Basic.RepeatFileAutoAddNumberSuffix = repeatFileAutoAddNumberSuffix; return SetSettings(); } } \ No newline at end of file diff --git a/DownKyi.Core/Settings/SettingsManager.Danmaku.cs b/DownKyi.Core/Settings/SettingsManager.Danmaku.cs index cf5cebb..5eefba3 100644 --- a/DownKyi.Core/Settings/SettingsManager.Danmaku.cs +++ b/DownKyi.Core/Settings/SettingsManager.Danmaku.cs @@ -3,34 +3,34 @@ public partial class SettingsManager { // 是否屏蔽顶部弹幕 - private readonly AllowStatus danmakuTopFilter = AllowStatus.NO; + private const AllowStatus DanmakuTopFilter = AllowStatus.No; // 是否屏蔽底部弹幕 - private readonly AllowStatus danmakuBottomFilter = AllowStatus.NO; + private const AllowStatus DanmakuBottomFilter = AllowStatus.No; // 是否屏蔽滚动弹幕 - private readonly AllowStatus danmakuScrollFilter = AllowStatus.NO; + private const AllowStatus DanmakuScrollFilter = AllowStatus.No; // 是否自定义分辨率 - private readonly AllowStatus isCustomDanmakuResolution = AllowStatus.NO; + private const AllowStatus IsCustomDanmakuResolution = AllowStatus.No; // 分辨率-宽 - private readonly int danmakuScreenWidth = 1920; + private const int DanmakuScreenWidth = 1920; // 分辨率-高 - private readonly int danmakuScreenHeight = 1080; + private const int DanmakuScreenHeight = 1080; // 弹幕字体 - private readonly string danmakuFontName = "黑体"; + private const string DanmakuFontName = "黑体"; // 弹幕字体大小 - private readonly int danmakuFontSize = 50; + private const int DanmakuFontSize = 50; // 弹幕限制行数 - private readonly int danmakuLineCount = 0; + private const int DanmakuLineCount = 0; // 弹幕布局算法 - private readonly DanmakuLayoutAlgorithm danmakuLayoutAlgorithm = DanmakuLayoutAlgorithm.SYNC; + private const DanmakuLayoutAlgorithm DanmakuLayoutAlgorithm = Settings.DanmakuLayoutAlgorithm.Sync; /// @@ -39,15 +39,15 @@ public partial class SettingsManager /// public AllowStatus GetDanmakuTopFilter() { - appSettings = GetSettings(); - if (appSettings.Danmaku.DanmakuTopFilter == AllowStatus.NONE) + _appSettings = GetSettings(); + if (_appSettings.Danmaku.DanmakuTopFilter == AllowStatus.None) { // 第一次获取,先设置默认值 - SetDanmakuTopFilter(danmakuTopFilter); - return danmakuTopFilter; + SetDanmakuTopFilter(DanmakuTopFilter); + return DanmakuTopFilter; } - return appSettings.Danmaku.DanmakuTopFilter; + return _appSettings.Danmaku.DanmakuTopFilter; } /// @@ -57,7 +57,7 @@ public partial class SettingsManager /// public bool SetDanmakuTopFilter(AllowStatus danmakuFilter) { - appSettings.Danmaku.DanmakuTopFilter = danmakuFilter; + _appSettings.Danmaku.DanmakuTopFilter = danmakuFilter; return SetSettings(); } @@ -67,15 +67,15 @@ public partial class SettingsManager /// public AllowStatus GetDanmakuBottomFilter() { - appSettings = GetSettings(); - if (appSettings.Danmaku.DanmakuBottomFilter == AllowStatus.NONE) + _appSettings = GetSettings(); + if (_appSettings.Danmaku.DanmakuBottomFilter == AllowStatus.None) { // 第一次获取,先设置默认值 - SetDanmakuBottomFilter(danmakuBottomFilter); - return danmakuBottomFilter; + SetDanmakuBottomFilter(DanmakuBottomFilter); + return DanmakuBottomFilter; } - return appSettings.Danmaku.DanmakuBottomFilter; + return _appSettings.Danmaku.DanmakuBottomFilter; } /// @@ -85,7 +85,7 @@ public partial class SettingsManager /// public bool SetDanmakuBottomFilter(AllowStatus danmakuFilter) { - appSettings.Danmaku.DanmakuBottomFilter = danmakuFilter; + _appSettings.Danmaku.DanmakuBottomFilter = danmakuFilter; return SetSettings(); } @@ -95,15 +95,15 @@ public partial class SettingsManager /// public AllowStatus GetDanmakuScrollFilter() { - appSettings = GetSettings(); - if (appSettings.Danmaku.DanmakuScrollFilter == AllowStatus.NONE) + _appSettings = GetSettings(); + if (_appSettings.Danmaku.DanmakuScrollFilter == AllowStatus.None) { // 第一次获取,先设置默认值 - SetDanmakuScrollFilter(danmakuScrollFilter); - return danmakuScrollFilter; + SetDanmakuScrollFilter(DanmakuScrollFilter); + return DanmakuScrollFilter; } - return appSettings.Danmaku.DanmakuScrollFilter; + return _appSettings.Danmaku.DanmakuScrollFilter; } /// @@ -113,7 +113,7 @@ public partial class SettingsManager /// public bool SetDanmakuScrollFilter(AllowStatus danmakuFilter) { - appSettings.Danmaku.DanmakuScrollFilter = danmakuFilter; + _appSettings.Danmaku.DanmakuScrollFilter = danmakuFilter; return SetSettings(); } @@ -121,17 +121,17 @@ public partial class SettingsManager /// 获取是否自定义分辨率 /// /// - public AllowStatus IsCustomDanmakuResolution() + public AllowStatus GetIsCustomDanmakuResolution() { - appSettings = GetSettings(); - if (appSettings.Danmaku.IsCustomDanmakuResolution == AllowStatus.NONE) + _appSettings = GetSettings(); + if (_appSettings.Danmaku.IsCustomDanmakuResolution == AllowStatus.None) { // 第一次获取,先设置默认值 - IsCustomDanmakuResolution(isCustomDanmakuResolution); - return isCustomDanmakuResolution; + SetIsCustomDanmakuResolution(IsCustomDanmakuResolution); + return IsCustomDanmakuResolution; } - return appSettings.Danmaku.IsCustomDanmakuResolution; + return _appSettings.Danmaku.IsCustomDanmakuResolution; } /// @@ -139,9 +139,9 @@ public partial class SettingsManager /// /// /// - public bool IsCustomDanmakuResolution(AllowStatus isCustomResolution) + public bool SetIsCustomDanmakuResolution(AllowStatus isCustomResolution) { - appSettings.Danmaku.IsCustomDanmakuResolution = isCustomResolution; + _appSettings.Danmaku.IsCustomDanmakuResolution = isCustomResolution; return SetSettings(); } @@ -151,15 +151,15 @@ public partial class SettingsManager /// public int GetDanmakuScreenWidth() { - appSettings = GetSettings(); - if (appSettings.Danmaku.DanmakuScreenWidth == -1) + _appSettings = GetSettings(); + if (_appSettings.Danmaku.DanmakuScreenWidth == -1) { // 第一次获取,先设置默认值 - SetDanmakuScreenWidth(danmakuScreenWidth); - return danmakuScreenWidth; + SetDanmakuScreenWidth(DanmakuScreenWidth); + return DanmakuScreenWidth; } - return appSettings.Danmaku.DanmakuScreenWidth; + return _appSettings.Danmaku.DanmakuScreenWidth; } /// @@ -169,7 +169,7 @@ public partial class SettingsManager /// public bool SetDanmakuScreenWidth(int screenWidth) { - appSettings.Danmaku.DanmakuScreenWidth = screenWidth; + _appSettings.Danmaku.DanmakuScreenWidth = screenWidth; return SetSettings(); } @@ -179,15 +179,15 @@ public partial class SettingsManager /// public int GetDanmakuScreenHeight() { - appSettings = GetSettings(); - if (appSettings.Danmaku.DanmakuScreenHeight == -1) + _appSettings = GetSettings(); + if (_appSettings.Danmaku.DanmakuScreenHeight == -1) { // 第一次获取,先设置默认值 - SetDanmakuScreenHeight(danmakuScreenHeight); - return danmakuScreenHeight; + SetDanmakuScreenHeight(DanmakuScreenHeight); + return DanmakuScreenHeight; } - return appSettings.Danmaku.DanmakuScreenHeight; + return _appSettings.Danmaku.DanmakuScreenHeight; } /// @@ -197,7 +197,7 @@ public partial class SettingsManager /// public bool SetDanmakuScreenHeight(int screenHeight) { - appSettings.Danmaku.DanmakuScreenHeight = screenHeight; + _appSettings.Danmaku.DanmakuScreenHeight = screenHeight; return SetSettings(); } @@ -207,15 +207,15 @@ public partial class SettingsManager /// public string GetDanmakuFontName() { - appSettings = GetSettings(); - if (appSettings.Danmaku.DanmakuFontName == null) + _appSettings = GetSettings(); + if (_appSettings.Danmaku.DanmakuFontName == null) { // 第一次获取,先设置默认值 - SetDanmakuFontName(danmakuFontName); - return danmakuFontName; + SetDanmakuFontName(DanmakuFontName); + return DanmakuFontName; } - return appSettings.Danmaku.DanmakuFontName; + return _appSettings.Danmaku.DanmakuFontName; } /// @@ -225,7 +225,7 @@ public partial class SettingsManager /// public bool SetDanmakuFontName(string danmakuFontName) { - appSettings.Danmaku.DanmakuFontName = danmakuFontName; + _appSettings.Danmaku.DanmakuFontName = danmakuFontName; return SetSettings(); } @@ -235,15 +235,15 @@ public partial class SettingsManager /// public int GetDanmakuFontSize() { - appSettings = GetSettings(); - if (appSettings.Danmaku.DanmakuFontSize == -1) + _appSettings = GetSettings(); + if (_appSettings.Danmaku.DanmakuFontSize == -1) { // 第一次获取,先设置默认值 - SetDanmakuFontSize(danmakuFontSize); - return danmakuFontSize; + SetDanmakuFontSize(DanmakuFontSize); + return DanmakuFontSize; } - return appSettings.Danmaku.DanmakuFontSize; + return _appSettings.Danmaku.DanmakuFontSize; } /// @@ -253,7 +253,7 @@ public partial class SettingsManager /// public bool SetDanmakuFontSize(int danmakuFontSize) { - appSettings.Danmaku.DanmakuFontSize = danmakuFontSize; + _appSettings.Danmaku.DanmakuFontSize = danmakuFontSize; return SetSettings(); } @@ -263,15 +263,15 @@ public partial class SettingsManager /// public int GetDanmakuLineCount() { - appSettings = GetSettings(); - if (appSettings.Danmaku.DanmakuLineCount == -1) + _appSettings = GetSettings(); + if (_appSettings.Danmaku.DanmakuLineCount == -1) { // 第一次获取,先设置默认值 - SetDanmakuLineCount(danmakuLineCount); - return danmakuLineCount; + SetDanmakuLineCount(DanmakuLineCount); + return DanmakuLineCount; } - return appSettings.Danmaku.DanmakuLineCount; + return _appSettings.Danmaku.DanmakuLineCount; } /// @@ -281,7 +281,7 @@ public partial class SettingsManager /// public bool SetDanmakuLineCount(int danmakuLineCount) { - appSettings.Danmaku.DanmakuLineCount = danmakuLineCount; + _appSettings.Danmaku.DanmakuLineCount = danmakuLineCount; return SetSettings(); } @@ -291,15 +291,15 @@ public partial class SettingsManager /// public DanmakuLayoutAlgorithm GetDanmakuLayoutAlgorithm() { - appSettings = GetSettings(); - if (appSettings.Danmaku.DanmakuLayoutAlgorithm == DanmakuLayoutAlgorithm.NONE) + _appSettings = GetSettings(); + if (_appSettings.Danmaku.DanmakuLayoutAlgorithm == DanmakuLayoutAlgorithm.None) { // 第一次获取,先设置默认值 - SetDanmakuLayoutAlgorithm(danmakuLayoutAlgorithm); - return danmakuLayoutAlgorithm; + SetDanmakuLayoutAlgorithm(DanmakuLayoutAlgorithm); + return DanmakuLayoutAlgorithm; } - return appSettings.Danmaku.DanmakuLayoutAlgorithm; + return _appSettings.Danmaku.DanmakuLayoutAlgorithm; } /// @@ -309,7 +309,7 @@ public partial class SettingsManager /// public bool SetDanmakuLayoutAlgorithm(DanmakuLayoutAlgorithm danmakuLayoutAlgorithm) { - appSettings.Danmaku.DanmakuLayoutAlgorithm = danmakuLayoutAlgorithm; + _appSettings.Danmaku.DanmakuLayoutAlgorithm = danmakuLayoutAlgorithm; return SetSettings(); } } \ No newline at end of file diff --git a/DownKyi.Core/Settings/SettingsManager.Network.cs b/DownKyi.Core/Settings/SettingsManager.Network.cs index 6c9138f..cb60392 100644 --- a/DownKyi.Core/Settings/SettingsManager.Network.cs +++ b/DownKyi.Core/Settings/SettingsManager.Network.cs @@ -7,73 +7,72 @@ namespace DownKyi.Core.Settings public partial class SettingsManager { // 是否开启解除地区限制 - private readonly AllowStatus isLiftingOfRegion = AllowStatus.YES; + private const AllowStatus IsLiftingOfRegion = AllowStatus.Yes; // 启用https - private readonly AllowStatus useSSL = AllowStatus.YES; + private const AllowStatus UseSsl = AllowStatus.Yes; // UserAgent - private readonly string userAgent = - "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"; + private const string UserAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"; // 下载器 - private readonly Downloader downloader = Downloader.ARIA; + private const Downloader Downloader = Settings.Downloader.Aria; // 最大同时下载数(任务数) - private readonly int maxCurrentDownloads = 3; + private const int MaxCurrentDownloads = 3; // 单文件最大线程数 - private readonly int split = 8; + private const int Split = 8; // HttpProxy代理 - private readonly AllowStatus isHttpProxy = AllowStatus.NO; - private readonly string httpProxy = string.Empty; - private readonly int httpProxyListenPort = 0; + private const AllowStatus IsHttpProxy = AllowStatus.No; + private readonly string _httpProxy = string.Empty; + private const int HttpProxyListenPort = 0; // Aria服务器token - private readonly string ariaToken = "downkyi"; + private const string AriaToken = "downkyi"; // Aria服务器host - private readonly string ariaHost = "http://localhost"; + private const string AriaHost = "http://localhost"; // Aria服务器端口号 - private readonly int ariaListenPort = 6800; + private const int AriaListenPort = 6800; // Aria日志等级 - private readonly AriaConfigLogLevel ariaLogLevel = AriaConfigLogLevel.INFO; + private const AriaConfigLogLevel AriaLogLevel = AriaConfigLogLevel.INFO; // Aria单文件最大线程数 - private readonly int ariaSplit = 5; + private const int AriaSplit = 5; // Aria下载速度限制 - private readonly int ariaMaxOverallDownloadLimit = 0; + private const int AriaMaxOverallDownloadLimit = 0; // Aria下载单文件速度限制 - private readonly int ariaMaxDownloadLimit = 0; + private const int AriaMaxDownloadLimit = 0; // Aria文件预分配 - private readonly AriaConfigFileAllocation ariaFileAllocation = AriaConfigFileAllocation.NONE; + private const AriaConfigFileAllocation AriaFileAllocation = AriaConfigFileAllocation.NONE; // Aria HttpProxy代理 - private readonly AllowStatus isAriaHttpProxy = AllowStatus.NO; - private readonly string ariaHttpProxy = string.Empty; - private readonly int ariaHttpProxyListenPort = 0; + private const AllowStatus IsAriaHttpProxy = AllowStatus.No; + private readonly string _ariaHttpProxy = string.Empty; + private const int AriaHttpProxyListenPort = 0; /// /// 获取是否解除地区限制 /// /// - public AllowStatus IsLiftingOfRegion() + public AllowStatus GetIsLiftingOfRegion() { - appSettings = GetSettings(); - if (appSettings.Network.IsLiftingOfRegion == AllowStatus.NONE) + _appSettings = GetSettings(); + if (_appSettings.Network.IsLiftingOfRegion == AllowStatus.None) { // 第一次获取,先设置默认值 - IsLiftingOfRegion(isLiftingOfRegion); - return isLiftingOfRegion; + SetIsLiftingOfRegion(IsLiftingOfRegion); + return IsLiftingOfRegion; } - return appSettings.Network.IsLiftingOfRegion; + return _appSettings.Network.IsLiftingOfRegion; } /// @@ -81,9 +80,9 @@ namespace DownKyi.Core.Settings /// /// /// - public bool IsLiftingOfRegion(AllowStatus isLiftingOfRegion) + public bool SetIsLiftingOfRegion(AllowStatus isLiftingOfRegion) { - appSettings.Network.IsLiftingOfRegion = isLiftingOfRegion; + _appSettings.Network.IsLiftingOfRegion = isLiftingOfRegion; return SetSettings(); } @@ -91,27 +90,27 @@ namespace DownKyi.Core.Settings /// 获取是否启用https /// /// - public AllowStatus UseSSL() + public AllowStatus GetUseSsl() { - appSettings = GetSettings(); - if (appSettings.Network.UseSSL == AllowStatus.NONE) + _appSettings = GetSettings(); + if (_appSettings.Network.UseSsl == AllowStatus.None) { // 第一次获取,先设置默认值 - UseSSL(useSSL); - return useSSL; + SetUseSsl(UseSsl); + return UseSsl; } - return appSettings.Network.UseSSL; + return _appSettings.Network.UseSsl; } /// /// 设置是否启用https /// - /// + /// /// - public bool UseSSL(AllowStatus useSSL) + public bool SetUseSsl(AllowStatus useSsl) { - appSettings.Network.UseSSL = useSSL; + _appSettings.Network.UseSsl = useSsl; return SetSettings(); } @@ -121,15 +120,15 @@ namespace DownKyi.Core.Settings /// public string GetUserAgent() { - appSettings = GetSettings(); - if (appSettings.Network.UserAgent == string.Empty) + _appSettings = GetSettings(); + if (_appSettings.Network.UserAgent == string.Empty) { // 第一次获取,先设置默认值 - SetUserAgent(userAgent); - return userAgent; + SetUserAgent(UserAgent); + return UserAgent; } - return appSettings.Network.UserAgent; + return _appSettings.Network.UserAgent; } /// @@ -139,7 +138,7 @@ namespace DownKyi.Core.Settings /// public bool SetUserAgent(string userAgent) { - appSettings.Network.UserAgent = userAgent; + _appSettings.Network.UserAgent = userAgent; return SetSettings(); } @@ -149,11 +148,11 @@ namespace DownKyi.Core.Settings /// public Downloader GetDownloader() { - appSettings = GetSettings(); - if (appSettings.Network.Downloader != Downloader.NOT_SET) return appSettings.Network.Downloader; + _appSettings = GetSettings(); + if (_appSettings.Network.Downloader != Downloader.NotSet) return _appSettings.Network.Downloader; // 第一次获取,先设置默认值 - SetDownloader(downloader); - return downloader; + SetDownloader(Downloader); + return Downloader; } /// @@ -163,7 +162,7 @@ namespace DownKyi.Core.Settings /// public bool SetDownloader(Downloader downloader) { - appSettings.Network.Downloader = downloader; + _appSettings.Network.Downloader = downloader; return SetSettings(); } @@ -173,11 +172,11 @@ namespace DownKyi.Core.Settings /// public int GetMaxCurrentDownloads() { - appSettings = GetSettings(); - if (appSettings.Network.MaxCurrentDownloads != -1) return appSettings.Network.MaxCurrentDownloads; + _appSettings = GetSettings(); + if (_appSettings.Network.MaxCurrentDownloads != -1) return _appSettings.Network.MaxCurrentDownloads; // 第一次获取,先设置默认值 - SetMaxCurrentDownloads(maxCurrentDownloads); - return maxCurrentDownloads; + SetMaxCurrentDownloads(MaxCurrentDownloads); + return MaxCurrentDownloads; } /// @@ -187,7 +186,7 @@ namespace DownKyi.Core.Settings /// public bool SetMaxCurrentDownloads(int maxCurrentDownloads) { - appSettings.Network.MaxCurrentDownloads = maxCurrentDownloads; + _appSettings.Network.MaxCurrentDownloads = maxCurrentDownloads; return SetSettings(); } @@ -197,11 +196,11 @@ namespace DownKyi.Core.Settings /// public int GetSplit() { - appSettings = GetSettings(); - if (appSettings.Network.Split != -1) return appSettings.Network.Split; + _appSettings = GetSettings(); + if (_appSettings.Network.Split != -1) return _appSettings.Network.Split; // 第一次获取,先设置默认值 - SetSplit(split); - return split; + SetSplit(Split); + return Split; } /// @@ -211,7 +210,7 @@ namespace DownKyi.Core.Settings /// public bool SetSplit(int split) { - appSettings.Network.Split = split; + _appSettings.Network.Split = split; return SetSettings(); } @@ -219,13 +218,13 @@ namespace DownKyi.Core.Settings /// 获取是否开启Http代理 /// /// - public AllowStatus IsHttpProxy() + public AllowStatus GetIsHttpProxy() { - appSettings = GetSettings(); - if (appSettings.Network.IsHttpProxy != AllowStatus.NONE) return appSettings.Network.IsHttpProxy; + _appSettings = GetSettings(); + if (_appSettings.Network.IsHttpProxy != AllowStatus.None) return _appSettings.Network.IsHttpProxy; // 第一次获取,先设置默认值 - IsHttpProxy(isHttpProxy); - return isHttpProxy; + SetIsHttpProxy(IsHttpProxy); + return IsHttpProxy; } /// @@ -233,9 +232,9 @@ namespace DownKyi.Core.Settings /// /// /// - public bool IsHttpProxy(AllowStatus isHttpProxy) + public bool SetIsHttpProxy(AllowStatus isHttpProxy) { - appSettings.Network.IsHttpProxy = isHttpProxy; + _appSettings.Network.IsHttpProxy = isHttpProxy; return SetSettings(); } @@ -245,11 +244,11 @@ namespace DownKyi.Core.Settings /// public string GetHttpProxy() { - appSettings = GetSettings(); - if (appSettings.Network.HttpProxy != null) return appSettings.Network.HttpProxy; + _appSettings = GetSettings(); + if (_appSettings.Network.HttpProxy != null) return _appSettings.Network.HttpProxy; // 第一次获取,先设置默认值 - SetHttpProxy(httpProxy); - return httpProxy; + SetHttpProxy(_httpProxy); + return _httpProxy; } /// @@ -259,7 +258,7 @@ namespace DownKyi.Core.Settings /// public bool SetHttpProxy(string httpProxy) { - appSettings.Network.HttpProxy = httpProxy; + _appSettings.Network.HttpProxy = httpProxy; return SetSettings(); } @@ -269,11 +268,11 @@ namespace DownKyi.Core.Settings /// public int GetHttpProxyListenPort() { - appSettings = GetSettings(); - if (appSettings.Network.HttpProxyListenPort != -1) return appSettings.Network.HttpProxyListenPort; + _appSettings = GetSettings(); + if (_appSettings.Network.HttpProxyListenPort != -1) return _appSettings.Network.HttpProxyListenPort; // 第一次获取,先设置默认值 - SetHttpProxyListenPort(httpProxyListenPort); - return httpProxyListenPort; + SetHttpProxyListenPort(HttpProxyListenPort); + return HttpProxyListenPort; } /// @@ -283,7 +282,7 @@ namespace DownKyi.Core.Settings /// public bool SetHttpProxyListenPort(int httpProxyListenPort) { - appSettings.Network.HttpProxyListenPort = httpProxyListenPort; + _appSettings.Network.HttpProxyListenPort = httpProxyListenPort; return SetSettings(); } @@ -293,15 +292,15 @@ namespace DownKyi.Core.Settings /// public string GetAriaToken() { - appSettings = GetSettings(); - if (appSettings.Network.AriaToken == null) + _appSettings = GetSettings(); + if (_appSettings.Network.AriaToken == null) { // 第一次获取,先设置默认值 - SetHttpProxy(ariaToken); - return ariaToken; + SetAriaToken(AriaToken); + return AriaToken; } - return appSettings.Network.AriaToken; + return _appSettings.Network.AriaToken; } /// @@ -311,7 +310,7 @@ namespace DownKyi.Core.Settings /// public bool SetAriaToken(string token) { - appSettings.Network.AriaToken = token; + _appSettings.Network.AriaToken = token; return SetSettings(); } @@ -321,15 +320,15 @@ namespace DownKyi.Core.Settings /// public string GetAriaHost() { - appSettings = GetSettings(); - if (appSettings.Network.AriaHost == null) + _appSettings = GetSettings(); + if (_appSettings.Network.AriaHost == null) { // 第一次获取,先设置默认值 - SetHttpProxy(ariaHost); - return ariaHost; + SetAriaHost(AriaHost); + return AriaHost; } - return appSettings.Network.AriaHost; + return _appSettings.Network.AriaHost; } /// @@ -339,7 +338,7 @@ namespace DownKyi.Core.Settings /// public bool SetAriaHost(string host) { - appSettings.Network.AriaHost = host; + _appSettings.Network.AriaHost = host; return SetSettings(); } @@ -349,15 +348,15 @@ namespace DownKyi.Core.Settings /// public int GetAriaListenPort() { - appSettings = GetSettings(); - if (appSettings.Network.AriaListenPort == -1) + _appSettings = GetSettings(); + if (_appSettings.Network.AriaListenPort == -1) { // 第一次获取,先设置默认值 - SetAriaListenPort(ariaListenPort); - return ariaListenPort; + SetAriaListenPort(AriaListenPort); + return AriaListenPort; } - return appSettings.Network.AriaListenPort; + return _appSettings.Network.AriaListenPort; } /// @@ -367,7 +366,7 @@ namespace DownKyi.Core.Settings /// public bool SetAriaListenPort(int ariaListenPort) { - appSettings.Network.AriaListenPort = ariaListenPort; + _appSettings.Network.AriaListenPort = ariaListenPort; return SetSettings(); } @@ -377,15 +376,15 @@ namespace DownKyi.Core.Settings /// public AriaConfigLogLevel GetAriaLogLevel() { - appSettings = GetSettings(); - if (appSettings.Network.AriaLogLevel == AriaConfigLogLevel.NOT_SET) + _appSettings = GetSettings(); + if (_appSettings.Network.AriaLogLevel == AriaConfigLogLevel.NOT_SET) { // 第一次获取,先设置默认值 - SetAriaLogLevel(ariaLogLevel); - return ariaLogLevel; + SetAriaLogLevel(AriaLogLevel); + return AriaLogLevel; } - return appSettings.Network.AriaLogLevel; + return _appSettings.Network.AriaLogLevel; } /// @@ -395,7 +394,7 @@ namespace DownKyi.Core.Settings /// public bool SetAriaLogLevel(AriaConfigLogLevel ariaLogLevel) { - appSettings.Network.AriaLogLevel = ariaLogLevel; + _appSettings.Network.AriaLogLevel = ariaLogLevel; return SetSettings(); } @@ -405,15 +404,15 @@ namespace DownKyi.Core.Settings /// public int GetAriaSplit() { - appSettings = GetSettings(); - if (appSettings.Network.AriaSplit == -1) + _appSettings = GetSettings(); + if (_appSettings.Network.AriaSplit == -1) { // 第一次获取,先设置默认值 - SetAriaSplit(ariaSplit); - return ariaSplit; + SetAriaSplit(AriaSplit); + return AriaSplit; } - return appSettings.Network.AriaSplit; + return _appSettings.Network.AriaSplit; } /// @@ -423,7 +422,7 @@ namespace DownKyi.Core.Settings /// public bool SetAriaSplit(int ariaSplit) { - appSettings.Network.AriaSplit = ariaSplit; + _appSettings.Network.AriaSplit = ariaSplit; return SetSettings(); } @@ -433,15 +432,15 @@ namespace DownKyi.Core.Settings /// public int GetAriaMaxOverallDownloadLimit() { - appSettings = GetSettings(); - if (appSettings.Network.AriaMaxOverallDownloadLimit == -1) + _appSettings = GetSettings(); + if (_appSettings.Network.AriaMaxOverallDownloadLimit == -1) { // 第一次获取,先设置默认值 - SetAriaMaxOverallDownloadLimit(ariaMaxOverallDownloadLimit); - return ariaMaxOverallDownloadLimit; + SetAriaMaxOverallDownloadLimit(AriaMaxOverallDownloadLimit); + return AriaMaxOverallDownloadLimit; } - return appSettings.Network.AriaMaxOverallDownloadLimit; + return _appSettings.Network.AriaMaxOverallDownloadLimit; } /// @@ -451,7 +450,7 @@ namespace DownKyi.Core.Settings /// public bool SetAriaMaxOverallDownloadLimit(int ariaMaxOverallDownloadLimit) { - appSettings.Network.AriaMaxOverallDownloadLimit = ariaMaxOverallDownloadLimit; + _appSettings.Network.AriaMaxOverallDownloadLimit = ariaMaxOverallDownloadLimit; return SetSettings(); } @@ -461,15 +460,15 @@ namespace DownKyi.Core.Settings /// public int GetAriaMaxDownloadLimit() { - appSettings = GetSettings(); - if (appSettings.Network.AriaMaxDownloadLimit == -1) + _appSettings = GetSettings(); + if (_appSettings.Network.AriaMaxDownloadLimit == -1) { // 第一次获取,先设置默认值 - SetAriaMaxDownloadLimit(ariaMaxDownloadLimit); - return ariaMaxDownloadLimit; + SetAriaMaxDownloadLimit(AriaMaxDownloadLimit); + return AriaMaxDownloadLimit; } - return appSettings.Network.AriaMaxDownloadLimit; + return _appSettings.Network.AriaMaxDownloadLimit; } /// @@ -479,7 +478,7 @@ namespace DownKyi.Core.Settings /// public bool SetAriaMaxDownloadLimit(int ariaMaxDownloadLimit) { - appSettings.Network.AriaMaxDownloadLimit = ariaMaxDownloadLimit; + _appSettings.Network.AriaMaxDownloadLimit = ariaMaxDownloadLimit; return SetSettings(); } @@ -489,15 +488,15 @@ namespace DownKyi.Core.Settings /// public AriaConfigFileAllocation GetAriaFileAllocation() { - appSettings = GetSettings(); - if (appSettings.Network.AriaFileAllocation == AriaConfigFileAllocation.NOT_SET) + _appSettings = GetSettings(); + if (_appSettings.Network.AriaFileAllocation == AriaConfigFileAllocation.NOT_SET) { // 第一次获取,先设置默认值 - SetAriaFileAllocation(ariaFileAllocation); - return ariaFileAllocation; + SetAriaFileAllocation(AriaFileAllocation); + return AriaFileAllocation; } - return appSettings.Network.AriaFileAllocation; + return _appSettings.Network.AriaFileAllocation; } /// @@ -507,7 +506,7 @@ namespace DownKyi.Core.Settings /// public bool SetAriaFileAllocation(AriaConfigFileAllocation ariaFileAllocation) { - appSettings.Network.AriaFileAllocation = ariaFileAllocation; + _appSettings.Network.AriaFileAllocation = ariaFileAllocation; return SetSettings(); } @@ -515,17 +514,17 @@ namespace DownKyi.Core.Settings /// 获取是否开启Aria http代理 /// /// - public AllowStatus IsAriaHttpProxy() + public AllowStatus GetIsAriaHttpProxy() { - appSettings = GetSettings(); - if (appSettings.Network.IsAriaHttpProxy == AllowStatus.NONE) + _appSettings = GetSettings(); + if (_appSettings.Network.IsAriaHttpProxy == AllowStatus.None) { // 第一次获取,先设置默认值 - IsAriaHttpProxy(isAriaHttpProxy); - return isAriaHttpProxy; + SetIsAriaHttpProxy(IsAriaHttpProxy); + return IsAriaHttpProxy; } - return appSettings.Network.IsAriaHttpProxy; + return _appSettings.Network.IsAriaHttpProxy; } /// @@ -533,9 +532,9 @@ namespace DownKyi.Core.Settings /// /// /// - public bool IsAriaHttpProxy(AllowStatus isAriaHttpProxy) + public bool SetIsAriaHttpProxy(AllowStatus isAriaHttpProxy) { - appSettings.Network.IsAriaHttpProxy = isAriaHttpProxy; + _appSettings.Network.IsAriaHttpProxy = isAriaHttpProxy; return SetSettings(); } @@ -545,15 +544,15 @@ namespace DownKyi.Core.Settings /// public string GetAriaHttpProxy() { - appSettings = GetSettings(); - if (appSettings.Network.AriaHttpProxy == null) + _appSettings = GetSettings(); + if (_appSettings.Network.AriaHttpProxy == null) { // 第一次获取,先设置默认值 - SetAriaHttpProxy(ariaHttpProxy); - return ariaHttpProxy; + SetAriaHttpProxy(_ariaHttpProxy); + return _ariaHttpProxy; } - return appSettings.Network.AriaHttpProxy; + return _appSettings.Network.AriaHttpProxy; } /// @@ -563,7 +562,7 @@ namespace DownKyi.Core.Settings /// public bool SetAriaHttpProxy(string ariaHttpProxy) { - appSettings.Network.AriaHttpProxy = ariaHttpProxy; + _appSettings.Network.AriaHttpProxy = ariaHttpProxy; return SetSettings(); } @@ -573,15 +572,15 @@ namespace DownKyi.Core.Settings /// public int GetAriaHttpProxyListenPort() { - appSettings = GetSettings(); - if (appSettings.Network.AriaHttpProxyListenPort == -1) + _appSettings = GetSettings(); + if (_appSettings.Network.AriaHttpProxyListenPort == -1) { // 第一次获取,先设置默认值 - SetAriaHttpProxyListenPort(ariaHttpProxyListenPort); - return ariaHttpProxyListenPort; + SetAriaHttpProxyListenPort(AriaHttpProxyListenPort); + return AriaHttpProxyListenPort; } - return appSettings.Network.AriaHttpProxyListenPort; + return _appSettings.Network.AriaHttpProxyListenPort; } /// @@ -591,7 +590,7 @@ namespace DownKyi.Core.Settings /// public bool SetAriaHttpProxyListenPort(int ariaHttpProxyListenPort) { - appSettings.Network.AriaHttpProxyListenPort = ariaHttpProxyListenPort; + _appSettings.Network.AriaHttpProxyListenPort = ariaHttpProxyListenPort; return SetSettings(); } } diff --git a/DownKyi.Core/Settings/SettingsManager.UserInfo.cs b/DownKyi.Core/Settings/SettingsManager.UserInfo.cs index 50649c1..32efcc5 100644 --- a/DownKyi.Core/Settings/SettingsManager.UserInfo.cs +++ b/DownKyi.Core/Settings/SettingsManager.UserInfo.cs @@ -5,7 +5,7 @@ namespace DownKyi.Core.Settings; public partial class SettingsManager { // 登录用户的mid - private readonly UserInfoSettings userInfo = new UserInfoSettings + private readonly UserInfoSettings _userInfo = new() { Mid = -1, Name = "", @@ -19,25 +19,25 @@ public partial class SettingsManager /// public UserInfoSettings GetUserInfo() { - appSettings = GetSettings(); - if (appSettings.UserInfo == null) + _appSettings = GetSettings(); + if (_appSettings.UserInfo == null) { // 第一次获取,先设置默认值 - SetUserInfo(userInfo); - return userInfo; + SetUserInfo(_userInfo); + return _userInfo; } - return appSettings.UserInfo; + return _appSettings.UserInfo; } /// /// 设置中保存登录用户的信息,在index刷新用户状态时使用 /// - /// + /// /// public bool SetUserInfo(UserInfoSettings userInfo) { - appSettings.UserInfo = userInfo; + _appSettings.UserInfo = userInfo; return SetSettings(); } } \ No newline at end of file diff --git a/DownKyi.Core/Settings/SettingsManager.Video.cs b/DownKyi.Core/Settings/SettingsManager.Video.cs index ff425bf..d763e2a 100644 --- a/DownKyi.Core/Settings/SettingsManager.Video.cs +++ b/DownKyi.Core/Settings/SettingsManager.Video.cs @@ -7,56 +7,56 @@ namespace DownKyi.Core.Settings; public partial class SettingsManager { // 设置优先下载的视频编码 - private readonly int videoCodecs = 7; + private const int VideoCodecs = 7; // 设置优先下载画质 - private readonly int quality = 120; + private const int Quality = 120; // 设置优先下载音质 - private readonly int audioQuality = 30280; - + private const int AudioQuality = 30280; + // 设置首选视频解析方式 private const int VideoParseType = 1; // 是否下载flv视频后转码为mp4 - private readonly AllowStatus isTranscodingFlvToMp4 = AllowStatus.YES; - + private const AllowStatus IsTranscodingFlvToMp4 = AllowStatus.Yes; + // 是否下载aac音频后转码为mp3 - private readonly AllowStatus isTranscodingAacToMp3 = AllowStatus.YES; + private const AllowStatus IsTranscodingAacToMp3 = AllowStatus.Yes; // 默认下载目录 - private readonly string saveVideoRootPath = StorageManager.GetMedia(); + private readonly string _saveVideoRootPath = StorageManager.GetMedia(); // 历史下载目录 - private readonly List historyVideoRootPaths = new(); + private readonly List _historyVideoRootPaths = new(); // 是否使用默认下载目录,如果是,则每次点击下载选中项时不再询问下载目录 - private readonly AllowStatus isUseSaveVideoRootPath = AllowStatus.NO; + private const AllowStatus IsUseSaveVideoRootPath = AllowStatus.No; // 下载内容 - private readonly VideoContentSettings videoContent = new(); + private readonly VideoContentSettings _videoContent = new(); // 文件命名格式 - private readonly List fileNameParts = new() + private readonly List _fileNameParts = new() { - FileNamePart.MAIN_TITLE, - FileNamePart.SLASH, - FileNamePart.SECTION, - FileNamePart.SLASH, - FileNamePart.ORDER, - FileNamePart.HYPHEN, - FileNamePart.PAGE_TITLE, - FileNamePart.HYPHEN, - FileNamePart.VIDEO_QUALITY, - FileNamePart.HYPHEN, - FileNamePart.VIDEO_CODEC, + FileNamePart.MainTitle, + FileNamePart.Slash, + FileNamePart.Section, + FileNamePart.Slash, + FileNamePart.Order, + FileNamePart.Hyphen, + FileNamePart.PageTitle, + FileNamePart.Hyphen, + FileNamePart.VideoQuality, + FileNamePart.Hyphen, + FileNamePart.VideoCodec, }; // 文件命名中的时间格式 - private readonly string fileNamePartTimeFormat = "yyyy-MM-dd"; + private const string FileNamePartTimeFormat = "yyyy-MM-dd"; // 文件命名中的序号格式 - private readonly OrderFormat orderFormat = OrderFormat.NATURAL; + private const OrderFormat OrderFormat = Settings.OrderFormat.Natural; /// /// 获取优先下载的视频编码 @@ -64,15 +64,15 @@ public partial class SettingsManager /// public int GetVideoCodecs() { - appSettings = GetSettings(); - if (appSettings.Video.VideoCodecs == -1) + _appSettings = GetSettings(); + if (_appSettings.Video.VideoCodecs == -1) { // 第一次获取,先设置默认值 - SetVideoCodecs(videoCodecs); - return videoCodecs; + SetVideoCodecs(VideoCodecs); + return VideoCodecs; } - return appSettings.Video.VideoCodecs; + return _appSettings.Video.VideoCodecs; } /// @@ -82,7 +82,7 @@ public partial class SettingsManager /// public bool SetVideoCodecs(int videoCodecs) { - appSettings.Video.VideoCodecs = videoCodecs; + _appSettings.Video.VideoCodecs = videoCodecs; return SetSettings(); } @@ -92,15 +92,15 @@ public partial class SettingsManager /// public int GetQuality() { - appSettings = GetSettings(); - if (appSettings.Video.Quality == -1) + _appSettings = GetSettings(); + if (_appSettings.Video.Quality == -1) { // 第一次获取,先设置默认值 - SetQuality(quality); - return quality; + SetQuality(Quality); + return Quality; } - return appSettings.Video.Quality; + return _appSettings.Video.Quality; } /// @@ -110,7 +110,7 @@ public partial class SettingsManager /// public bool SetQuality(int quality) { - appSettings.Video.Quality = quality; + _appSettings.Video.Quality = quality; return SetSettings(); } @@ -120,15 +120,15 @@ public partial class SettingsManager /// public int GetAudioQuality() { - appSettings = GetSettings(); - if (appSettings.Video.AudioQuality == -1) + _appSettings = GetSettings(); + if (_appSettings.Video.AudioQuality == -1) { // 第一次获取,先设置默认值 - SetAudioQuality(audioQuality); - return audioQuality; + SetAudioQuality(AudioQuality); + return AudioQuality; } - return appSettings.Video.AudioQuality; + return _appSettings.Video.AudioQuality; } /// @@ -138,7 +138,7 @@ public partial class SettingsManager /// public bool SetAudioQuality(int quality) { - appSettings.Video.AudioQuality = quality; + _appSettings.Video.AudioQuality = quality; return SetSettings(); } @@ -148,15 +148,15 @@ public partial class SettingsManager /// public int GetVideoParseType() { - appSettings = GetSettings(); - if (appSettings.Video.VideoParseType == null) + _appSettings = GetSettings(); + if (_appSettings.Video.VideoParseType == null) { // 第一次获取,先设置默认值 SetVideoParseType(VideoParseType); return VideoParseType; } - return appSettings.Video.VideoParseType; + return _appSettings.Video.VideoParseType; } /// @@ -166,7 +166,7 @@ public partial class SettingsManager /// public bool SetVideoParseType(int videoParseType) { - appSettings.Video.VideoParseType = videoParseType; + _appSettings.Video.VideoParseType = videoParseType; return SetSettings(); } @@ -174,17 +174,17 @@ public partial class SettingsManager /// 获取是否下载flv视频后转码为mp4 /// /// - public AllowStatus IsTranscodingFlvToMp4() + public AllowStatus GetIsTranscodingFlvToMp4() { - appSettings = GetSettings(); - if (appSettings.Video.IsTranscodingFlvToMp4 == AllowStatus.NONE) + _appSettings = GetSettings(); + if (_appSettings.Video.IsTranscodingFlvToMp4 == AllowStatus.None) { // 第一次获取,先设置默认值 - IsTranscodingFlvToMp4(isTranscodingFlvToMp4); - return isTranscodingFlvToMp4; + SetIsTranscodingFlvToMp4(IsTranscodingFlvToMp4); + return IsTranscodingFlvToMp4; } - return appSettings.Video.IsTranscodingFlvToMp4; + return _appSettings.Video.IsTranscodingFlvToMp4; } /// @@ -192,9 +192,9 @@ public partial class SettingsManager /// /// /// - public bool IsTranscodingFlvToMp4(AllowStatus isTranscodingFlvToMp4) + public bool SetIsTranscodingFlvToMp4(AllowStatus isTranscodingFlvToMp4) { - appSettings.Video.IsTranscodingFlvToMp4 = isTranscodingFlvToMp4; + _appSettings.Video.IsTranscodingFlvToMp4 = isTranscodingFlvToMp4; return SetSettings(); } @@ -202,17 +202,17 @@ public partial class SettingsManager /// 获取是否下载aac音频后转码为mp3 /// /// - public AllowStatus IsTranscodingAacToMp3() + public AllowStatus GetIsTranscodingAacToMp3() { - appSettings = GetSettings(); - if (appSettings.Video.IsTranscodingAacToMp3 == AllowStatus.NONE) + _appSettings = GetSettings(); + if (_appSettings.Video.IsTranscodingAacToMp3 == AllowStatus.None) { // 第一次获取,先设置默认值 - IsTranscodingAacToMp3(isTranscodingAacToMp3); - return isTranscodingAacToMp3; + SetIsTranscodingAacToMp3(IsTranscodingAacToMp3); + return IsTranscodingAacToMp3; } - return appSettings.Video.IsTranscodingAacToMp3; + return _appSettings.Video.IsTranscodingAacToMp3; } /// @@ -220,9 +220,9 @@ public partial class SettingsManager /// /// /// - public bool IsTranscodingAacToMp3(AllowStatus isTranscodingAacToMp3) + public bool SetIsTranscodingAacToMp3(AllowStatus isTranscodingAacToMp3) { - appSettings.Video.IsTranscodingAacToMp3 = isTranscodingAacToMp3; + _appSettings.Video.IsTranscodingAacToMp3 = isTranscodingAacToMp3; return SetSettings(); } @@ -232,15 +232,15 @@ public partial class SettingsManager /// public string GetSaveVideoRootPath() { - appSettings = GetSettings(); - if (appSettings.Video.SaveVideoRootPath == null) + _appSettings = GetSettings(); + if (_appSettings.Video.SaveVideoRootPath == null) { // 第一次获取,先设置默认值 - SetSaveVideoRootPath(saveVideoRootPath); - return saveVideoRootPath; + SetSaveVideoRootPath(_saveVideoRootPath); + return _saveVideoRootPath; } - return appSettings.Video.SaveVideoRootPath; + return _appSettings.Video.SaveVideoRootPath; } /// @@ -250,7 +250,7 @@ public partial class SettingsManager /// public bool SetSaveVideoRootPath(string path) { - appSettings.Video.SaveVideoRootPath = path; + _appSettings.Video.SaveVideoRootPath = path; return SetSettings(); } @@ -260,15 +260,15 @@ public partial class SettingsManager /// public List GetHistoryVideoRootPaths() { - appSettings = GetSettings(); - if (appSettings.Video.HistoryVideoRootPaths == null) + _appSettings = GetSettings(); + if (_appSettings.Video.HistoryVideoRootPaths == null) { // 第一次获取,先设置默认值 - SetHistoryVideoRootPaths(historyVideoRootPaths); - return historyVideoRootPaths; + SetHistoryVideoRootPaths(_historyVideoRootPaths); + return _historyVideoRootPaths; } - return appSettings.Video.HistoryVideoRootPaths; + return _appSettings.Video.HistoryVideoRootPaths; } /// @@ -278,7 +278,7 @@ public partial class SettingsManager /// public bool SetHistoryVideoRootPaths(List historyPaths) { - appSettings.Video.HistoryVideoRootPaths = historyPaths; + _appSettings.Video.HistoryVideoRootPaths = historyPaths; return SetSettings(); } @@ -286,17 +286,17 @@ public partial class SettingsManager /// 获取是否使用默认下载目录 /// /// - public AllowStatus IsUseSaveVideoRootPath() + public AllowStatus GetIsUseSaveVideoRootPath() { - appSettings = GetSettings(); - if (appSettings.Video.IsUseSaveVideoRootPath == AllowStatus.NONE) + _appSettings = GetSettings(); + if (_appSettings.Video.IsUseSaveVideoRootPath == AllowStatus.None) { // 第一次获取,先设置默认值 - IsUseSaveVideoRootPath(isUseSaveVideoRootPath); - return isUseSaveVideoRootPath; + SetIsUseSaveVideoRootPath(IsUseSaveVideoRootPath); + return IsUseSaveVideoRootPath; } - return appSettings.Video.IsUseSaveVideoRootPath; + return _appSettings.Video.IsUseSaveVideoRootPath; } /// @@ -304,9 +304,9 @@ public partial class SettingsManager /// /// /// - public bool IsUseSaveVideoRootPath(AllowStatus isUseSaveVideoRootPath) + public bool SetIsUseSaveVideoRootPath(AllowStatus isUseSaveVideoRootPath) { - appSettings.Video.IsUseSaveVideoRootPath = isUseSaveVideoRootPath; + _appSettings.Video.IsUseSaveVideoRootPath = isUseSaveVideoRootPath; return SetSettings(); } @@ -316,15 +316,15 @@ public partial class SettingsManager /// public VideoContentSettings GetVideoContent() { - appSettings = GetSettings(); - if (appSettings.Video.VideoContent == null) + _appSettings = GetSettings(); + if (_appSettings.Video.VideoContent == null) { // 第一次获取,先设置默认值 - SetVideoContent(videoContent); - return videoContent; + SetVideoContent(_videoContent); + return _videoContent; } - return appSettings.Video.VideoContent; + return _appSettings.Video.VideoContent; } /// @@ -334,7 +334,7 @@ public partial class SettingsManager /// public bool SetVideoContent(VideoContentSettings videoContent) { - appSettings.Video.VideoContent = videoContent; + _appSettings.Video.VideoContent = videoContent; return SetSettings(); } @@ -344,25 +344,25 @@ public partial class SettingsManager /// public List GetFileNameParts() { - appSettings = GetSettings(); - if (appSettings.Video.FileNameParts == null || appSettings.Video.FileNameParts.Count == 0) + _appSettings = GetSettings(); + if (_appSettings.Video.FileNameParts == null || _appSettings.Video.FileNameParts.Count == 0) { // 第一次获取,先设置默认值 - SetFileNameParts(fileNameParts); - return fileNameParts; + SetFileNameParts(_fileNameParts); + return _fileNameParts; } - return appSettings.Video.FileNameParts; + return _appSettings.Video.FileNameParts; } /// /// 设置文件命名格式 /// - /// + /// /// public bool SetFileNameParts(List fileNameParts) { - appSettings.Video.FileNameParts = fileNameParts; + _appSettings.Video.FileNameParts = fileNameParts; return SetSettings(); } @@ -372,16 +372,16 @@ public partial class SettingsManager /// public string GetFileNamePartTimeFormat() { - appSettings = GetSettings(); - if (appSettings.Video.FileNamePartTimeFormat == null || - appSettings.Video.FileNamePartTimeFormat == string.Empty) + _appSettings = GetSettings(); + if (_appSettings.Video.FileNamePartTimeFormat == null || + _appSettings.Video.FileNamePartTimeFormat == string.Empty) { // 第一次获取,先设置默认值 - SetFileNamePartTimeFormat(fileNamePartTimeFormat); - return fileNamePartTimeFormat; + SetFileNamePartTimeFormat(FileNamePartTimeFormat); + return FileNamePartTimeFormat; } - return appSettings.Video.FileNamePartTimeFormat; + return _appSettings.Video.FileNamePartTimeFormat; } /// @@ -391,7 +391,7 @@ public partial class SettingsManager /// public bool SetFileNamePartTimeFormat(string fileNamePartTimeFormat) { - appSettings.Video.FileNamePartTimeFormat = fileNamePartTimeFormat; + _appSettings.Video.FileNamePartTimeFormat = fileNamePartTimeFormat; return SetSettings(); } @@ -401,15 +401,15 @@ public partial class SettingsManager /// public OrderFormat GetOrderFormat() { - appSettings = GetSettings(); - if (appSettings.Video.OrderFormat == OrderFormat.NOT_SET) + _appSettings = GetSettings(); + if (_appSettings.Video.OrderFormat == OrderFormat.NotSet) { // 第一次获取,先设置默认值 - SetOrderFormat(orderFormat); - return orderFormat; + SetOrderFormat(OrderFormat); + return OrderFormat; } - return appSettings.Video.OrderFormat; + return _appSettings.Video.OrderFormat; } /// @@ -419,7 +419,7 @@ public partial class SettingsManager /// public bool SetOrderFormat(OrderFormat orderFormat) { - appSettings.Video.OrderFormat = orderFormat; + _appSettings.Video.OrderFormat = orderFormat; return SetSettings(); } } \ No newline at end of file diff --git a/DownKyi.Core/Settings/SettingsManager.cs b/DownKyi.Core/Settings/SettingsManager.cs index e2183e8..1c56bda 100644 --- a/DownKyi.Core/Settings/SettingsManager.cs +++ b/DownKyi.Core/Settings/SettingsManager.cs @@ -14,17 +14,17 @@ namespace DownKyi.Core.Settings; public partial class SettingsManager { - private static SettingsManager instance; + private static SettingsManager? _instance; // 内存中保存一份配置 - private AppSettings appSettings; + private AppSettings _appSettings; #if DEBUG // 设置的配置文件 - private readonly string settingsName = StorageManager.GetSettings() + "_debug.json"; + private readonly string _settingsName = StorageManager.GetSettings() + "_debug.json"; #else // 设置的配置文件 - private readonly string settingsName = Storage.StorageManager.GetSettings(); + private readonly string _settingsName = Storage.StorageManager.GetSettings(); // 密钥 private readonly string password = "YO1J$4#p"; @@ -36,12 +36,7 @@ public partial class SettingsManager /// public static SettingsManager GetInstance() { - if (instance == null) - { - instance = new SettingsManager(); - } - - return instance; + return _instance ??= new SettingsManager(); } /// @@ -49,7 +44,7 @@ public partial class SettingsManager /// private SettingsManager() { - appSettings = GetSettings(); + _appSettings = GetSettings(); } /// @@ -58,9 +53,9 @@ public partial class SettingsManager /// private AppSettings GetSettings() { - if (appSettings != null) + if (_appSettings != null) { - return appSettings; + return _appSettings; } try @@ -70,9 +65,8 @@ public partial class SettingsManager //string jsonWordTemplate = streamReader.ReadToEnd(); //streamReader.Close(); //fileStream.Close(); - string jsonWordTemplate = string.Empty; - using (var stream = new FileStream(settingsName, FileMode.Open, FileAccess.Read, - FileShare.ReadWrite | FileShare.Delete)) + var jsonWordTemplate = string.Empty; + using (var stream = new FileStream(_settingsName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete)) { using (var reader = new StreamReader(stream, Encoding.UTF8)) { @@ -104,7 +98,7 @@ public partial class SettingsManager { try { - string json = JsonConvert.SerializeObject(appSettings); + var json = JsonConvert.SerializeObject(_appSettings); #if DEBUG #else @@ -112,7 +106,7 @@ public partial class SettingsManager json = Encryptor.EncryptString(json, password); #endif - File.WriteAllText(settingsName, json); + File.WriteAllText(_settingsName, json); return true; } catch (Exception e) diff --git a/DownKyi.Core/Settings/VideoCodecs.cs b/DownKyi.Core/Settings/VideoCodecs.cs index 10da355..5e0b1fc 100644 --- a/DownKyi.Core/Settings/VideoCodecs.cs +++ b/DownKyi.Core/Settings/VideoCodecs.cs @@ -2,7 +2,7 @@ public enum VideoCodecs { - NONE = 0, - AVC, - HEVC + None = 0, + Avc, + Hevc } \ No newline at end of file diff --git a/DownKyi.Core/Storage/Constant.cs b/DownKyi.Core/Storage/Constant.cs index a7d0cbf..5365552 100644 --- a/DownKyi.Core/Storage/Constant.cs +++ b/DownKyi.Core/Storage/Constant.cs @@ -43,7 +43,6 @@ internal static class Constant // 历史(搜索、下载) (加密) public static string Download { get; } = $"{Database}/Download.db"; - public static string History { get; } = $"{Database}/History.db"; // 配置 public static string Config { get; } = $"{Root}/Config"; @@ -60,33 +59,9 @@ internal static class Constant // 弹幕 public static string Danmaku { get; } = $"{Bilibili}/Danmakus"; - // 字幕 - public static string Subtitle { get; } = $"{Bilibili}/Subtitle"; - - // 评论 - // TODO - - // 头图 - public static string Toutu { get; } = $"{Bilibili}/Toutu"; - - // 封面 - public static string Cover { get; } = $"{Bilibili}/Cover"; - - // 封面文件索引 - public static string CoverIndex { get; } = $"{Cover}/Index.db"; - - // 视频快照 - public static string Snapshot { get; } = $"{Bilibili}/Snapshot"; - - // 视频快照文件索引 - public static string SnapshotIndex { get; } = $"{Cover}/Index.db"; - - // 用户头像 - public static string Header { get; } = $"{Bilibili}/Header"; - - // 用户头像文件索引 - public static string HeaderIndex { get; } = $"{Header}/Index.db"; - // 下载 public static string Media { get; } = $"{Root}/Media"; + + // 缓存 + public static string Cache { get; } = $"{Root}/Cache"; } \ No newline at end of file diff --git a/DownKyi.Core/Storage/Database/Cover.cs b/DownKyi.Core/Storage/Database/Cover.cs deleted file mode 100644 index 037c246..0000000 --- a/DownKyi.Core/Storage/Database/Cover.cs +++ /dev/null @@ -1,10 +0,0 @@ -namespace DownKyi.Core.Storage.Database; - -public class Cover -{ - public long Avid { get; set; } - public string Bvid { get; set; } - public long Cid { get; set; } - public string Url { get; set; } - public string Md5 { get; set; } -} \ No newline at end of file diff --git a/DownKyi.Core/Storage/Database/CoverDb.cs b/DownKyi.Core/Storage/Database/CoverDb.cs deleted file mode 100644 index 50de6ea..0000000 --- a/DownKyi.Core/Storage/Database/CoverDb.cs +++ /dev/null @@ -1,147 +0,0 @@ -using DownKyi.Core.Logging; -using Console = DownKyi.Core.Utils.Debugging.Console; - -namespace DownKyi.Core.Storage.Database; - -public class CoverDb -{ - private const string key = "b5018ecc-09d1-4da2-aa49-4625e41e623e"; - private readonly string tableName = "cover"; - -#if DEBUG - private readonly DbHelper dbHelper = new DbHelper(StorageManager.GetCoverIndex().Replace(".db", "_debug.db")); -#else - private readonly DbHelper dbHelper = new DbHelper(StorageManager.GetCoverIndex(), key); -#endif - - public CoverDb() - { - CreateTable(); - } - - /// - /// 关闭数据库连接 - /// - public void Close() - { - dbHelper.Close(); - } - - /// - /// 插入新的数据 - /// - /// - public void Insert(Cover cover) - { - try - { - string sql = - $"insert into {tableName} values ({cover.Avid}, '{cover.Bvid}', {cover.Cid}, '{cover.Url}', '{cover.Md5}')"; - dbHelper.ExecuteNonQuery(sql); - } - catch (Exception e) - { - Console.PrintLine("Insert()发生异常: {0}", e); - LogManager.Error("CoverDb", e); - } - } - - /// - /// 更新数据,以url检索 - /// - /// - public void Update(Cover cover) - { - try - { - string sql = - $"update {tableName} set avid={cover.Avid}, bvid='{cover.Bvid}', cid={cover.Cid}, md5='{cover.Md5}' where url glob '{cover.Url}'"; - dbHelper.ExecuteNonQuery(sql); - } - catch (Exception e) - { - Console.PrintLine("Update()发生异常: {0}", e); - LogManager.Error("CoverDb", e); - } - } - - /// - /// 查询所有数据 - /// - /// - public List QueryAll() - { - string sql = $"select * from {tableName}"; - return Query(sql); - } - - /// - /// 查询url对应的数据 - /// - /// - /// - public Cover QueryByUrl(string url) - { - string sql = $"select * from {tableName} where url glob '{url}'"; - List query = Query(sql); - return query.Count > 0 ? query[0] : null; - } - - /// - /// 查询md5对应的数据 - /// - /// - /// - public Cover QueryByMd5(string md5) - { - string sql = $"select * from {tableName} where md5 glob '{md5}'"; - List query = Query(sql); - return query.Count > 0 ? query[0] : null; - } - - /// - /// 查询数据 - /// - /// - /// - private List Query(string sql) - { - List covers = new List(); - - try - { - dbHelper.ExecuteQuery(sql, reader => - { - while (reader.Read()) - { - Cover cover = new Cover - { - Avid = (long)reader["avid"], - Bvid = (string)reader["bvid"], - Cid = (long)reader["cid"], - Url = (string)reader["url"], - Md5 = (string)reader["md5"] - }; - covers.Add(cover); - } - }); - } - catch (Exception e) - { - Console.PrintLine("Query()发生异常: {0}", e); - LogManager.Error($"{tableName}", e); - } - - return covers; - } - - /// - /// 如果表不存在则创建表 - /// - private void CreateTable() - { - string sql = - $"create table if not exists {tableName} (avid unsigned big int, bvid varchar(20), cid unsigned big int, url varchar(255) unique, md5 varchar(32) unique)"; - dbHelper.ExecuteNonQuery(sql); - } -} \ No newline at end of file diff --git a/DownKyi.Core/Storage/Database/DbHelper.cs b/DownKyi.Core/Storage/Database/DbHelper.cs index ceefac1..4f2855c 100644 --- a/DownKyi.Core/Storage/Database/DbHelper.cs +++ b/DownKyi.Core/Storage/Database/DbHelper.cs @@ -7,10 +7,10 @@ namespace DownKyi.Core.Storage.Database; public class DbHelper { - private readonly string connStr; - private readonly SqliteConnection conn; + private readonly string _connStr; + private readonly SqliteConnection? _conn; - private static readonly Dictionary database = new(); + private static readonly Dictionary Database = new(); /// /// 创建一个数据库 @@ -18,23 +18,23 @@ public class DbHelper /// public DbHelper(string dbPath) { - connStr = new SqliteConnectionStringBuilder + _connStr = new SqliteConnectionStringBuilder { Mode = SqliteOpenMode.ReadWriteCreate, DataSource = dbPath }.ToString(); - if (database.ContainsKey(connStr)) + if (Database.TryGetValue(_connStr, out var value)) { - conn = database[connStr]; + _conn = value; - if (conn != null) + if (_conn != null) { return; } } - conn = new SqliteConnection(connStr); - database.Add(connStr, conn); + _conn = new SqliteConnection(_connStr); + Database.Add(_connStr, _conn); } /// @@ -44,25 +44,25 @@ public class DbHelper /// public DbHelper(string dbPath, string secretKey) { - connStr = new SqliteConnectionStringBuilder + _connStr = new SqliteConnectionStringBuilder { Mode = SqliteOpenMode.ReadWriteCreate, Password = secretKey, DataSource = dbPath }.ToString(); - if (database.ContainsKey(connStr)) + if (Database.TryGetValue(_connStr, out var value)) { - conn = database[connStr]; + _conn = value; - if (conn != null) + if (_conn != null) { return; } } - conn = new SqliteConnection(connStr); + _conn = new SqliteConnection(_connStr); // conn.SetPassword(secretKey); - database.Add(connStr, conn); + Database.Add(_connStr, _conn); } /// @@ -71,7 +71,7 @@ public class DbHelper /// public bool IsOpen() { - return conn.State == ConnectionState.Open; + return _conn?.State == ConnectionState.Open; } /// @@ -79,14 +79,14 @@ public class DbHelper /// public void Open() { - if (conn == null) + if (_conn == null) { return; } if (!IsOpen()) { - conn.Open(); + _conn.Open(); } } @@ -95,47 +95,44 @@ public class DbHelper /// public void Close() { - if (conn == null) + if (_conn == null) { return; } - if (IsOpen()) - { - conn.Close(); + if (!IsOpen()) return; + _conn.Close(); - database.Remove(connStr); - } + Database.Remove(_connStr); } /// /// 执行一条SQL语句 /// /// - public void ExecuteNonQuery(string sql, Action action = null) + /// + public void ExecuteNonQuery(string sql, Action? action = null) { - if (conn == null) + if (_conn == null) { return; } try { - lock (conn) + lock (_conn) { Open(); - using (var tr = conn.BeginTransaction()) + using var tr = _conn.BeginTransaction(); + using (var command = _conn.CreateCommand()) { - using (var command = conn.CreateCommand()) - { - command.CommandText = sql; - // 添加参数 - action?.Invoke(command.Parameters); - command.ExecuteNonQuery(); - } - - tr.Commit(); + command.CommandText = sql; + // 添加参数 + action?.Invoke(command.Parameters); + command.ExecuteNonQuery(); } + + tr.Commit(); } } catch (SqliteException e) @@ -152,22 +149,20 @@ public class DbHelper /// public void ExecuteQuery(string sql, Action action) { - if (conn == null) + if (_conn == null) { return; } try { - lock (conn) + lock (_conn) { Open(); - using (var command = conn.CreateCommand()) - { - command.CommandText = sql; - var reader = command.ExecuteReader(); - action(reader); - } + using var command = _conn.CreateCommand(); + command.CommandText = sql; + var reader = command.ExecuteReader(); + action(reader); } } catch (SqliteException e) diff --git a/DownKyi.Core/Storage/Database/Download/DownloadDb.cs b/DownKyi.Core/Storage/Database/Download/DownloadDb.cs index 8c5eeac..5874016 100644 --- a/DownKyi.Core/Storage/Database/Download/DownloadDb.cs +++ b/DownKyi.Core/Storage/Database/Download/DownloadDb.cs @@ -132,14 +132,14 @@ public class DownloadDb /// /// /// - public object QueryById(string uuid) + public object? QueryById(string uuid) { - string sql = $"select * from {tableName} where id glob '{uuid}'"; - Dictionary query = Query(sql); + var sql = $"select * from {tableName} where id glob '{uuid}'"; + var query = Query(sql); if (query.ContainsKey(uuid)) { - query.TryGetValue(uuid, out object obj); + query.TryGetValue(uuid, out var obj); return obj; } else @@ -155,7 +155,7 @@ public class DownloadDb /// private Dictionary Query(string sql) { - Dictionary objects = new Dictionary(); + var objects = new Dictionary(); dbHelper.ExecuteQuery(sql, reader => { @@ -164,13 +164,13 @@ public class DownloadDb try { // 读取字节数组 - byte[] array = (byte[])reader["data"]; + var array = (byte[])reader["data"]; // 定义一个流 - MemoryStream stream = new MemoryStream(array); + var stream = new MemoryStream(array); //定义一个格式化器 - BinaryFormatter formatter = new BinaryFormatter(); + var formatter = new BinaryFormatter(); // 反序列化 - object obj = formatter.Deserialize(stream); + var obj = formatter.Deserialize(stream); objects.Add((string)reader["id"], obj); } @@ -190,7 +190,7 @@ public class DownloadDb /// protected void CreateTable() { - string sql = $"create table if not exists {tableName} (id varchar(255) unique, data blob)"; + var sql = $"create table if not exists {tableName} (id varchar(255) unique, data blob)"; dbHelper.ExecuteNonQuery(sql); } } \ No newline at end of file diff --git a/DownKyi.Core/Storage/Database/Header.cs b/DownKyi.Core/Storage/Database/Header.cs deleted file mode 100644 index cda3e11..0000000 --- a/DownKyi.Core/Storage/Database/Header.cs +++ /dev/null @@ -1,9 +0,0 @@ -namespace DownKyi.Core.Storage.Database; - -public class Header -{ - public long Mid { get; set; } - public string Name { get; set; } - public string Url { get; set; } - public string Md5 { get; set; } -} \ No newline at end of file diff --git a/DownKyi.Core/Storage/Database/HeaderDb.cs b/DownKyi.Core/Storage/Database/HeaderDb.cs deleted file mode 100644 index 9229b0f..0000000 --- a/DownKyi.Core/Storage/Database/HeaderDb.cs +++ /dev/null @@ -1,134 +0,0 @@ -using DownKyi.Core.Logging; -using Console = DownKyi.Core.Utils.Debugging.Console; - -namespace DownKyi.Core.Storage.Database; - -public class HeaderDb -{ - private const string key = "7c1f1f40-7cdf-4d11-ad28-f0137a3c5308"; - private readonly string tableName = "header"; - -#if DEBUG - private readonly DbHelper dbHelper = new DbHelper(StorageManager.GetHeaderIndex().Replace(".db", "_debug.db")); -#else - private readonly DbHelper dbHelper = new DbHelper(StorageManager.GetHeaderIndex(), key); -#endif - - public HeaderDb() - { - CreateTable(); - } - - /// - /// 关闭数据库连接 - /// - public void Close() - { - dbHelper.Close(); - } - - /// - /// 插入新的数据 - /// - /// - public void Insert(Header header) - { - try - { - string sql = - $"insert into {tableName} values ({header.Mid}, '{header.Name}', '{header.Url}', '{header.Md5}')"; - dbHelper.ExecuteNonQuery(sql); - } - catch (Exception e) - { - Console.PrintLine("Insert()发生异常: {0}", e); - LogManager.Error("HeaderDb", e); - } - } - - /// - /// 更新数据 - /// - /// - public void Update(Header header) - { - try - { - string sql = - $"update {tableName} set name='{header.Name}', url='{header.Url}', md5='{header.Md5}' where mid={header.Mid}"; - dbHelper.ExecuteNonQuery(sql); - } - catch (Exception e) - { - Console.PrintLine("Update()发生异常: {0}", e); - LogManager.Error("HeaderDb", e); - } - } - - /// - /// 查询所有数据 - /// - /// - public List
QueryAll() - { - string sql = $"select * from {tableName}"; - return Query(sql); - } - - /// - /// 查询mid对应的数据 - /// - /// - /// - public Header QueryByMid(long mid) - { - string sql = $"select * from {tableName} where mid={mid}"; - List
query = Query(sql); - return query.Count > 0 ? query[0] : null; - } - - /// - /// 查询数据 - /// - /// - /// - private List
Query(string sql) - { - List
headers = new List
(); - - try - { - dbHelper.ExecuteQuery(sql, reader => - { - while (reader.Read()) - { - Header header = new Header - { - Mid = (long)reader["mid"], - Name = (string)reader["name"], - Url = (string)reader["url"], - Md5 = (string)reader["md5"] - }; - headers.Add(header); - } - }); - } - catch (Exception e) - { - Console.PrintLine("Query()发生异常: {0}", e); - LogManager.Error($"{tableName}", e); - } - - return headers; - } - - /// - /// 如果表不存在则创建表 - /// - private void CreateTable() - { - string sql = - $"create table if not exists {tableName} (mid unsigned big int unique, name varchar(255), url varchar(255), md5 varchar(32))"; - dbHelper.ExecuteNonQuery(sql); - } -} \ No newline at end of file diff --git a/DownKyi.Core/Storage/StorageCover.cs b/DownKyi.Core/Storage/StorageCover.cs deleted file mode 100644 index b1faf85..0000000 --- a/DownKyi.Core/Storage/StorageCover.cs +++ /dev/null @@ -1,281 +0,0 @@ -using Avalonia; -using Avalonia.Media.Imaging; -using DownKyi.Core.Logging; -using DownKyi.Core.Storage.Database; -using DownKyi.Core.Utils.Encryptor; -using Console = DownKyi.Core.Utils.Debugging.Console; - -namespace DownKyi.Core.Storage; - -public class StorageCover -{ - // 先判断本地有没有 - // 如果有 - // 则返回本地的图片路径 - // 如果没有 - // 则下载图片并返回本地的图片路径 - - /// - /// 获取封面缩略图 - /// - /// - /// - /// - /// - /// - /// - /// - public Bitmap GetCoverThumbnail(long avid, string bvid, long cid, string url, int width, int height) - { - var header = GetCover(avid, bvid, cid, url); - - return GetCoverThumbnail(header, width, height); - } - - /// - /// 获取封面缩略图 - /// - /// - /// - /// - /// - public Bitmap GetCoverThumbnail(string cover, int width, int height) - { - if (cover == null) - { - return null; - } - - try - { - var bitmap = new Bitmap(cover); - return bitmap.CreateScaledBitmap(new PixelSize(width, height), BitmapInterpolationMode.Unspecified); - - // return StorageUtils.BitmapToBitmapImage(new Bitmap(thumbnail)); - } - catch (ArgumentException) - { - try - { - // SimpleDecoder simpleDecoder = new SimpleDecoder(cover); - // Bitmap bitmap = simpleDecoder.WebPtoBitmap(); - // Image thumbnail = bitmap.GetThumbnailImage(width, height, null, IntPtr.Zero); - // - // return StorageUtils.BitmapToBitmapImage(new Bitmap(thumbnail)); - return null; - } - catch (Exception ex) - { - Console.PrintLine("GetCoverThumbnail()发生异常: {0}", ex); - LogManager.Error("StorageCover.GetCoverThumbnail()", ex); - - return null; - } - } - catch (Exception e) - { - Console.PrintLine("GetCoverThumbnail()发生异常: {0}", e); - LogManager.Error("StorageCover.GetCoverThumbnail()", e); - - return null; - } - } - - /// - /// 获取封面 - /// - /// - /// - public string GetCover(string url) - { - return GetCover(0, "", 0, url); - } - - /// - /// 获取封面 - /// - /// - /// - /// - /// - /// - public string GetCover(long avid, string bvid, long cid, string url) - { - var coverDb = new CoverDb(); - var cover = coverDb.QueryByUrl(url); - - // 如果存在,直接返回 - // 如果不存在,则先下载 - if (cover != null) - { - var coverPath = $"{StorageManager.GetCover()}/{cover.Md5}"; - if (File.Exists(coverPath)) - { - var newCover = new Cover - { - Avid = avid, - Bvid = bvid, - Cid = cid, - Url = url, - Md5 = cover.Md5 - }; - coverDb.Update(newCover); - - //coverDb.Close(); - return $"{StorageManager.GetCover()}/{cover.Md5}"; - } - else - { - var md5 = DownloadImage(url); - if (md5 != null) - { - Cover newCover = new Cover - { - Avid = avid, - Bvid = bvid, - Cid = cid, - Url = url, - Md5 = md5 - }; - coverDb.Update(newCover); - - //coverDb.Close(); - return $"{StorageManager.GetCover()}/{md5}"; - } - else - { - //coverDb.Close(); - return null; - } - } - } - else - { - var md5 = DownloadImage(url); - if (md5 != null) - { - Cover newCover = new Cover - { - Avid = avid, - Bvid = bvid, - Cid = cid, - Url = url, - Md5 = md5 - }; - coverDb.Insert(newCover); - - //coverDb.Close(); - return $"{StorageManager.GetCover()}/{md5}"; - } - else - { - //coverDb.Close(); - return null; - } - } - } - - public async Task GetCoverAsync(string url,TimeSpan? timeOut = null) - { - timeOut = timeOut ?? TimeSpan.FromSeconds(1.5); - using var stream = await GetImageBytesAsync(url, timeOut); - return stream == null ? null : new Bitmap(stream); - } - - - public async Task GetImageBytesAsync(string imageUrl,TimeSpan? timeOut = null) - { - try - { - using (var httpClient = new HttpClient()) - { - if (timeOut is not null) - { - httpClient.Timeout = timeOut.Value; - } - var response = await httpClient.GetAsync(imageUrl); - response.EnsureSuccessStatusCode(); - - var stream = await response.Content.ReadAsStreamAsync(); - return stream; - } - } - catch (Exception e) - { - return null; - } - } - - /// - /// 下载图片 - /// - /// - /// - private string DownloadImage(string url) - { - var localFile = Path.GetTempPath() + Guid.NewGuid().ToString("N"); - - // 下载 - var isSuccessed = StorageUtils.DownloadImage(url, localFile); - if (isSuccessed) - { - try - { - string md5 = Hash.GetMD5HashFromFile(localFile); - - if (File.Exists(localFile)) - { - string destFile = $"{StorageManager.GetCover()}/{md5}"; - - try - { - File.Delete(destFile); - } - catch - { - } - - // 移动到指定位置 - File.Move(localFile, destFile); - - return md5; - } - else - { - return null; - } - } - catch (Exception e) - { - Console.PrintLine("DownloadImage()发生异常: {0}", e); - LogManager.Error("StorageCover", e); - return null; - } - } - - return null; - } - - /// - /// 本地是否存在 - /// - /// - /// - public bool IsLocal(CoverDb coverDb, string url) - { - var cover = coverDb.QueryByUrl(url); - return cover != null; - } - - /// - /// 返回图片md5值 - /// - /// - /// - /// - public string LocalCover(CoverDb coverDb, string url) - { - var cover = coverDb.QueryByUrl(url); - return cover.Md5; - } -} \ No newline at end of file diff --git a/DownKyi.Core/Storage/StorageHeader.cs b/DownKyi.Core/Storage/StorageHeader.cs deleted file mode 100644 index 0f229fd..0000000 --- a/DownKyi.Core/Storage/StorageHeader.cs +++ /dev/null @@ -1,210 +0,0 @@ -using Avalonia; -using Avalonia.Media.Imaging; -using DownKyi.Core.Logging; -using DownKyi.Core.Storage.Database; -using DownKyi.Core.Utils.Encryptor; -using Console = DownKyi.Core.Utils.Debugging.Console; - -namespace DownKyi.Core.Storage; - -public class StorageHeader -{ - // 先判断本地有没有 - // 如果有 - // 则返回本地的图片路径 - // 如果没有 - // 则下载图片并返回本地的图片路径 - - /// - /// 获取用户头像缩略图 - /// - /// - /// - /// - /// - /// - /// - public Bitmap GetHeaderThumbnail(long mid, string name, string url, int width, int height) - { - string header = GetHeader(mid, name, url); - if (header == null) - { - return null; - } - - return GetHeaderThumbnail(header, width, height); - } - - /// - /// 获取用户头像缩略图 - /// - /// - /// - /// - /// - public Bitmap GetHeaderThumbnail(string header, int width, int height) - { - if (header == null) - { - return null; - } - - try - { - Bitmap bitmap = new Bitmap(header); - var thumbnail = bitmap.CreateScaledBitmap(new PixelSize(width, height), BitmapInterpolationMode.Unspecified); - - return thumbnail; - } - catch (ArgumentException) - { - try - { - /*SimpleDecoder simpleDecoder = new SimpleDecoder(header); - Bitmap bitmap = simpleDecoder.WebPtoBitmap(); - Image thumbnail = bitmap.GetThumbnailImage(width, height, null, IntPtr.Zero); - - return StorageUtils.BitmapToBitmapImage(new Bitmap(thumbnail));*/ - return null; - } - catch (Exception ex) - { - Console.PrintLine("GetHeaderThumbnail()发生异常: {0}", ex); - LogManager.Error("StorageHeader.GetHeaderThumbnail()", ex); - - return null; - } - } - catch (Exception e) - { - Console.PrintLine("GetHeaderThumbnail()发生异常: {0}", e); - LogManager.Error("StorageHeader.GetHeaderThumbnail()", e); - - return null; - } - } - - /// - /// 获取用户头像 - /// - /// - /// - public string GetHeader(long mid, string name, string url) - { - HeaderDb headerDb = new HeaderDb(); - Header header = headerDb.QueryByMid(mid); - - if (header != null) - { - string headerPath = $"{StorageManager.GetHeader()}/{header.Md5}"; - if (File.Exists(headerPath)) - { - Header newHeader = new Header - { - Mid = mid, - Name = name, - Url = url, - Md5 = header.Md5 - }; - headerDb.Update(newHeader); - //headerDb.Close(); - return $"{StorageManager.GetHeader()}/{header.Md5}"; - } - else - { - string md5 = DownloadImage(url); - if (md5 != null) - { - Header newHeader = new Header - { - Mid = mid, - Name = name, - Url = url, - Md5 = md5 - }; - headerDb.Insert(newHeader); - //headerDb.Close(); - return $"{StorageManager.GetHeader()}/{md5}"; - } - else - { - //headerDb.Close(); - return null; - } - } - } - else - { - var md5 = DownloadImage(url); - if (md5 != null) - { - Header newHeader = new Header - { - Mid = mid, - Name = name, - Url = url, - Md5 = md5 - }; - headerDb.Insert(newHeader); - //headerDb.Close(); - return $"{StorageManager.GetHeader()}/{md5}"; - } - else - { - //headerDb.Close(); - return null; - } - } - } - - - /// - /// 下载图片 - /// - /// - /// - private string DownloadImage(string url) - { - string localFile = Path.GetTempPath() + Guid.NewGuid().ToString("N"); - - // 下载 - bool isSuccessed = StorageUtils.DownloadImage(url, localFile); - if (isSuccessed) - { - try - { - string md5 = Hash.GetMD5HashFromFile(localFile); - - if (File.Exists(localFile)) - { - string destFile = $"{StorageManager.GetHeader()}/{md5}"; - - try - { - File.Delete(destFile); - } - catch - { - } - - // 移动到指定位置 - File.Move(localFile, destFile); - - return md5; - } - else - { - return null; - } - } - catch (Exception e) - { - Console.PrintLine("DownloadImage()发生异常: {0}", e); - LogManager.Error("StorageHeader", e); - return null; - } - } - - return null; - } -} \ No newline at end of file diff --git a/DownKyi.Core/Storage/StorageManager.cs b/DownKyi.Core/Storage/StorageManager.cs index f425c2f..902c72d 100644 --- a/DownKyi.Core/Storage/StorageManager.cs +++ b/DownKyi.Core/Storage/StorageManager.cs @@ -32,16 +32,6 @@ public static class StorageManager return Constant.Download; } - /// - /// 获取历史记录的文件路径 - /// - /// - public static string GetHistory() - { - CreateDirectory(Constant.Database); - return Constant.History; - } - /// /// 获取设置的文件路径 /// @@ -71,87 +61,15 @@ public static class StorageManager return CreateDirectory(Constant.Danmaku); } - /// - /// 获取字幕的文件夹路径 - /// - /// - public static string GetSubtitle() - { - return CreateDirectory(Constant.Subtitle); - } - - /// - /// 获取头图的文件夹路径 - /// - /// - public static string GetToutu() - { - return CreateDirectory(Constant.Toutu); - } - - /// - /// 获取封面的文件夹路径 - /// - /// - public static string GetCover() - { - return CreateDirectory(Constant.Cover); - } - - /// - /// 获取封面索引的文件路径 - /// - /// - public static string GetCoverIndex() - { - CreateDirectory(Constant.Cover); - return Constant.CoverIndex; - } - - /// - /// 获取视频快照的文件夹路径 - /// - /// - public static string GetSnapshot() - { - return CreateDirectory(Constant.Snapshot); - } - - /// - /// 获取视频快照索引的文件路径 - /// - /// - public static string GetSnapshotIndex() - { - CreateDirectory(Constant.Snapshot); - return Constant.SnapshotIndex; - } - - /// - /// 获取用户头像的文件夹路径 - /// - /// - public static string GetHeader() - { - return CreateDirectory(Constant.Header); - } - - /// - /// 获取用户头像索引的文件路径 - /// - /// - public static string GetHeaderIndex() - { - CreateDirectory(Constant.Header); - return Constant.HeaderIndex; - } - public static string GetMedia() { - CreateDirectory(Constant.Media); - return Constant.Media; + return CreateDirectory(Constant.Media); } + public static string GetCache() + { + return CreateDirectory(Constant.Cache); + } /// /// 若文件夹不存在,则创建文件夹 diff --git a/DownKyi.Core/Storage/StorageUtils.cs b/DownKyi.Core/Storage/StorageUtils.cs index b99fe6f..1204af3 100644 --- a/DownKyi.Core/Storage/StorageUtils.cs +++ b/DownKyi.Core/Storage/StorageUtils.cs @@ -4,7 +4,7 @@ using Console = DownKyi.Core.Utils.Debugging.Console; namespace DownKyi.Core.Storage; -internal static class StorageUtils +public static class StorageUtils { /// /// 下载图片 diff --git a/DownKyi.Core/Utils/Encryptor/Encryptor.File.cs b/DownKyi.Core/Utils/Encryptor/Encryptor.File.cs index ef978f7..8fa5b68 100644 --- a/DownKyi.Core/Utils/Encryptor/Encryptor.File.cs +++ b/DownKyi.Core/Utils/Encryptor/Encryptor.File.cs @@ -1,13 +1,11 @@ -using System; -using System.IO; -using System.Security.Cryptography; +using System.Security.Cryptography; namespace DownKyi.Core.Utils.Encryptor; public static partial class Encryptor { - private const ulong FC_TAG = 0xFC010203040506CF; - private const int BUFFER_SIZE = 128 * 1024; + private const ulong FcTag = 0xFC010203040506CF; + private const int BufferSize = 128 * 1024; /// /// 加密文件 @@ -17,59 +15,54 @@ public static partial class Encryptor /// 加密密码 public static void EncryptFile(string inFile, string outFile, string password) { - using (FileStream fin = File.OpenRead(inFile), fout = File.OpenWrite(outFile)) + using FileStream fin = File.OpenRead(inFile), fout = File.OpenWrite(outFile); + var lSize = fin.Length; // 输入文件长度 + var size = (int)lSize; + var bytes = new byte[BufferSize]; // 缓存 + var read = -1; // 输入文件读取数量 + var value = 0; + + // 获取IV和salt + var iv = GenerateRandomBytes(16); + var salt = GenerateRandomBytes(16); + + // 创建加密对象 + var sma = CreateRijndael(password, salt); + sma.IV = iv; + + // 在输出文件开始部分写入IV和salt + fout.Write(iv, 0, iv.Length); + fout.Write(salt, 0, salt.Length); + + // 创建散列加密 + HashAlgorithm hasher = SHA256.Create(); + using CryptoStream cout = new(fout, sma.CreateEncryptor(), CryptoStreamMode.Write), chash = new(Stream.Null, hasher, CryptoStreamMode.Write); + var bw = new BinaryWriter(cout); + bw.Write(lSize); + + bw.Write(FcTag); + + // 读写字节块到加密流缓冲区 + while ((read = fin.Read(bytes, 0, bytes.Length)) != 0) { - long lSize = fin.Length; // 输入文件长度 - int size = (int)lSize; - byte[] bytes = new byte[BUFFER_SIZE]; // 缓存 - int read = -1; // 输入文件读取数量 - int value = 0; - - // 获取IV和salt - byte[] IV = GenerateRandomBytes(16); - byte[] salt = GenerateRandomBytes(16); - - // 创建加密对象 - SymmetricAlgorithm sma = CreateRijndael(password, salt); - sma.IV = IV; - - // 在输出文件开始部分写入IV和salt - fout.Write(IV, 0, IV.Length); - fout.Write(salt, 0, salt.Length); - - // 创建散列加密 - HashAlgorithm hasher = SHA256.Create(); - using (CryptoStream cout = new(fout, sma.CreateEncryptor(), CryptoStreamMode.Write), - chash = new(Stream.Null, hasher, CryptoStreamMode.Write)) - { - BinaryWriter bw = new BinaryWriter(cout); - bw.Write(lSize); - - bw.Write(FC_TAG); - - // 读写字节块到加密流缓冲区 - while ((read = fin.Read(bytes, 0, bytes.Length)) != 0) - { - cout.Write(bytes, 0, read); - chash.Write(bytes, 0, read); - value += read; - } - - // 关闭加密流 - chash.Flush(); - chash.Close(); - - // 读取散列 - byte[] hash = hasher.Hash; - - // 输入文件写入散列 - cout.Write(hash, 0, hash.Length); - - // 关闭文件流 - cout.Flush(); - cout.Close(); - } + cout.Write(bytes, 0, read); + chash.Write(bytes, 0, read); + value += read; } + + // 关闭加密流 + chash.Flush(); + chash.Close(); + + // 读取散列 + var hash = hasher.Hash; + + // 输入文件写入散列 + cout.Write(hash, 0, hash.Length); + + // 关闭文件流 + cout.Flush(); + cout.Close(); } /// @@ -81,86 +74,81 @@ public static partial class Encryptor public static void DecryptFile(string inFile, string outFile, string password) { // 创建打开文件流 - using (FileStream fin = File.OpenRead(inFile), fout = File.OpenWrite(outFile)) + using FileStream fin = File.OpenRead(inFile), fout = File.OpenWrite(outFile); + var size = (int)fin.Length; + var bytes = new byte[BufferSize]; + var read = -1; + var value = 0; + var outValue = 0; + + var iv = new byte[16]; + fin.Read(iv, 0, 16); + var salt = new byte[16]; + fin.Read(salt, 0, 16); + + var sma = CreateRijndael(password, salt); + sma.IV = iv; + + value = 32; + long lSize = -1; + + // 创建散列对象, 校验文件 + HashAlgorithm hasher = SHA256.Create(); + + try { - int size = (int)fin.Length; - byte[] bytes = new byte[BUFFER_SIZE]; - int read = -1; - int value = 0; - int outValue = 0; + using CryptoStream cin = new(fin, sma.CreateDecryptor(), CryptoStreamMode.Read), + chash = new(Stream.Null, hasher, CryptoStreamMode.Write); + // 读取文件长度 + var br = new BinaryReader(cin); + lSize = br.ReadInt64(); + var tag = br.ReadUInt64(); - byte[] IV = new byte[16]; - fin.Read(IV, 0, 16); - byte[] salt = new byte[16]; - fin.Read(salt, 0, 16); + if (FcTag != tag) throw new CryptoHelpException("文件被破坏"); - SymmetricAlgorithm sma = CreateRijndael(password, salt); - sma.IV = IV; + var numReads = lSize / BufferSize; - value = 32; - long lSize = -1; + var slack = lSize % BufferSize; - // 创建散列对象, 校验文件 - HashAlgorithm hasher = SHA256.Create(); - - try + for (var i = 0; i < numReads; ++i) { - using (CryptoStream cin = new(fin, sma.CreateDecryptor(), CryptoStreamMode.Read), - chash = new(Stream.Null, hasher, CryptoStreamMode.Write)) - { - // 读取文件长度 - BinaryReader br = new BinaryReader(cin); - lSize = br.ReadInt64(); - ulong tag = br.ReadUInt64(); - - if (FC_TAG != tag) - throw new CryptoHelpException("文件被破坏"); - - long numReads = lSize / BUFFER_SIZE; - - long slack = lSize % BUFFER_SIZE; - - for (int i = 0; i < numReads; ++i) - { - read = cin.Read(bytes, 0, bytes.Length); - fout.Write(bytes, 0, read); - chash.Write(bytes, 0, read); - value += read; - outValue += read; - } - - if (slack > 0) - { - read = cin.Read(bytes, 0, (int)slack); - fout.Write(bytes, 0, read); - chash.Write(bytes, 0, read); - value += read; - outValue += read; - } - - chash.Flush(); - chash.Close(); - - fout.Flush(); - fout.Close(); - - byte[] curHash = hasher.Hash; - - // 获取比较和旧的散列对象 - byte[] oldHash = new byte[hasher.HashSize / 8]; - read = cin.Read(oldHash, 0, oldHash.Length); - if ((oldHash.Length != read) || (!CheckByteArrays(oldHash, curHash))) - throw new CryptoHelpException("文件被破坏"); - } - } - catch (Exception e) - { - Console.WriteLine("DecryptFile()发生异常: {0}", e); + read = cin.Read(bytes, 0, bytes.Length); + fout.Write(bytes, 0, read); + chash.Write(bytes, 0, read); + value += read; + outValue += read; } - if (outValue != lSize) - throw new CryptoHelpException("文件大小不匹配"); + if (slack > 0) + { + read = cin.Read(bytes, 0, (int)slack); + fout.Write(bytes, 0, read); + chash.Write(bytes, 0, read); + value += read; + outValue += read; + } + + chash.Flush(); + chash.Close(); + + fout.Flush(); + fout.Close(); + + var curHash = hasher.Hash; + + // 获取比较和旧的散列对象 + var oldHash = new byte[hasher.HashSize / 8]; + read = cin.Read(oldHash, 0, oldHash.Length); + if (oldHash.Length != read || !CheckByteArrays(oldHash, curHash)) + throw new CryptoHelpException("文件被破坏"); } + catch (Exception e) + { + Console.WriteLine("DecryptFile()发生异常: {0}", e); + } + + if (outValue != lSize) + throw new CryptoHelpException("文件大小不匹配"); } /// @@ -173,7 +161,7 @@ public static partial class Encryptor { if (b1.Length == b2.Length) { - for (int i = 0; i < b1.Length; ++i) + for (var i = 0; i < b1.Length; ++i) { if (b1[i] != b2[i]) return false; @@ -193,9 +181,9 @@ public static partial class Encryptor /// 加密对象 private static SymmetricAlgorithm CreateRijndael(string password, byte[] salt) { - PasswordDeriveBytes pdb = new PasswordDeriveBytes(password, salt, "SHA256", 1000); + var pdb = new PasswordDeriveBytes(password, salt, "SHA256", 1000); - SymmetricAlgorithm sma = Rijndael.Create(); + SymmetricAlgorithm sma = Aes.Create(); sma.KeySize = 256; sma.Key = pdb.GetBytes(32); sma.Padding = PaddingMode.Zeros; @@ -210,9 +198,9 @@ public static partial class Encryptor private static byte[] GenerateRandomBytes(int count) { // 加密文件随机数生成 - RandomNumberGenerator rand = new RNGCryptoServiceProvider(); + var rand = RandomNumberGenerator.Create(); - byte[] bytes = new byte[count]; + var bytes = new byte[count]; rand.GetBytes(bytes); return bytes; } diff --git a/DownKyi.Core/Utils/Encryptor/Encryptor.String.cs b/DownKyi.Core/Utils/Encryptor/Encryptor.String.cs index 199c4c4..0394d1b 100644 --- a/DownKyi.Core/Utils/Encryptor/Encryptor.String.cs +++ b/DownKyi.Core/Utils/Encryptor/Encryptor.String.cs @@ -18,12 +18,12 @@ public static partial class Encryptor try { var rgbKey = Encoding.UTF8.GetBytes(encryptKey[..8]); //转换为字节 - var rgbIV = Encoding.UTF8.GetBytes(encryptKey[..8]); + var rgbIv = Encoding.UTF8.GetBytes(encryptKey[..8]); var inputByteArray = Encoding.UTF8.GetBytes(encryptString); - var dCSP = new DESCryptoServiceProvider(); //实例化数据加密标准 + var des = DES.Create(); //实例化数据加密标准 var mStream = new MemoryStream(); //实例化内存流 //将数据流链接到加密转换的流 - var cStream = new CryptoStream(mStream, dCSP.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write); + var cStream = new CryptoStream(mStream, des.CreateEncryptor(rgbKey, rgbIv), CryptoStreamMode.Write); cStream.Write(inputByteArray, 0, inputByteArray.Length); cStream.FlushFinalBlock(); // 转base64 @@ -48,11 +48,11 @@ public static partial class Encryptor try { var rgbKey = Encoding.UTF8.GetBytes(decryptKey); - var rgbIV = Encoding.UTF8.GetBytes(decryptKey); + var rgbIv = Encoding.UTF8.GetBytes(decryptKey); var inputByteArray = Convert.FromBase64String(decryptString); - var DCSP = new DESCryptoServiceProvider(); + var des = DES.Create(); var mStream = new MemoryStream(); - var cStream = new CryptoStream(mStream, DCSP.CreateDecryptor(rgbKey, rgbIV), CryptoStreamMode.Write); + var cStream = new CryptoStream(mStream, des.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 b246139..f799039 100644 --- a/DownKyi.Core/Utils/Encryptor/Hash.cs +++ b/DownKyi.Core/Utils/Encryptor/Hash.cs @@ -10,7 +10,7 @@ public static class Hash /// /// /// - public static string GetMd5Hash(string? input) + public static string? GetMd5Hash(string? input) { if (input == null) { @@ -45,7 +45,7 @@ public static class Hash try { var file = new FileStream(fileName, FileMode.Open); - MD5 md5 = new MD5CryptoServiceProvider(); + var md5 = MD5.Create(); var retVal = md5.ComputeHash(file); file.Close(); diff --git a/DownKyi.Core/Utils/Format.cs b/DownKyi.Core/Utils/Format.cs index 1dd871c..8b5e1f2 100644 --- a/DownKyi.Core/Utils/Format.cs +++ b/DownKyi.Core/Utils/Format.cs @@ -87,15 +87,13 @@ public static class Format /// public static string FormatSpeed(float speed) { - string formatSpeed = speed switch + return speed switch { <= 0 => "0B/s", < 1024 => $"{speed:F2}B/s", < 1024 * 1024 => $"{speed / 1024:F2}KB/s", _ => $"{speed / 1024 / 1024:F2}MB/s" }; - - return formatSpeed; } /// @@ -105,16 +103,14 @@ public static class Format /// public static string FormatFileSize(long fileSize) { - string formatFileSize = fileSize switch + return fileSize switch { <= 0 => "0B", - < 1024 => fileSize.ToString() + "B", + < 1024 => fileSize + "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; } /// @@ -128,9 +124,9 @@ public static class Format destName = Path.GetInvalidFileNameChars().Aggregate(destName, (current, c) => current.Replace(c.ToString(), string.Empty)); var cleanedName = destName - .SkipWhile(c => c == ' ' || c == '.') + .SkipWhile(c => c is ' ' or '.') .Reverse() - .SkipWhile(c => c == ' ' || c == '.') + .SkipWhile(c => c is ' ' or '.') .Reverse() .ToArray(); diff --git a/DownKyi.Core/Utils/ListHelper.cs b/DownKyi.Core/Utils/ListHelper.cs index 875150c..e488aa8 100644 --- a/DownKyi.Core/Utils/ListHelper.cs +++ b/DownKyi.Core/Utils/ListHelper.cs @@ -39,6 +39,7 @@ public static class ListHelper /// /// /// + /// public static void InsertUnique(Collection list, T item, int index, ref T currentSelection) { if (!list.Contains(item)) diff --git a/DownKyi.Core/Utils/ObjectHelper.cs b/DownKyi.Core/Utils/ObjectHelper.cs index 7fcff78..718fbe9 100644 --- a/DownKyi.Core/Utils/ObjectHelper.cs +++ b/DownKyi.Core/Utils/ObjectHelper.cs @@ -36,7 +36,7 @@ public static class ObjectHelper } // 获取expires - var expires = strList2.FirstOrDefault(it => it.Contains("Expires")).Split('=')[1]; + var expires = strList2.FirstOrDefault(it => it.Contains("Expires"))?.Split('=')[1]; var dateTime = DateTime.Now; dateTime = dateTime.AddSeconds(int.Parse(expires)); @@ -52,14 +52,13 @@ public static class ObjectHelper var value = strList3[1]; // 不需要 - if (name == "Expires" || name == "gourl") + if (name is "Expires" or "gourl") { continue; } // 添加cookie - cookieContainer.Add( - new Cookie(name, value.Replace(",", "%2c"), "/", ".bilibili.com") { Expires = dateTime }); + cookieContainer.Add(new Cookie(name, value.Replace(",", "%2c"), "/", ".bilibili.com") { Expires = dateTime }); Console.PrintLine(name + ": " + value + "\t" + cookieContainer.Count); } @@ -75,17 +74,16 @@ public static class ObjectHelper { var lstCookies = new List(); - var 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 (var pathList in table.Values) + foreach (var pathList in table?.Values ?? Array.Empty()) { - var lstCookieCol = (SortedList)pathList.GetType().InvokeMember("m_list", - BindingFlags.NonPublic | BindingFlags.GetField - | BindingFlags.Instance, null, pathList, - new object[] { }); - foreach (CookieCollection colCookies in lstCookieCol.Values) + var lstCookieCol = (SortedList?)pathList.GetType().InvokeMember("m_list", + BindingFlags.NonPublic | BindingFlags.GetField | BindingFlags.Instance, null, pathList, + Array.Empty()); + foreach (CookieCollection colCookies in lstCookieCol?.Values ?? Array.Empty()) { foreach (Cookie c in colCookies) { @@ -113,9 +111,9 @@ public static class ObjectHelper /// /// /// - public static CookieContainer ReadCookiesFromDisk(string file) + public static CookieContainer? ReadCookiesFromDisk(string file) { - return (CookieContainer)ReadObjectFromDisk(file); + return (CookieContainer?)ReadObjectFromDisk(file); } /// @@ -156,7 +154,7 @@ public static class ObjectHelper /// /// /// - public static object ReadObjectFromDisk(string file) + public static object? ReadObjectFromDisk(string file) { try { diff --git a/DownKyi.Core/Utils/QRCode.cs b/DownKyi.Core/Utils/QRCode.cs index f297ff1..455a8fe 100644 --- a/DownKyi.Core/Utils/QRCode.cs +++ b/DownKyi.Core/Utils/QRCode.cs @@ -3,7 +3,7 @@ using QRCoder; namespace DownKyi.Core.Utils; -public static class QRCode +public static class QrCode { /// /// 生成二维码 @@ -16,25 +16,22 @@ public static class QRCode /// 图标边框厚度 /// 二维码白边 /// 位图 - public static Bitmap EncodeQRCode(string msg, int version, int pixel, string? iconPath, int iconSize, int iconBorder, bool whiteEdge) + public static Bitmap EncodeQrCode(string msg, int version, int pixel, string? iconPath, int iconSize, int iconBorder, bool whiteEdge) { var codeGenerator = new QRCodeGenerator(); - var codeData = codeGenerator.CreateQrCode(msg, QRCodeGenerator.ECCLevel.H /* 这里设置容错率的一个级别 */, true, - false, QRCodeGenerator.EciMode.Utf8, version); + var codeData = codeGenerator.CreateQrCode(msg, QRCodeGenerator.ECCLevel.H /* 这里设置容错率的一个级别 */, true, false, QRCodeGenerator.EciMode.Utf8, version); var qrCode = new BitmapByteQRCode(codeData); var qrCodeAsBitmapByteArr = qrCode.GetGraphic(20); - Bitmap icon; - icon = string.IsNullOrEmpty(iconPath) ? null : new Bitmap(iconPath); + // Bitmap icon; + // icon = string.IsNullOrEmpty(iconPath) ? null : new Bitmap(iconPath); - Bitmap bmp; using var ms = new MemoryStream(qrCodeAsBitmapByteArr); - bmp = new Bitmap(ms); + var 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); - return bmp; } } \ No newline at end of file diff --git a/DownKyi/App.axaml.cs b/DownKyi/App.axaml.cs index 9e16bd9..bc169bd 100644 --- a/DownKyi/App.axaml.cs +++ b/DownKyi/App.axaml.cs @@ -148,6 +148,8 @@ public partial class App : PrismApplication { if (e.Action == NotifyCollectionChangedAction.Add) { + if (e.NewItems == null) return; + foreach (var item in e.NewItems) { if (item is DownloadingItem downloading) @@ -160,6 +162,8 @@ public partial class App : PrismApplication if (e.Action == NotifyCollectionChangedAction.Remove) { + if (e.OldItems == null) return; + foreach (var item in e.OldItems) { if (item is DownloadingItem downloading) @@ -179,6 +183,7 @@ public partial class App : PrismApplication { if (e.Action == NotifyCollectionChangedAction.Add) { + if (e.NewItems == null) return; foreach (var item in e.NewItems) { if (item is DownloadedItem downloaded) @@ -191,6 +196,7 @@ public partial class App : PrismApplication if (e.Action == NotifyCollectionChangedAction.Remove) { + if (e.OldItems == null) return; foreach (var item in e.OldItems) { if (item is DownloadedItem downloaded) @@ -207,16 +213,16 @@ public partial class App : PrismApplication var download = SettingsManager.GetInstance().GetDownloader(); switch (download) { - case Core.Settings.Downloader.NOT_SET: + case Core.Settings.Downloader.NotSet: break; - case Core.Settings.Downloader.BUILT_IN: - _downloadService = new BuiltinDownloadService(DownloadingList, DownloadedList, (IDialogService)Container.GetContainer().GetService(typeof(IDialogService))); + case Core.Settings.Downloader.BuiltIn: + _downloadService = new BuiltinDownloadService(DownloadingList, DownloadedList, (IDialogService?)Container.GetContainer().GetService(typeof(IDialogService))); break; - case Core.Settings.Downloader.ARIA: - _downloadService = new AriaDownloadService(DownloadingList, DownloadedList, (IDialogService)Container.GetContainer().GetService(typeof(IDialogService))); + case Core.Settings.Downloader.Aria: + _downloadService = new AriaDownloadService(DownloadingList, DownloadedList, (IDialogService?)Container.GetContainer().GetService(typeof(IDialogService))); break; - case Core.Settings.Downloader.CUSTOM_ARIA: - _downloadService = new CustomAriaDownloadService(DownloadingList, DownloadedList, (IDialogService)Container.GetContainer().GetService(typeof(IDialogService))); + case Core.Settings.Downloader.CustomAria: + _downloadService = new CustomAriaDownloadService(DownloadingList, DownloadedList, (IDialogService?)Container.GetContainer().GetService(typeof(IDialogService))); break; } @@ -264,7 +270,7 @@ public partial class App : PrismApplication // 按序号排序 list?.Sort((x, y) => { - var compare = x.MainTitle.CompareTo(y.MainTitle); + var compare = string.Compare(x.MainTitle, y.MainTitle, StringComparison.Ordinal); return compare == 0 ? x.Order.CompareTo(y.Order) : compare; }); break; diff --git a/DownKyi/AppConstant.cs b/DownKyi/AppConstant.cs index cad527c..88de5b9 100644 --- a/DownKyi/AppConstant.cs +++ b/DownKyi/AppConstant.cs @@ -1,7 +1,6 @@ -namespace DownKyi +namespace DownKyi; + +public class AppConstant { - public class AppConstant - { - public const string ClipboardId = "32ff00b1-1a09-4b25-9ca7-dcb6914b141c"; - } -} + public const string ClipboardId = "32ff00b1-1a09-4b25-9ca7-dcb6914b141c"; +} \ No newline at end of file diff --git a/DownKyi/CustomControl/AsyncImageLoader/IAsyncImageLoader.cs b/DownKyi/CustomControl/AsyncImageLoader/IAsyncImageLoader.cs new file mode 100644 index 0000000..ede1479 --- /dev/null +++ b/DownKyi/CustomControl/AsyncImageLoader/IAsyncImageLoader.cs @@ -0,0 +1,15 @@ +using System; +using System.Threading.Tasks; +using Avalonia.Media.Imaging; + +namespace DownKyi.CustomControl.AsyncImageLoader; + +public interface IAsyncImageLoader : IDisposable +{ + /// + /// Loads image + /// + /// Target url + /// Bitmap + public Task ProvideImageAsync(string url); +} \ No newline at end of file diff --git a/DownKyi/CustomControl/AsyncImageLoader/ImageBrushLoader.cs b/DownKyi/CustomControl/AsyncImageLoader/ImageBrushLoader.cs new file mode 100644 index 0000000..3afba63 --- /dev/null +++ b/DownKyi/CustomControl/AsyncImageLoader/ImageBrushLoader.cs @@ -0,0 +1,73 @@ +using System; +using System.IO; +using Avalonia; +using Avalonia.Logging; +using Avalonia.Media; +using Avalonia.Media.Imaging; +using DownKyi.Core.Storage; +using DownKyi.CustomControl.AsyncImageLoader.Loaders; + +namespace DownKyi.CustomControl.AsyncImageLoader; + +public static class ImageBrushLoader +{ + private static readonly ParametrizedLogger? Logger; + public static IAsyncImageLoader AsyncImageLoader { get; set; } = new DiskCachedWebImageLoader(Path.Combine(StorageManager.GetCache(), "Images")); + + static ImageBrushLoader() + { + SourceProperty.Changed.AddClassHandler(OnSourceChanged); + Logger = Avalonia.Logging.Logger.TryGet(LogEventLevel.Error, ImageLoader.AsyncImageLoaderLogArea); + } + + private static async void OnSourceChanged(ImageBrush imageBrush, AvaloniaPropertyChangedEventArgs args) + { + var (oldValue, newValue) = args.GetOldAndNewValue(); + if (oldValue == newValue) + return; + + SetIsLoading(imageBrush, true); + + Bitmap? bitmap = null; + try + { + if (newValue is not null) + { + bitmap = await AsyncImageLoader.ProvideImageAsync(newValue); + } + } + catch (Exception e) + { + Logger?.Log("ImageBrushLoader", "ImageBrushLoader image resolution failed: {0}", e); + } + + if (GetSource(imageBrush) != newValue) return; + imageBrush.Source = bitmap; + + SetIsLoading(imageBrush, false); + } + + public static readonly AttachedProperty SourceProperty = AvaloniaProperty.RegisterAttached("Source", typeof(ImageLoader)); + + public static string? GetSource(ImageBrush element) + { + return element.GetValue(SourceProperty); + } + + public static void SetSource(ImageBrush element, string? value) + { + element.SetValue(SourceProperty, value); + } + + public static readonly AttachedProperty IsLoadingProperty = AvaloniaProperty.RegisterAttached("IsLoading", typeof(ImageLoader)); + + public static bool GetIsLoading(ImageBrush element) + { + return element.GetValue(IsLoadingProperty); + } + + private static void SetIsLoading(ImageBrush element, bool value) + { + element.SetValue(IsLoadingProperty, value); + } +} \ No newline at end of file diff --git a/DownKyi/CustomControl/AsyncImageLoader/ImageLoader.cs b/DownKyi/CustomControl/AsyncImageLoader/ImageLoader.cs new file mode 100644 index 0000000..11a1027 --- /dev/null +++ b/DownKyi/CustomControl/AsyncImageLoader/ImageLoader.cs @@ -0,0 +1,107 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.IO; +using System.Threading; +using System.Threading.Tasks; +using Avalonia; +using Avalonia.Controls; +using Avalonia.Logging; +using Avalonia.Media.Imaging; +using DownKyi.Core.Storage; +using DownKyi.CustomControl.AsyncImageLoader.Loaders; + +namespace DownKyi.CustomControl.AsyncImageLoader; + +public static class ImageLoader +{ + private static readonly ParametrizedLogger? Logger; + + public const string AsyncImageLoaderLogArea = "AsyncImageLoader"; + + public static readonly AttachedProperty SourceProperty = + AvaloniaProperty.RegisterAttached("Source", typeof(ImageLoader)); + + public static readonly AttachedProperty IsLoadingProperty = + AvaloniaProperty.RegisterAttached("IsLoading", typeof(ImageLoader)); + + static ImageLoader() + { + SourceProperty.Changed.AddClassHandler(OnSourceChanged); + Logger = Avalonia.Logging.Logger.TryGet(LogEventLevel.Error, AsyncImageLoaderLogArea); + } + + public static IAsyncImageLoader AsyncImageLoader { get; set; } = new DiskCachedWebImageLoader(Path.Combine(StorageManager.GetCache(), "Images")); + + private static readonly ConcurrentDictionary PendingOperations = new(); + + private static async void OnSourceChanged(Image sender, AvaloniaPropertyChangedEventArgs args) + { + var url = args.GetNewValue(); + + var cts = PendingOperations.AddOrUpdate(sender, new CancellationTokenSource(), (x, y) => + { + y.Cancel(); + return new CancellationTokenSource(); + } + ); + + if (url == null) + { + ((ICollection>)PendingOperations).Remove(new KeyValuePair(sender, cts)); + sender.Source = null; + return; + } + + SetIsLoading(sender, true); + + var bitmap = await Task.Run(async () => + { + try + { + // A small delay allows to cancel early if the image goes out of screen too fast (eg. scrolling) + // The Bitmap constructor is expensive and cannot be cancelled + await Task.Delay(10, cts.Token); + + return await AsyncImageLoader.ProvideImageAsync(url); + } + catch (TaskCanceledException) + { + return null; + } + catch (Exception e) + { + Logger?.Log(LogEventLevel.Error, "ImageLoader image resolution failed: {0}", e); + + return null; + } + }); + + if (bitmap != null && !cts.Token.IsCancellationRequested) + sender.Source = bitmap!; + + // "It is not guaranteed to be thread safe by ICollection, but ConcurrentDictionary's implementation is. Additionally, we recently exposed this API for .NET 5 as a public ConcurrentDictionary.TryRemove" + ((ICollection>)PendingOperations).Remove(new KeyValuePair(sender, cts)); + SetIsLoading(sender, false); + } + + public static string? GetSource(Image element) + { + return element.GetValue(SourceProperty); + } + + public static void SetSource(Image element, string? value) + { + element.SetValue(SourceProperty, value); + } + + public static bool GetIsLoading(Image element) + { + return element.GetValue(IsLoadingProperty); + } + + private static void SetIsLoading(Image element, bool value) + { + element.SetValue(IsLoadingProperty, value); + } +} \ No newline at end of file diff --git a/DownKyi/CustomControl/AsyncImageLoader/Loaders/AdvancedImage.axaml b/DownKyi/CustomControl/AsyncImageLoader/Loaders/AdvancedImage.axaml new file mode 100644 index 0000000..c400e96 --- /dev/null +++ b/DownKyi/CustomControl/AsyncImageLoader/Loaders/AdvancedImage.axaml @@ -0,0 +1,20 @@ + + + + + + + \ No newline at end of file diff --git a/DownKyi/CustomControl/AsyncImageLoader/Loaders/AdvancedImage.axaml.cs b/DownKyi/CustomControl/AsyncImageLoader/Loaders/AdvancedImage.axaml.cs new file mode 100644 index 0000000..6fae2b9 --- /dev/null +++ b/DownKyi/CustomControl/AsyncImageLoader/Loaders/AdvancedImage.axaml.cs @@ -0,0 +1,339 @@ +using System; +using System.Threading; +using System.Threading.Tasks; +using Avalonia; +using Avalonia.Controls; +using Avalonia.Logging; +using Avalonia.Markup.Xaml; +using Avalonia.Media; +using Avalonia.Media.Imaging; +using Avalonia.Platform; + +namespace DownKyi.CustomControl.AsyncImageLoader.Loaders; + +public class AdvancedImage : ContentControl +{ + /// + /// Defines the property. + /// + public static readonly StyledProperty LoaderProperty = AvaloniaProperty.Register(nameof(Loader)); + + /// + /// Defines the property. + /// + public static readonly StyledProperty SourceProperty = AvaloniaProperty.Register(nameof(Source)); + + /// + /// Defines the property. + /// + public static readonly DirectProperty ShouldLoaderChangeTriggerUpdateProperty = + AvaloniaProperty.RegisterDirect( + nameof(ShouldLoaderChangeTriggerUpdate), + image => image._shouldLoaderChangeTriggerUpdate, + (image, b) => image._shouldLoaderChangeTriggerUpdate = b + ); + + /// + /// Defines the property. + /// + public static readonly DirectProperty IsLoadingProperty = + AvaloniaProperty.RegisterDirect( + nameof(IsLoading), + image => image._isLoading); + + /// + /// Defines the property. + /// + public static readonly DirectProperty CurrentImageProperty = + AvaloniaProperty.RegisterDirect( + nameof(CurrentImage), + image => image._currentImage); + + /// + /// Defines the property. + /// + public static readonly StyledProperty StretchProperty = + Image.StretchProperty.AddOwner(); + + /// + /// Defines the property. + /// + public static readonly StyledProperty StretchDirectionProperty = + Image.StretchDirectionProperty.AddOwner(); + + private readonly Uri? _baseUri; + + private RoundedRect _cornerRadiusClip; + + private IImage? _currentImage; + private bool _isCornerRadiusUsed; + + private bool _isLoading; + + private bool _shouldLoaderChangeTriggerUpdate; + + private CancellationTokenSource? _updateCancellationToken; + private readonly ParametrizedLogger? _logger; + + static AdvancedImage() + { + AffectsRender(CurrentImageProperty, StretchProperty, StretchDirectionProperty, + CornerRadiusProperty); + AffectsMeasure(CurrentImageProperty, StretchProperty, StretchDirectionProperty); + } + + /// + /// Initializes a new instance of the class. + /// + /// The base URL for the XAML context. + public AdvancedImage(Uri? baseUri) + { + _baseUri = baseUri; + _logger = Logger.TryGet(LogEventLevel.Error, ImageLoader.AsyncImageLoaderLogArea); + } + + /// + /// Initializes a new instance of the class. + /// + /// The XAML service provider. + public AdvancedImage(IServiceProvider serviceProvider) + : this((serviceProvider.GetService(typeof(IUriContext)) as IUriContext)?.BaseUri) + { + } + + /// + /// Gets or sets the URI for image that will be displayed. + /// + public IAsyncImageLoader? Loader + { + get => GetValue(LoaderProperty); + set => SetValue(LoaderProperty, value); + } + + /// + /// Gets or sets the URI for image that will be displayed. + /// + public string? Source + { + get => GetValue(SourceProperty); + set => SetValue(SourceProperty, value); + } + + /// + /// Gets or sets the value controlling whether the image should be reloaded after changing the loader. + /// + public bool ShouldLoaderChangeTriggerUpdate + { + get => _shouldLoaderChangeTriggerUpdate; + set => SetAndRaise(ShouldLoaderChangeTriggerUpdateProperty, ref _shouldLoaderChangeTriggerUpdate, value); + } + + /// + /// Gets a value indicating is image currently is loading state. + /// + public bool IsLoading + { + get => _isLoading; + private set => SetAndRaise(IsLoadingProperty, ref _isLoading, value); + } + + /// + /// Gets a currently loaded IImage. + /// + public IImage? CurrentImage + { + get => _currentImage; + set => SetAndRaise(CurrentImageProperty, ref _currentImage, value); + } + + /// + /// Gets or sets a value controlling how the image will be stretched. + /// + public Stretch Stretch + { + get => GetValue(StretchProperty); + set => SetValue(StretchProperty, value); + } + + /// + /// Gets or sets a value controlling in what direction the image will be stretched. + /// + public StretchDirection StretchDirection + { + get => GetValue(StretchDirectionProperty); + set => SetValue(StretchDirectionProperty, value); + } + + protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) + { + if (change.Property == SourceProperty) + UpdateImage(change.GetNewValue(), Loader); + else if (change.Property == LoaderProperty && ShouldLoaderChangeTriggerUpdate) + UpdateImage(change.GetNewValue(), Loader); + else if (change.Property == CurrentImageProperty) + ClearSourceIfUserProvideImage(); + else if (change.Property == CornerRadiusProperty) + UpdateCornerRadius(change.GetNewValue()); + else if (change.Property == BoundsProperty && CornerRadius != default) UpdateCornerRadius(CornerRadius); + base.OnPropertyChanged(change); + } + + private void ClearSourceIfUserProvideImage() + { + if (CurrentImage is not null and not ImageWrapper) + { + // User provided image himself + Source = null; + } + } + + private async void UpdateImage(string? source, IAsyncImageLoader? loader) + { + var cancellationTokenSource = new CancellationTokenSource(); + + var oldCancellationToken = Interlocked.Exchange(ref _updateCancellationToken, cancellationTokenSource); + + try + { + oldCancellationToken?.Cancel(); + } + catch (ObjectDisposedException) + { + } + + if (source is null && CurrentImage is not ImageWrapper) + { + // User provided image himself + return; + } + + IsLoading = true; + CurrentImage = null; + + + var bitmap = await Task.Run(async () => + { + try + { + if (source == null) + return null; + + // A small delay allows to cancel early if the image goes out of screen too fast (eg. scrolling) + // The Bitmap constructor is expensive and cannot be cancelled + await Task.Delay(10, cancellationTokenSource.Token); + + // Hack to support relative URI + // TODO: Refactor IAsyncImageLoader to support BaseUri + try + { + var uri = new Uri(source, UriKind.RelativeOrAbsolute); + if (AssetLoader.Exists(uri, _baseUri)) + return new Bitmap(AssetLoader.Open(uri, _baseUri)); + } + catch (Exception) + { + // ignored + } + + loader ??= ImageLoader.AsyncImageLoader; + return await loader.ProvideImageAsync(source); + } + catch (TaskCanceledException) + { + return null; + } + catch (Exception e) + { + _logger?.Log(this, "AdvancedImage image resolution failed: {0}", e); + + return null; + } + finally + { + cancellationTokenSource.Dispose(); + } + }, CancellationToken.None); + + if (cancellationTokenSource.IsCancellationRequested) + return; + CurrentImage = bitmap is null ? null : new ImageWrapper(bitmap); + IsLoading = false; + } + + private void UpdateCornerRadius(CornerRadius radius) + { + _isCornerRadiusUsed = radius != default; + _cornerRadiusClip = new RoundedRect(new Rect(0, 0, Bounds.Width, Bounds.Height), radius); + } + + /// + /// Renders the control. + /// + /// The drawing context. + public override void Render(DrawingContext context) + { + var source = CurrentImage; + + if (source != null && Bounds is { Width: > 0, Height: > 0 }) + { + var viewPort = new Rect(Bounds.Size); + var sourceSize = source.Size; + + var scale = Stretch.CalculateScaling(Bounds.Size, sourceSize, StretchDirection); + var scaledSize = sourceSize * scale; + var destRect = viewPort + .CenterRect(new Rect(scaledSize)) + .Intersect(viewPort); + var sourceRect = new Rect(sourceSize) + .CenterRect(new Rect(destRect.Size / scale)); + + DrawingContext.PushedState? pushedState = + _isCornerRadiusUsed ? context.PushClip(_cornerRadiusClip) : null; + context.DrawImage(source, sourceRect, destRect); + pushedState?.Dispose(); + } + else + { + base.Render(context); + } + } + + /// + /// Measures the control. + /// + /// The available size. + /// The desired size of the control. + protected override Size MeasureOverride(Size availableSize) + { + return CurrentImage != null + ? Stretch.CalculateSize(availableSize, CurrentImage.Size, StretchDirection) + : base.MeasureOverride(availableSize); + } + + /// + protected override Size ArrangeOverride(Size finalSize) + { + return CurrentImage != null + ? Stretch.CalculateSize(finalSize, CurrentImage.Size) + : base.ArrangeOverride(finalSize); + } + + public sealed class ImageWrapper : IImage + { + public IImage ImageImplementation { get; } + + internal ImageWrapper(IImage imageImplementation) + { + ImageImplementation = imageImplementation; + } + + /// + public void Draw(DrawingContext context, Rect sourceRect, Rect destRect) + { + ImageImplementation.Draw(context, sourceRect, destRect); + } + + /// + public Size Size => ImageImplementation.Size; + } +} \ No newline at end of file diff --git a/DownKyi/CustomControl/AsyncImageLoader/Loaders/BaseWebImageLoader.cs b/DownKyi/CustomControl/AsyncImageLoader/Loaders/BaseWebImageLoader.cs new file mode 100644 index 0000000..d37f722 --- /dev/null +++ b/DownKyi/CustomControl/AsyncImageLoader/Loaders/BaseWebImageLoader.cs @@ -0,0 +1,177 @@ +using System; +using System.IO; +using System.Net.Http; +using System.Threading.Tasks; +using Avalonia.Logging; +using Avalonia.Media.Imaging; +using Avalonia.Platform; + +namespace DownKyi.CustomControl.AsyncImageLoader.Loaders; + +public class BaseWebImageLoader : IAsyncImageLoader +{ + private readonly ParametrizedLogger? _logger; + private readonly bool _shouldDisposeHttpClient; + + /// + /// Initializes a new instance with new instance + /// + public BaseWebImageLoader() : this(new HttpClient(), true) + { + } + + /// + /// Initializes a new instance with the provided , and specifies whether that + /// should be disposed when this instance is disposed. + /// + /// The HttpMessageHandler responsible for processing the HTTP response messages. + /// + /// true if the inner handler should be disposed of by Dispose; false if you intend to + /// reuse the HttpClient. + /// + public BaseWebImageLoader(HttpClient httpClient, bool disposeHttpClient) + { + HttpClient = httpClient; + _shouldDisposeHttpClient = disposeHttpClient; + _logger = Logger.TryGet(LogEventLevel.Error, ImageLoader.AsyncImageLoaderLogArea); + } + + protected HttpClient HttpClient { get; } + + /// + public virtual async Task ProvideImageAsync(string url) + { + return await LoadAsync(url).ConfigureAwait(false); + } + + public void Dispose() + { + Dispose(true); + GC.SuppressFinalize(this); + } + + /// + /// Attempts to load bitmap + /// + /// Target url + /// Bitmap + protected virtual async Task LoadAsync(string url) + { + var internalOrCachedBitmap = + await LoadFromLocalAsync(url).ConfigureAwait(false) + ?? await LoadFromInternalAsync(url).ConfigureAwait(false) + ?? await LoadFromGlobalCache(url).ConfigureAwait(false); + if (internalOrCachedBitmap != null) return internalOrCachedBitmap; + + try + { + var externalBytes = await LoadDataFromExternalAsync(url).ConfigureAwait(false); + if (externalBytes == null) return null; + + using var memoryStream = new MemoryStream(externalBytes); + var bitmap = new Bitmap(memoryStream); + await SaveToGlobalCache(url, externalBytes).ConfigureAwait(false); + return bitmap; + } + catch (Exception e) + { + _logger?.Log(this, "Failed to resolve image: {RequestUri}\nException: {Exception}", url, e); + + return null; + } + } + + /// + /// the url maybe is local file url,so if file exists ,we got a Bitmap + /// + /// + /// + private Task LoadFromLocalAsync(string url) + { + return Task.FromResult(File.Exists(url) ? new Bitmap(url) : null); + } + + /// + /// Receives image bytes from an internal source (for example, from the disk). + /// This data will be NOT cached globally (because it is assumed that it is already in internal source us and does not + /// require global caching) + /// + /// Target url + /// Bitmap + protected virtual Task LoadFromInternalAsync(string url) + { + try + { + var uri = url.StartsWith("/") + ? new Uri(url, UriKind.Relative) + : new Uri(url, UriKind.RelativeOrAbsolute); + + if (uri.Scheme == Uri.UriSchemeHttp || uri.Scheme == Uri.UriSchemeHttps) + return Task.FromResult(null); + + if (uri is { IsAbsoluteUri: true, IsFile: true }) + return Task.FromResult(new Bitmap(uri.LocalPath))!; + + return Task.FromResult(new Bitmap(AssetLoader.Open(uri)))!; + } + catch (Exception e) + { + _logger?.Log(this, + "Failed to resolve image from request with uri: {RequestUri}\nException: {Exception}", url, e); + return Task.FromResult(null); + } + } + + /// + /// Receives image bytes from an external source (for example, from the Internet). + /// This data will be cached globally (if required by the current implementation) + /// + /// Target url + /// Image bytes + protected virtual async Task LoadDataFromExternalAsync(string url) + { + try + { + return await HttpClient.GetByteArrayAsync(url).ConfigureAwait(false); + } + catch (Exception e) + { + _logger?.Log(this, + "Failed to resolve image from request with uri: {RequestUri}\nException: {Exception}", url, e); + return null; + } + } + + /// + /// Attempts to load image from global cache (if it is stored before) + /// + /// Target url + /// Bitmap + protected virtual Task LoadFromGlobalCache(string url) + { + // Current implementation does not provide global caching + return Task.FromResult(null); + } + + /// + /// Attempts to load image from global cache (if it is stored before) + /// + /// Target url + /// Bytes to save + /// Bitmap + protected virtual Task SaveToGlobalCache(string url, byte[] imageBytes) + { + // Current implementation does not provide global caching + return Task.CompletedTask; + } + + ~BaseWebImageLoader() + { + Dispose(false); + } + + protected virtual void Dispose(bool disposing) + { + if (disposing && _shouldDisposeHttpClient) HttpClient.Dispose(); + } +} \ No newline at end of file diff --git a/DownKyi/CustomControl/AsyncImageLoader/Loaders/DiskCachedWebImageLoader.cs b/DownKyi/CustomControl/AsyncImageLoader/Loaders/DiskCachedWebImageLoader.cs new file mode 100644 index 0000000..871b379 --- /dev/null +++ b/DownKyi/CustomControl/AsyncImageLoader/Loaders/DiskCachedWebImageLoader.cs @@ -0,0 +1,60 @@ +using System; +using System.IO; +using System.Net.Http; +using System.Security.Cryptography; +using System.Text; +using System.Threading.Tasks; +using Avalonia.Media.Imaging; + +namespace DownKyi.CustomControl.AsyncImageLoader.Loaders; + +public class DiskCachedWebImageLoader : BaseWebImageLoader +{ + private readonly string _cacheFolder; + + public DiskCachedWebImageLoader(string cacheFolder = "Cache/Images/") + { + _cacheFolder = cacheFolder; + } + + public DiskCachedWebImageLoader(HttpClient httpClient, bool disposeHttpClient, string cacheFolder = "Cache/Images/") : base(httpClient, disposeHttpClient) + { + _cacheFolder = cacheFolder; + } + + /// + protected override Task LoadFromGlobalCache(string url) + { + var path = Path.Combine(_cacheFolder, CreateMd5(url)); + + return File.Exists(path) ? Task.FromResult(new Bitmap(path)) : Task.FromResult(null); + } + +#if NETSTANDARD2_1 + protected override async Task SaveToGlobalCache(string url, byte[] imageBytes) { + var path = Path.Combine(_cacheFolder, CreateMd5(url)); + + Directory.CreateDirectory(_cacheFolder); + await File.WriteAllBytesAsync(path, imageBytes).ConfigureAwait(false); + } +#else + protected override Task SaveToGlobalCache(string url, byte[] imageBytes) + { + var path = Path.Combine(_cacheFolder, CreateMd5(url)); + Directory.CreateDirectory(_cacheFolder); + File.WriteAllBytes(path, imageBytes); + return Task.CompletedTask; + } +#endif + + protected static string CreateMd5(string input) + { + // Use input string to calculate MD5 hash + using var md5 = MD5.Create(); + var inputBytes = Encoding.ASCII.GetBytes(input); + var hashBytes = md5.ComputeHash(inputBytes); + + // Convert the byte array to hexadecimal string + return BitConverter.ToString(hashBytes).Replace("-", ""); + } +} \ No newline at end of file diff --git a/DownKyi/CustomControl/AsyncImageLoader/Loaders/RamCachedWebImageLoader.cs b/DownKyi/CustomControl/AsyncImageLoader/Loaders/RamCachedWebImageLoader.cs new file mode 100644 index 0000000..50e3f69 --- /dev/null +++ b/DownKyi/CustomControl/AsyncImageLoader/Loaders/RamCachedWebImageLoader.cs @@ -0,0 +1,31 @@ +using System.Collections.Concurrent; +using System.Net.Http; +using System.Threading.Tasks; +using Avalonia.Media.Imaging; + +namespace DownKyi.CustomControl.AsyncImageLoader.Loaders; + +public class RamCachedWebImageLoader : BaseWebImageLoader +{ + private readonly ConcurrentDictionary> _memoryCache = new(); + + /// + public RamCachedWebImageLoader() + { + } + + /// + public RamCachedWebImageLoader(HttpClient httpClient, bool disposeHttpClient) : base(httpClient, disposeHttpClient) + { + } + + /// + public override async Task ProvideImageAsync(string url) + { + var bitmap = await _memoryCache.GetOrAdd(url, LoadAsync).ConfigureAwait(false); + // If load failed - remove from cache and return + // Next load attempt will try to load image again + if (bitmap == null) _memoryCache.TryRemove(url, out _); + return bitmap; + } +} \ No newline at end of file diff --git a/DownKyi/CustomControl/Loading.cs b/DownKyi/CustomControl/Loading.cs index 4a62c98..c5baeaf 100644 --- a/DownKyi/CustomControl/Loading.cs +++ b/DownKyi/CustomControl/Loading.cs @@ -74,8 +74,8 @@ public class Loading : TemplatedControl protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); - double maxSideLength = Math.Min(this.Width, this.Height); - double ellipseDiameter = 0.1 * maxSideLength; + var maxSideLength = Math.Min(Width, Height); + var ellipseDiameter = 0.1 * maxSideLength; if (maxSideLength <= 40) { ellipseDiameter += 1; diff --git a/DownKyi/DownKyi.csproj b/DownKyi/DownKyi.csproj index b5fd154..374ee9c 100644 --- a/DownKyi/DownKyi.csproj +++ b/DownKyi/DownKyi.csproj @@ -16,15 +16,15 @@ - - - - + + + + - - - - + + + + diff --git a/DownKyi/Models/Downloaded.cs b/DownKyi/Models/Downloaded.cs index 4c99124..b23b8d8 100644 --- a/DownKyi/Models/Downloaded.cs +++ b/DownKyi/Models/Downloaded.cs @@ -19,7 +19,7 @@ public class Downloaded // : DownloadBase { FinishedTimestamp = finishedTimestamp; - var startTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1)); // 当地时区 + var startTime = TimeZoneInfo.ConvertTimeFromUtc(new DateTime(1970, 1, 1), TimeZoneInfo.Local); // 当地时区 var dateTime = startTime.AddSeconds(finishedTimestamp); FinishedTime = dateTime.ToString("yyyy-MM-dd HH:mm:ss"); } diff --git a/DownKyi/Models/Downloading.cs b/DownKyi/Models/Downloading.cs index 2a5528b..ead353b 100644 --- a/DownKyi/Models/Downloading.cs +++ b/DownKyi/Models/Downloading.cs @@ -15,7 +15,7 @@ public class Downloading // : DownloadBase } // Aria相关 - public string Gid { get; set; } + public string? Gid { get; set; } // 下载的文件 public Dictionary DownloadFiles { get; set; } diff --git a/DownKyi/Services/AlertService.cs b/DownKyi/Services/AlertService.cs index 76e6001..4dc4bfa 100644 --- a/DownKyi/Services/AlertService.cs +++ b/DownKyi/Services/AlertService.cs @@ -13,7 +13,7 @@ public class AlertService public AlertService(IDialogService? dialogService) { - this._dialogService = dialogService; + _dialogService = dialogService; } /// diff --git a/DownKyi/Services/BangumiInfoService.cs b/DownKyi/Services/BangumiInfoService.cs index cf4ff4c..511ddca 100644 --- a/DownKyi/Services/BangumiInfoService.cs +++ b/DownKyi/Services/BangumiInfoService.cs @@ -135,7 +135,7 @@ public class BangumiInfoService : IInfoService // 文件命名中的时间格式 var timeFormat = SettingsManager.GetInstance().GetFileNamePartTimeFormat(); // 视频发布时间 - var startTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1)); // 当地时区 + var startTime = TimeZoneInfo.ConvertTimeFromUtc(new DateTime(1970, 1, 1), TimeZoneInfo.Local); // 当地时区 var dateTime = startTime.AddSeconds(episode.PubTime); page.PublishTime = dateTime.ToString(timeFormat); @@ -228,7 +228,7 @@ public class BangumiInfoService : IInfoService // 文件命名中的时间格式 var timeFormat = SettingsManager.GetInstance().GetFileNamePartTimeFormat(); // 视频发布时间 - var startTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1)); // 当地时区 + var startTime = TimeZoneInfo.ConvertTimeFromUtc(new DateTime(1970, 1, 1), TimeZoneInfo.Local); // 当地时区 var dateTime = startTime.AddSeconds(episode.PubTime); page.PublishTime = dateTime.ToString(timeFormat); @@ -271,25 +271,17 @@ public class BangumiInfoService : IInfoService // 查询、保存封面 // 将SeasonId保存到avid字段中 // 每集封面的cid保存到cid字段,EpisodeId保存到bvid字段中 - var storageCover = new StorageCover(); var coverUrl = _bangumiSeason.Cover; - var cover = storageCover.GetCover(_bangumiSeason.SeasonId, "bangumi", -1, coverUrl); // 获取用户头像 string upName; - string? header; if (_bangumiSeason.UpInfo != null) { upName = _bangumiSeason.UpInfo.Name; - - var storageHeader = new StorageHeader(); - header = storageHeader.GetHeader(_bangumiSeason.UpInfo.Mid, _bangumiSeason.UpInfo.Name, - _bangumiSeason.UpInfo.Avatar); } else { upName = ""; - header = null; } // 为videoInfoView赋值 @@ -298,7 +290,6 @@ public class BangumiInfoService : IInfoService { videoInfoView.CoverUrl = coverUrl; - videoInfoView.Cover = cover == null ? null : ImageHelper.LoadFromResource(new Uri(cover)); videoInfoView.Title = _bangumiSeason.Title; // 分区id @@ -316,17 +307,8 @@ public class BangumiInfoService : IInfoService videoInfoView.Description = _bangumiSeason.Evaluate; videoInfoView.UpName = upName; - if (header != null) - { - var storageHeader = new StorageHeader(); - videoInfoView.UpHeader = storageHeader.GetHeaderThumbnail(header, 48, 48); - - videoInfoView.UpperMid = _bangumiSeason.UpInfo.Mid; - } - else - { - videoInfoView.UpHeader = null; - } + videoInfoView.UpHeader = _bangumiSeason.UpInfo.Avatar; + videoInfoView.UpperMid = _bangumiSeason.UpInfo.Mid; }); return videoInfoView; diff --git a/DownKyi/Services/CheeseInfoService.cs b/DownKyi/Services/CheeseInfoService.cs index a20bed7..5a748b7 100644 --- a/DownKyi/Services/CheeseInfoService.cs +++ b/DownKyi/Services/CheeseInfoService.cs @@ -103,7 +103,7 @@ public class CheeseInfoService : IInfoService // 文件命名中的时间格式 var timeFormat = SettingsManager.GetInstance().GetFileNamePartTimeFormat(); // 视频发布时间 - var startTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1)); // 当地时区 + var startTime = TimeZoneInfo.ConvertTimeFromUtc(new DateTime(1970, 1, 1), TimeZoneInfo.Local); // 当地时区 var dateTime = startTime.AddSeconds(episode.ReleaseDate); page.PublishTime = dateTime.ToString(timeFormat); @@ -146,23 +146,17 @@ public class CheeseInfoService : IInfoService // 查询、保存封面 // 将SeasonId保存到avid字段中 // 每集封面的cid保存到cid字段,EpisodeId保存到bvid字段中 - var storageCover = new StorageCover(); var coverUrl = _cheeseView.Cover; - var cover = storageCover.GetCover(_cheeseView.SeasonId, "cheese", -1, coverUrl); // 获取用户头像 string upName; - string header; if (_cheeseView.UpInfo != null) { upName = _cheeseView.UpInfo.Name; - var storageHeader = new StorageHeader(); - header = storageHeader.GetHeader(_cheeseView.UpInfo.Mid, _cheeseView.UpInfo.Name, _cheeseView.UpInfo.Avatar); } else { upName = ""; - header = null; } // 为videoInfoView赋值 @@ -171,7 +165,6 @@ public class CheeseInfoService : IInfoService { videoInfoView.CoverUrl = coverUrl; - videoInfoView.Cover = cover == null ? null : ImageHelper.LoadFromResource(new Uri(cover)); videoInfoView.Title = _cheeseView.Title; // 分区id @@ -191,17 +184,8 @@ public class CheeseInfoService : IInfoService videoInfoView.Description = _cheeseView.Subtitle; videoInfoView.UpName = upName; - if (header != null) - { - var storageHeader = new StorageHeader(); - videoInfoView.UpHeader = storageHeader.GetHeaderThumbnail(header, 48, 48); - - videoInfoView.UpperMid = _cheeseView.UpInfo.Mid; - } - else - { - videoInfoView.UpHeader = null; - } + videoInfoView.UpHeader = _cheeseView.UpInfo.Avatar; + videoInfoView.UpperMid = _cheeseView.UpInfo.Mid; }); return videoInfoView; diff --git a/DownKyi/Services/Download/AddToDownloadService.cs b/DownKyi/Services/Download/AddToDownloadService.cs index 5e32782..84855dd 100644 --- a/DownKyi/Services/Download/AddToDownloadService.cs +++ b/DownKyi/Services/Download/AddToDownloadService.cs @@ -30,7 +30,7 @@ public class AddToDownloadService { private readonly string Tag = "AddToDownloadService"; private IInfoService _videoInfoService; - private VideoInfoView _videoInfoView; + private VideoInfoView? _videoInfoView; private List? _videoSections; // 下载内容 @@ -48,13 +48,13 @@ public class AddToDownloadService { switch (streamType) { - case PlayStreamType.VIDEO: + case PlayStreamType.Video: _videoInfoService = new VideoInfoService(null); break; - case PlayStreamType.BANGUMI: + case PlayStreamType.Bangumi: _videoInfoService = new BangumiInfoService(null); break; - case PlayStreamType.CHEESE: + case PlayStreamType.Cheese: _videoInfoService = new CheeseInfoService(null); break; default: @@ -71,13 +71,13 @@ public class AddToDownloadService { switch (streamType) { - case PlayStreamType.VIDEO: + case PlayStreamType.Video: _videoInfoService = new VideoInfoService(id); break; - case PlayStreamType.BANGUMI: + case PlayStreamType.Bangumi: _videoInfoService = new BangumiInfoService(id); break; - case PlayStreamType.CHEESE: + case PlayStreamType.Cheese: _videoInfoService = new CheeseInfoService(id); break; default: @@ -157,13 +157,14 @@ public class AddToDownloadService /// 选择文件夹和下载项 /// /// - public async Task SetDirectory(IDialogService dialogService) + public async Task SetDirectory(IDialogService? dialogService) { + if (dialogService == null) return null; // 选择的下载文件夹 var directory = string.Empty; // 是否使用默认下载目录 - if (SettingsManager.GetInstance().IsUseSaveVideoRootPath() == AllowStatus.YES) + if (SettingsManager.GetInstance().GetIsUseSaveVideoRootPath() == AllowStatus.Yes) { // 下载内容 var videoContent = SettingsManager.GetInstance().GetVideoContent(); @@ -232,8 +233,7 @@ public class AddToDownloadService /// 下载路径 /// 是否下载所有,包括未选中项 /// 添加的数量 - public async Task AddToDownload(IEventAggregator eventAggregator, IDialogService dialogService, - string? directory, bool isAll = false) + public async Task AddToDownload(IEventAggregator eventAggregator, IDialogService? dialogService, string? directory, bool isAll = false) { if (string.IsNullOrEmpty(directory)) { @@ -319,8 +319,7 @@ public class AddToDownloadService continue; } - if (item.DownloadBase.Cid == page.Cid && item.Resolution.Id == page.VideoQuality.Quality && - item.AudioCodec.Name == page.AudioQualityFormat && + if (item.DownloadBase.Cid == page.Cid && item.Resolution.Id == page.VideoQuality.Quality && item.AudioCodec.Name == page.AudioQualityFormat && item.VideoCodecName == page.VideoQuality.SelectedVideoCodec) { // eventAggregator.GetEvent().Publish($"{page.Name}{DictionaryResource.GetString("TipAlreadyToAddDownloaded")}"); @@ -338,8 +337,7 @@ public class AddToDownloadService { "message", $"{item.Name}已下载,是否重新下载" }, }; - await dialogService.ShowDialogAsync(ViewAlreadyDownloadedDialogViewModel.Tag, param, - buttonResult => { result = buttonResult.Result; }); + await dialogService.ShowDialogAsync(ViewAlreadyDownloadedDialogViewModel.Tag, param, buttonResult => { result = buttonResult.Result; }); }); if (result == ButtonResult.OK) @@ -377,7 +375,7 @@ public class AddToDownloadService // 视频分区 var zoneId = -1; var zoneList = VideoZone.Instance().GetZones(); - var zone = zoneList.Find(it => it.Id == _videoInfoView.TypeId); + var zone = zoneList.Find(it => it.Id == _videoInfoView?.TypeId); if (zone != null) { if (zone.ParentId == 0) @@ -426,10 +424,10 @@ public class AddToDownloadService var orderFormat = SettingsManager.GetInstance().GetOrderFormat(); switch (orderFormat) { - case OrderFormat.NATURAL: + case OrderFormat.Natural: fileName.SetOrder(page.Order); break; - case OrderFormat.LEADING_ZEROS: + case OrderFormat.LeadingZeros: fileName.SetOrder(page.Order, section.VideoPages.Count); break; } @@ -466,14 +464,14 @@ public class AddToDownloadService switch (_videoInfoView.TypeId) { case -10: - playStreamType = PlayStreamType.CHEESE; + playStreamType = PlayStreamType.Cheese; break; case 13: case 23: case 177: case 167: case 11: - playStreamType = PlayStreamType.BANGUMI; + playStreamType = PlayStreamType.Bangumi; break; case 1: case 3: @@ -492,7 +490,7 @@ public class AddToDownloadService case 5: case 181: default: - playStreamType = PlayStreamType.VIDEO; + playStreamType = PlayStreamType.Video; break; } @@ -516,8 +514,7 @@ public class AddToDownloadService Name = page.Name, Duration = page.Duration, VideoCodecName = page.VideoQuality.SelectedVideoCodec, - Resolution = new Quality - { Name = page.VideoQuality.QualityFormat, Id = page.VideoQuality.Quality }, + Resolution = new Quality { Name = page.VideoQuality.QualityFormat, Id = page.VideoQuality.Quality }, AudioCodec = Constant.GetAudioQualities().FirstOrDefault(t => { return t.Name == page.AudioQualityFormat; }), Page = page.Page }; diff --git a/DownKyi/Services/Download/AriaDownloadService.cs b/DownKyi/Services/Download/AriaDownloadService.cs index c9ac159..67211e3 100644 --- a/DownKyi/Services/Download/AriaDownloadService.cs +++ b/DownKyi/Services/Download/AriaDownloadService.cs @@ -26,7 +26,7 @@ public class AriaDownloadService : DownloadService, IDownloadService public AriaDownloadService( ObservableCollection downloadingList, ObservableCollection downloadedList, - IDialogService dialogService) : + IDialogService? dialogService) : base(downloadingList, downloadedList, dialogService) { Tag = "AriaDownloadService"; @@ -64,7 +64,7 @@ public class AriaDownloadService : DownloadService, IDownloadService /// /// /// - private string DownloadVideo(DownloadingItem downloading, PlayUrlDashVideo downloadVideo) + private string DownloadVideo(DownloadingItem downloading, PlayUrlDashVideo? downloadVideo) { // 如果为空,说明没有匹配到可下载的音频视频 if (downloadVideo == null) @@ -130,8 +130,8 @@ public class AriaDownloadService : DownloadService, IDownloadService } // 启用https - var useSSL = SettingsManager.GetInstance().UseSSL(); - if (useSSL == AllowStatus.YES) + var useSSL = SettingsManager.GetInstance().GetUseSsl(); + if (useSSL == AllowStatus.Yes) { for (var i = 0; i < urls.Count; i++) { @@ -359,7 +359,7 @@ public class AriaDownloadService : DownloadService, IDownloadService // 显示错误信息 if (errorMessage != null && errorMessage.Contains("ERROR")) { - var alertService = new AlertService(dialogService); + var alertService = new AlertService(DialogService); var result = await alertService.ShowMessage(SystemIcon.Instance().Error, $"Aria2 {DictionaryResource.GetString("Error")}", errorMessage, @@ -440,7 +440,7 @@ public class AriaDownloadService : DownloadService, IDownloadService }; // 如果设置了代理,则增加HttpProxy - if (SettingsManager.GetInstance().IsAriaHttpProxy() == AllowStatus.YES) + if (SettingsManager.GetInstance().GetIsAriaHttpProxy() == AllowStatus.Yes) { option.HttpProxy = $"http://{SettingsManager.GetInstance().GetAriaHttpProxy()}:{SettingsManager.GetInstance().GetAriaHttpProxyListenPort()}"; @@ -485,7 +485,7 @@ public class AriaDownloadService : DownloadService, IDownloadService private void AriaTellStatus(long totalLength, long completedLength, long speed, string gid) { // 当前的下载视频 - DownloadingItem video = null; + DownloadingItem? video = null; try { video = downloadingList.FirstOrDefault(it => it.Downloading.Gid == gid); diff --git a/DownKyi/Services/Download/BuiltinDownloadService.cs b/DownKyi/Services/Download/BuiltinDownloadService.cs index c4f5840..c748790 100644 --- a/DownKyi/Services/Download/BuiltinDownloadService.cs +++ b/DownKyi/Services/Download/BuiltinDownloadService.cs @@ -23,7 +23,7 @@ public class BuiltinDownloadService : DownloadService, IDownloadService { public BuiltinDownloadService(ObservableCollection downloadingList, ObservableCollection downloadedList, - IDialogService dialogService + IDialogService? dialogService ) : base(downloadingList, downloadedList, dialogService) { Tag = "BuiltinDownloadService"; @@ -61,7 +61,7 @@ public class BuiltinDownloadService : DownloadService, IDownloadService /// /// /// - private string DownloadVideo(DownloadingItem downloading, PlayUrlDashVideo downloadVideo) + private string DownloadVideo(DownloadingItem downloading, PlayUrlDashVideo? downloadVideo) { // 如果为空,说明没有匹配到可下载的音频视频 if (downloadVideo == null) @@ -127,8 +127,8 @@ public class BuiltinDownloadService : DownloadService, IDownloadService } // 启用https - var useSsl = SettingsManager.GetInstance().UseSSL(); - if (useSsl == AllowStatus.YES) + var useSsl = SettingsManager.GetInstance().GetUseSsl(); + if (useSsl == AllowStatus.Yes) { for (var i = 0; i < urls.Count; i++) { @@ -307,7 +307,7 @@ public class BuiltinDownloadService : DownloadService, IDownloadService Referer = "https://www.bilibili.com", }; - if (SettingsManager.GetInstance().IsHttpProxy() == AllowStatus.YES) + if (SettingsManager.GetInstance().GetIsHttpProxy() == AllowStatus.Yes) { requestConfiguration.Proxy = new WebProxy(SettingsManager.GetInstance().GetHttpProxy(), SettingsManager.GetInstance().GetHttpProxyListenPort()); @@ -316,7 +316,8 @@ public class BuiltinDownloadService : DownloadService, IDownloadService var downloadOpt = new DownloadConfiguration { ChunkCount = SettingsManager.GetInstance().GetSplit(), - RequestConfiguration = requestConfiguration + RequestConfiguration = requestConfiguration, + ParallelDownload = true }; foreach (var url in urls) { diff --git a/DownKyi/Services/Download/CustomAriaDownloadService.cs b/DownKyi/Services/Download/CustomAriaDownloadService.cs index f99390f..97a50f1 100644 --- a/DownKyi/Services/Download/CustomAriaDownloadService.cs +++ b/DownKyi/Services/Download/CustomAriaDownloadService.cs @@ -26,7 +26,7 @@ public class CustomAriaDownloadService : DownloadService, IDownloadService { public CustomAriaDownloadService(ObservableCollection downloadingList, ObservableCollection downloadedList, - IDialogService dialogService + IDialogService? dialogService ) : base(downloadingList, downloadedList, dialogService) { Tag = "AriaDownloadService"; @@ -41,7 +41,7 @@ public class CustomAriaDownloadService : DownloadService, IDownloadService /// public override string DownloadAudio(DownloadingItem downloading) { - PlayUrlDashVideo downloadAudio = BaseDownloadAudio(downloading); + var downloadAudio = BaseDownloadAudio(downloading); return DownloadVideo(downloading, downloadAudio); } @@ -53,7 +53,7 @@ public class CustomAriaDownloadService : DownloadService, IDownloadService /// public override string DownloadVideo(DownloadingItem downloading) { - PlayUrlDashVideo downloadVideo = BaseDownloadVideo(downloading); + var downloadVideo = BaseDownloadVideo(downloading); return DownloadVideo(downloading, downloadVideo); } @@ -64,7 +64,7 @@ public class CustomAriaDownloadService : DownloadService, IDownloadService /// /// /// - private string DownloadVideo(DownloadingItem downloading, PlayUrlDashVideo downloadVideo) + private string DownloadVideo(DownloadingItem downloading, PlayUrlDashVideo? downloadVideo) { // 如果为空,说明没有匹配到可下载的音频视频 if (downloadVideo == null) @@ -130,8 +130,8 @@ public class CustomAriaDownloadService : DownloadService, IDownloadService } // 启用https - AllowStatus useSSL = SettingsManager.GetInstance().UseSSL(); - if (useSSL == AllowStatus.YES) + AllowStatus useSSL = SettingsManager.GetInstance().GetUseSsl(); + if (useSSL == AllowStatus.Yes) { for (int i = 0; i < urls.Count; i++) { diff --git a/DownKyi/Services/Download/DownloadService.cs b/DownKyi/Services/Download/DownloadService.cs index f9b1341..857b41f 100644 --- a/DownKyi/Services/Download/DownloadService.cs +++ b/DownKyi/Services/Download/DownloadService.cs @@ -28,7 +28,7 @@ public abstract class DownloadService protected string Tag = "DownloadService"; // protected TaskbarIcon _notifyIcon; - protected IDialogService dialogService; + protected readonly IDialogService? DialogService; protected ObservableCollection downloadingList; protected ObservableCollection downloadedList; @@ -43,16 +43,18 @@ public abstract class DownloadService /// /// 初始化 /// - /// + /// + /// + /// /// - public DownloadService(ObservableCollection downloadingList, ObservableCollection downloadedList, IDialogService dialogService) + public DownloadService(ObservableCollection downloadingList, ObservableCollection downloadedList, IDialogService? dialogService) { this.downloadingList = downloadingList; this.downloadedList = downloadedList; - this.dialogService = dialogService; + DialogService = dialogService; } - protected PlayUrlDashVideo BaseDownloadAudio(DownloadingItem downloading) + protected PlayUrlDashVideo? BaseDownloadAudio(DownloadingItem downloading) { // 更新状态显示 downloading.DownloadStatusTitle = DictionaryResource.GetString("WhileDownloading"); @@ -80,7 +82,7 @@ public abstract class DownloadService } // 根据音频id匹配 - PlayUrlDashVideo downloadAudio = null; + PlayUrlDashVideo? downloadAudio = null; foreach (var audio in downloading.PlayUrl.Dash.Audio) { if (audio.Id == downloading.AudioCodec.Id) @@ -112,7 +114,7 @@ public abstract class DownloadService return downloadAudio; } - protected PlayUrlDashVideo BaseDownloadVideo(DownloadingItem downloading) + protected PlayUrlDashVideo? BaseDownloadVideo(DownloadingItem downloading) { // 更新状态显示 downloading.DownloadStatusTitle = DictionaryResource.GetString("WhileDownloading"); @@ -140,11 +142,11 @@ public abstract class DownloadService } // 根据视频编码匹配 - PlayUrlDashVideo downloadVideo = null; + PlayUrlDashVideo? downloadVideo = null; foreach (var video in downloading.PlayUrl.Dash.Video) { - Quality codecs = Constant.GetCodecIds().FirstOrDefault(t => t.Id == video.CodecId); - if (video.Id == downloading.Resolution.Id && codecs.Name == downloading.VideoCodecName) + var codecs = Constant.GetCodecIds().FirstOrDefault(t => t.Id == video.CodecId); + if (video.Id == downloading.Resolution.Id && codecs?.Name == downloading.VideoCodecName) { downloadVideo = video; break; @@ -164,25 +166,14 @@ public abstract class DownloadService // 下载速度 downloading.SpeedDisplay = string.Empty; - // 查询、保存封面 - var storageCover = new StorageCover(); - var cover = storageCover.GetCover(downloading.DownloadBase.Avid, downloading.DownloadBase.Bvid, downloading.DownloadBase.Cid, coverUrl); - if (cover == null) - { - return null; - } - // 复制图片到指定位置 try { - File.Copy(cover, fileName, true); + if (coverUrl == null) return null; + StorageUtils.DownloadImage(coverUrl, fileName); // 记录本次下载的文件 - if (!downloading.Downloading.DownloadFiles.ContainsKey(coverUrl)) - { - downloading.Downloading.DownloadFiles.Add(coverUrl, fileName); - } - + downloading.Downloading.DownloadFiles.TryAdd(coverUrl, fileName); return fileName; } catch (Exception e) @@ -242,9 +233,9 @@ public abstract class DownloadService }; Core.Danmaku2Ass.Bilibili.GetInstance() - .SetTopFilter(SettingsManager.GetInstance().GetDanmakuTopFilter() == AllowStatus.YES) - .SetBottomFilter(SettingsManager.GetInstance().GetDanmakuBottomFilter() == AllowStatus.YES) - .SetScrollFilter(SettingsManager.GetInstance().GetDanmakuScrollFilter() == AllowStatus.YES) + .SetTopFilter(SettingsManager.GetInstance().GetDanmakuTopFilter() == AllowStatus.Yes) + .SetBottomFilter(SettingsManager.GetInstance().GetDanmakuBottomFilter() == AllowStatus.Yes) + .SetScrollFilter(SettingsManager.GetInstance().GetDanmakuScrollFilter() == AllowStatus.Yes) .Create(downloading.DownloadBase.Avid, downloading.DownloadBase.Cid, subtitleConfig, assFile); return assFile; @@ -262,8 +253,7 @@ public abstract class DownloadService var srtFiles = new List(); - var subRipTexts = VideoStream.GetSubtitle(downloading.DownloadBase.Avid, downloading.DownloadBase.Bvid, - downloading.DownloadBase.Cid); + var subRipTexts = VideoStream.GetSubtitle(downloading.DownloadBase.Avid, downloading.DownloadBase.Bvid, downloading.DownloadBase.Cid); if (subRipTexts == null) { return null; @@ -277,10 +267,7 @@ public abstract class DownloadService File.WriteAllText(srtFile, subRip.SrtString); // 记录本次下载的文件 - if (!downloading.Downloading.DownloadFiles.ContainsKey("subtitle")) - { - downloading.Downloading.DownloadFiles.Add("subtitle", srtFile); - } + downloading.Downloading.DownloadFiles.TryAdd("subtitle", srtFile); srtFiles.Add(srtFile); } @@ -312,7 +299,7 @@ public abstract class DownloadService var finalFile = $"{downloading.DownloadBase.FilePath}.mp4"; if (videoUid == null) { - finalFile = SettingsManager.GetInstance().IsTranscodingAacToMp3() == AllowStatus.YES + finalFile = SettingsManager.GetInstance().GetIsTranscodingAacToMp3() == AllowStatus.Yes ? $"{downloading.DownloadBase.FilePath}.mp3" : downloading.AudioCodec.Id == 30251 ? $"{downloading.DownloadBase.FilePath}.flac" @@ -361,7 +348,7 @@ public abstract class DownloadService // 解析 switch (downloading.Downloading.PlayStreamType) { - case PlayStreamType.VIDEO: + case PlayStreamType.Video: downloading.PlayUrl = SettingsManager.GetInstance().GetVideoParseType() switch { 0 => VideoStream.GetVideoPlayUrl(downloading.DownloadBase.Avid, downloading.DownloadBase.Bvid, downloading.DownloadBase.Cid), @@ -370,11 +357,11 @@ public abstract class DownloadService _ => null }; break; - case PlayStreamType.BANGUMI: + case PlayStreamType.Bangumi: downloading.PlayUrl = VideoStream.GetBangumiPlayUrl(downloading.DownloadBase.Avid, downloading.DownloadBase.Bvid, downloading.DownloadBase.Cid); break; - case PlayStreamType.CHEESE: + case PlayStreamType.Cheese: downloading.PlayUrl = VideoStream.GetCheesePlayUrl(downloading.DownloadBase.Avid, downloading.DownloadBase.Bvid, downloading.DownloadBase.Cid, downloading.DownloadBase.EpisodeId); @@ -416,14 +403,11 @@ public abstract class DownloadService } // 开始下载 - if (downloading.Downloading.DownloadStatus == DownloadStatus.NotStarted || - downloading.Downloading.DownloadStatus == DownloadStatus.WaitForDownload) - { - //这里需要立刻设置状态,否则如果SingleDownload没有及时执行,会重复创建任务 - downloading.Downloading.DownloadStatus = DownloadStatus.Downloading; - downloadingTasks.Add(SingleDownload(downloading)); - downloadingCount++; - } + if (downloading.Downloading.DownloadStatus is not (DownloadStatus.NotStarted or DownloadStatus.WaitForDownload)) continue; + //这里需要立刻设置状态,否则如果SingleDownload没有及时执行,会重复创建任务 + downloading.Downloading.DownloadStatus = DownloadStatus.Downloading; + downloadingTasks.Add(SingleDownload(downloading)); + downloadingCount++; } } catch (InvalidOperationException e) @@ -490,7 +474,7 @@ public abstract class DownloadService Console.PrintLine(Tag, e.ToString()); LogManager.Debug(Tag, e.Message); - var alertService = new AlertService(dialogService); + var alertService = new AlertService(DialogService); var result = await alertService.ShowError($"{path}{DictionaryResource.GetString("DirectoryError")}"); return; @@ -517,7 +501,7 @@ public abstract class DownloadService if (downloading.DownloadBase.NeedDownloadContent["downloadAudio"]) { //audioUid = DownloadAudio(downloading); - for (int i = 0; i < retry; i++) + for (var i = 0; i < retry; i++) { audioUid = DownloadAudio(downloading); if (audioUid != null && audioUid != nullMark) @@ -620,30 +604,16 @@ public abstract class DownloadService { // 只有下载音频不下载视频时才输出aac // 只要下载视频就输出mp4 - if (File.Exists(outputMedia)) - { - // 成功 - isMediaSuccess = true; - } - else - { - isMediaSuccess = false; - } + // 成功 + isMediaSuccess = File.Exists(outputMedia); } // 检测弹幕是否下载成功 var isDanmakuSuccess = true; if (downloading.DownloadBase.NeedDownloadContent["downloadDanmaku"]) { - if (File.Exists(outputDanmaku)) - { - // 成功 - isDanmakuSuccess = true; - } - else - { - isDanmakuSuccess = false; - } + // 成功 + isDanmakuSuccess = File.Exists(outputDanmaku); } // 检测字幕是否下载成功 @@ -656,7 +626,7 @@ public abstract class DownloadService } else { - foreach (string subtitle in outputSubtitles) + foreach (var subtitle in outputSubtitles) { if (!File.Exists(subtitle)) { @@ -744,7 +714,7 @@ public abstract class DownloadService /// /// /// - protected string GetImageExtension(string coverUrl) + protected string GetImageExtension(string? coverUrl) { if (coverUrl == null) { @@ -753,7 +723,7 @@ public abstract class DownloadService // 图片的扩展名 var temp = coverUrl.Split('.'); - var fileExtension = temp[temp.Length - 1]; + var fileExtension = temp[^1]; return fileExtension; } @@ -765,20 +735,20 @@ public abstract class DownloadService var operation = SettingsManager.GetInstance().GetAfterDownloadOperation(); switch (operation) { - case AfterDownloadOperation.NONE: + case AfterDownloadOperation.None: // 没有操作 break; - case AfterDownloadOperation.OPEN_FOLDER: + case AfterDownloadOperation.OpenFolder: // 打开文件夹 break; - case AfterDownloadOperation.CLOSE_APP: + case AfterDownloadOperation.CloseApp: // 关闭程序 App.PropertyChangeAsync(() => { // System.Windows.Application.Current.Shutdown(); }); break; - case AfterDownloadOperation.CLOSE_SYSTEM: + case AfterDownloadOperation.CloseSystem: // 关机 // Process.Start("shutdown.exe", "-s"); break; diff --git a/DownKyi/Services/Download/DownloadStorageService.cs b/DownKyi/Services/Download/DownloadStorageService.cs index 77373ca..a6f619c 100644 --- a/DownKyi/Services/Download/DownloadStorageService.cs +++ b/DownKyi/Services/Download/DownloadStorageService.cs @@ -9,11 +9,11 @@ public class DownloadStorageService { ~DownloadStorageService() { - DownloadingDb downloadingDb = new DownloadingDb(); + var downloadingDb = new DownloadingDb(); downloadingDb.Close(); - DownloadedDb downloadedDb = new DownloadedDb(); + var downloadedDb = new DownloadedDb(); downloadedDb.Close(); - DownloadBaseDb downloadBaseDb = new DownloadBaseDb(); + var downloadBaseDb = new DownloadBaseDb(); downloadBaseDb.Close(); } @@ -23,17 +23,17 @@ public class DownloadStorageService /// 添加下载中数据 /// /// - public void AddDownloading(DownloadingItem downloadingItem) + public void AddDownloading(DownloadingItem? downloadingItem) { - if (downloadingItem == null || downloadingItem.DownloadBase == null) + if (downloadingItem?.DownloadBase == null) { return; } AddDownloadBase(downloadingItem.DownloadBase); - DownloadingDb downloadingDb = new DownloadingDb(); - object obj = downloadingDb.QueryById(downloadingItem.DownloadBase.Uuid); + var downloadingDb = new DownloadingDb(); + var obj = downloadingDb.QueryById(downloadingItem.DownloadBase.Uuid); if (obj == null) { downloadingDb.Insert(downloadingItem.DownloadBase.Uuid, downloadingItem.Downloading); @@ -45,16 +45,16 @@ public class DownloadStorageService /// 删除下载中数据 /// /// - public void RemoveDownloading(DownloadingItem downloadingItem) + public void RemoveDownloading(DownloadingItem? downloadingItem) { - if (downloadingItem == null || downloadingItem.DownloadBase == null) + if (downloadingItem?.DownloadBase == null) { return; } RemoveDownloadBase(downloadingItem.DownloadBase.Uuid); - DownloadingDb downloadingDb = new DownloadingDb(); + var downloadingDb = new DownloadingDb(); downloadingDb.Delete(downloadingItem.DownloadBase.Uuid); //downloadingDb.Close(); } @@ -66,29 +66,27 @@ public class DownloadStorageService public List GetDownloading() { // 从数据库获取数据 - DownloadingDb downloadingDb = new DownloadingDb(); - Dictionary dic = downloadingDb.QueryAll(); + var downloadingDb = new DownloadingDb(); + var dic = downloadingDb.QueryAll(); //downloadingDb.Close(); // 遍历 - List list = new List(); - foreach (KeyValuePair item in dic) + var list = new List(); + foreach (var item in dic) { - if (item.Value is Downloading downloading) + if (item.Value is not Downloading downloading) continue; + var downloadingItem = new DownloadingItem { - DownloadingItem downloadingItem = new DownloadingItem - { - DownloadBase = GetDownloadBase(item.Key), - Downloading = downloading - }; + DownloadBase = GetDownloadBase(item.Key), + Downloading = downloading + }; - if (downloadingItem.DownloadBase == null) - { - continue; - } - - list.Add(downloadingItem); + if (downloadingItem.DownloadBase == null) + { + continue; } + + list.Add(downloadingItem); } return list; @@ -98,16 +96,16 @@ public class DownloadStorageService /// 修改下载中数据 /// /// - public void UpdateDownloading(DownloadingItem downloadingItem) + public void UpdateDownloading(DownloadingItem? downloadingItem) { - if (downloadingItem == null || downloadingItem.DownloadBase == null) + if (downloadingItem?.DownloadBase == null) { return; } UpdateDownloadBase(downloadingItem.DownloadBase); - DownloadingDb downloadingDb = new DownloadingDb(); + var downloadingDb = new DownloadingDb(); downloadingDb.Update(downloadingItem.DownloadBase.Uuid, downloadingItem.Downloading); //downloadingDb.Close(); } @@ -120,17 +118,17 @@ public class DownloadStorageService /// 添加下载完成数据 /// /// - public void AddDownloaded(DownloadedItem downloadedItem) + public void AddDownloaded(DownloadedItem? downloadedItem) { - if (downloadedItem == null || downloadedItem.DownloadBase == null) + if (downloadedItem?.DownloadBase == null) { return; } AddDownloadBase(downloadedItem.DownloadBase); - DownloadedDb downloadedDb = new DownloadedDb(); - object obj = downloadedDb.QueryById(downloadedItem.DownloadBase.Uuid); + var downloadedDb = new DownloadedDb(); + var obj = downloadedDb.QueryById(downloadedItem.DownloadBase.Uuid); if (obj == null) { downloadedDb.Insert(downloadedItem.DownloadBase.Uuid, downloadedItem.Downloaded); @@ -142,16 +140,16 @@ public class DownloadStorageService /// 删除下载完成数据 /// /// - public void RemoveDownloaded(DownloadedItem downloadedItem) + public void RemoveDownloaded(DownloadedItem? downloadedItem) { - if (downloadedItem == null || downloadedItem.DownloadBase == null) + if (downloadedItem?.DownloadBase == null) { return; } RemoveDownloadBase(downloadedItem.DownloadBase.Uuid); - DownloadedDb downloadedDb = new DownloadedDb(); + var downloadedDb = new DownloadedDb(); downloadedDb.Delete(downloadedItem.DownloadBase.Uuid); //downloadedDb.Close(); } @@ -163,17 +161,17 @@ public class DownloadStorageService public List GetDownloaded() { // 从数据库获取数据 - DownloadedDb downloadedDb = new DownloadedDb(); - Dictionary dic = downloadedDb.QueryAll(); + var downloadedDb = new DownloadedDb(); + var dic = downloadedDb.QueryAll(); //downloadedDb.Close(); // 遍历 - List list = new List(); - foreach (KeyValuePair item in dic) + var list = new List(); + foreach (var item in dic) { if (item.Value is Downloaded downloaded) { - DownloadedItem downloadedItem = new DownloadedItem + var downloadedItem = new DownloadedItem { DownloadBase = GetDownloadBase(item.Key), Downloaded = downloaded @@ -195,16 +193,16 @@ public class DownloadStorageService /// 修改下载完成数据 /// /// - public void UpdateDownloaded(DownloadedItem downloadedItem) + public void UpdateDownloaded(DownloadedItem? downloadedItem) { - if (downloadedItem == null || downloadedItem.DownloadBase == null) + if (downloadedItem?.DownloadBase == null) { return; } UpdateDownloadBase(downloadedItem.DownloadBase); - DownloadedDb downloadedDb = new DownloadedDb(); + var downloadedDb = new DownloadedDb(); downloadedDb.Update(downloadedItem.DownloadBase.Uuid, downloadedItem.Downloaded); //downloadedDb.Close(); } @@ -217,15 +215,15 @@ public class DownloadStorageService /// 向数据库添加DownloadBase /// /// - private void AddDownloadBase(DownloadBase downloadBase) + private void AddDownloadBase(DownloadBase? downloadBase) { if (downloadBase == null) { return; } - DownloadBaseDb downloadBaseDb = new DownloadBaseDb(); - object obj = downloadBaseDb.QueryById(downloadBase.Uuid); + var downloadBaseDb = new DownloadBaseDb(); + var obj = downloadBaseDb.QueryById(downloadBase.Uuid); if (obj == null) { downloadBaseDb.Insert(downloadBase.Uuid, downloadBase); @@ -236,10 +234,10 @@ public class DownloadStorageService /// /// 从数据库删除DownloadBase /// - /// + /// private void RemoveDownloadBase(string uuid) { - DownloadBaseDb downloadBaseDb = new DownloadBaseDb(); + var downloadBaseDb = new DownloadBaseDb(); downloadBaseDb.Delete(uuid); //downloadBaseDb.Close(); } @@ -250,8 +248,8 @@ public class DownloadStorageService /// private DownloadBase GetDownloadBase(string uuid) { - DownloadBaseDb downloadBaseDb = new DownloadBaseDb(); - object obj = downloadBaseDb.QueryById(uuid); + var downloadBaseDb = new DownloadBaseDb(); + var obj = downloadBaseDb.QueryById(uuid); //downloadBaseDb.Close(); return obj is DownloadBase downloadBase ? downloadBase : null; @@ -261,14 +259,14 @@ public class DownloadStorageService /// 从数据库修改DownloadBase /// /// - private void UpdateDownloadBase(DownloadBase downloadBase) + private void UpdateDownloadBase(DownloadBase? downloadBase) { if (downloadBase == null) { return; } - DownloadBaseDb downloadBaseDb = new DownloadBaseDb(); + var downloadBaseDb = new DownloadBaseDb(); downloadBaseDb.Update(downloadBase.Uuid, downloadBase); //downloadBaseDb.Close(); } diff --git a/DownKyi/Services/FavoritesService.cs b/DownKyi/Services/FavoritesService.cs index cb713b5..b506ab7 100644 --- a/DownKyi/Services/FavoritesService.cs +++ b/DownKyi/Services/FavoritesService.cs @@ -20,7 +20,7 @@ public class FavoritesService : IFavoritesService /// /// /// - public Favorites GetFavorites(long mediaId) + public Favorites? GetFavorites(long mediaId) { var favoritesMetaInfo = FavoritesInfo.GetFavoritesInfo(mediaId); if (favoritesMetaInfo == null) @@ -29,24 +29,10 @@ public class FavoritesService : IFavoritesService } // 查询、保存封面 - var storageCover = new StorageCover(); - var coverUrl = favoritesMetaInfo.Cover; - var cover = storageCover.GetCoverThumbnail(favoritesMetaInfo.Id, "Favorites", favoritesMetaInfo.Mid, coverUrl, 300, 188); + var coverUrl = favoritesMetaInfo?.Cover; // 获取用户头像 - string upName; - string header; - if (favoritesMetaInfo.Upper != null) - { - upName = favoritesMetaInfo.Upper.Name; - var storageHeader = new StorageHeader(); - header = storageHeader.GetHeader(favoritesMetaInfo.Upper.Mid, favoritesMetaInfo.Upper.Name, favoritesMetaInfo.Upper.Face); - } - else - { - upName = ""; - header = null; - } + var upName = favoritesMetaInfo?.Upper != null ? favoritesMetaInfo.Upper.Name : ""; // 为Favorites赋值 var favorites = new Favorites(); @@ -54,10 +40,9 @@ public class FavoritesService : IFavoritesService { favorites.CoverUrl = coverUrl; - favorites.Cover = cover; favorites.Title = favoritesMetaInfo.Title; - var startTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1)); // 当地时区 + var startTime = TimeZoneInfo.ConvertTimeFromUtc(new DateTime(1970, 1, 1), TimeZoneInfo.Local); // 当地时区 var dateTime = startTime.AddSeconds(favoritesMetaInfo.Ctime); favorites.CreateTime = dateTime.ToString("yyyy-MM-dd HH:mm:ss"); @@ -69,17 +54,8 @@ public class FavoritesService : IFavoritesService favorites.MediaCount = favoritesMetaInfo.MediaCount; favorites.UpName = upName; - if (header != null) - { - var storageHeader = new StorageHeader(); - favorites.UpHeader = storageHeader.GetHeaderThumbnail(header, 48, 48); - - favorites.UpperMid = favoritesMetaInfo.Upper.Mid; - } - else - { - favorites.UpHeader = null; - } + favorites.UpHeader = favoritesMetaInfo.Upper.Face; + favorites.UpperMid = favoritesMetaInfo.Upper.Mid; }); return favorites; @@ -136,12 +112,10 @@ public class FavoritesService : IFavoritesService order++; // 查询、保存封面 - var storageCover = new StorageCover(); var coverUrl = media.Cover; - Bitmap cover = storageCover.GetCoverThumbnail(media.Id, media.Bvid, -1, coverUrl, 200, 125); // 当地时区 - DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1)); + var startTime = TimeZoneInfo.ConvertTimeFromUtc(new DateTime(1970, 1, 1), TimeZoneInfo.Local);; // 创建时间 var dateCTime = startTime.AddSeconds(media.Ctime); @@ -158,7 +132,7 @@ public class FavoritesService : IFavoritesService Avid = media.Id, Bvid = media.Bvid, Order = order, - Cover = cover, + Cover = coverUrl, Title = media.Title, PlayNumber = media.CntInfo != null ? Format.FormatNumber(media.CntInfo.Play) : "0", DanmakuNumber = media.CntInfo != null ? Format.FormatNumber(media.CntInfo.Danmaku) : "0", diff --git a/DownKyi/Services/IFavoritesService.cs b/DownKyi/Services/IFavoritesService.cs index 41c7619..50fae62 100644 --- a/DownKyi/Services/IFavoritesService.cs +++ b/DownKyi/Services/IFavoritesService.cs @@ -9,7 +9,7 @@ namespace DownKyi.Services; public interface IFavoritesService { - Favorites GetFavorites(long mediaId); + Favorites? GetFavorites(long mediaId); //void GetFavoritesMediaList(long mediaId, ObservableCollection result, IEventAggregator eventAggregator, CancellationToken cancellationToken); //void GetFavoritesMediaList(long mediaId, int pn, int ps, ObservableCollection result, IEventAggregator eventAggregator, CancellationToken cancellationToken); diff --git a/DownKyi/Services/Utils.cs b/DownKyi/Services/Utils.cs index 5de33b1..2799317 100644 --- a/DownKyi/Services/Utils.cs +++ b/DownKyi/Services/Utils.cs @@ -17,7 +17,7 @@ internal static class Utils /// /// /// - internal static void VideoPageInfo(PlayUrl playUrl, VideoPage page) + internal static void VideoPageInfo(PlayUrl? playUrl, VideoPage page) { if (playUrl == null) { diff --git a/DownKyi/Services/VideoInfoService.cs b/DownKyi/Services/VideoInfoService.cs index 0826266..4fdec0f 100644 --- a/DownKyi/Services/VideoInfoService.cs +++ b/DownKyi/Services/VideoInfoService.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using Avalonia.Media.Imaging; using Avalonia.Threading; using DownKyi.Core.BiliApi.BiliUtils; using DownKyi.Core.BiliApi.Models; @@ -46,12 +45,7 @@ public class VideoInfoService : IInfoService /// public List? GetVideoPages() { - if (_videoView == null) - { - return null; - } - - if (_videoView.Pages == null) + if (_videoView?.Pages == null) { return null; } @@ -114,10 +108,10 @@ public class VideoInfoService : IInfoService } // 文件命名中的时间格式 - string timeFormat = SettingsManager.GetInstance().GetFileNamePartTimeFormat(); + var timeFormat = SettingsManager.GetInstance().GetFileNamePartTimeFormat(); // 视频发布时间 - DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1)); // 当地时区 - DateTime dateTime = startTime.AddSeconds(_videoView.Pubdate); + var startTime = TimeZoneInfo.ConvertTimeFromUtc(new DateTime(1970, 1, 1), TimeZoneInfo.Local); // 当地时区 + var dateTime = startTime.AddSeconds(_videoView.Pubdate); videoPage.PublishTime = dateTime.ToString(timeFormat); videoPages.Add(videoPage); @@ -132,7 +126,7 @@ public class VideoInfoService : IInfoService /// public List? GetVideoSections(bool noUgc = false) { - if (_videoView == null || _videoView.UgcSeason?.Sections == null || _videoView.UgcSeason.Sections.Count == 0) + if (_videoView?.UgcSeason.Sections == null || _videoView.UgcSeason.Sections.Count == 0) { return null; } @@ -147,7 +141,7 @@ public class VideoInfoService : IInfoService } var timeFormat = SettingsManager.GetInstance().GetFileNamePartTimeFormat(); - var startTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1)); + var startTime = TimeZoneInfo.ConvertTimeFromUtc(new DateTime(1970, 1, 1), TimeZoneInfo.Local);; foreach (var section in _videoView.UgcSeason.Sections) { @@ -165,6 +159,7 @@ public class VideoInfoService : IInfoService pages.Add(GenerateVideoPage(episode, ++order, startTime, timeFormat)); } } + if (pages.Count > 0) { var videoSection = new VideoSection @@ -215,7 +210,7 @@ public class VideoInfoService : IInfoService Cid = p.Cid, EpisodeId = -1, FirstFrame = episode.Arc.Pic, - Order = order ++, + Order = order++, Name = p.Part, Duration = "N/A", Owner = _videoView.Owner, @@ -239,7 +234,7 @@ public class VideoInfoService : IInfoService Order = order, Name = episode.Title, Duration = "N/A", - Owner = _videoView.Owner ?? new VideoOwner { Name = "", Face = "", Mid = -1 }, + Owner = _videoView?.Owner ?? new VideoOwner { Name = "", Face = "", Mid = -1 }, Page = episode.Page.Page }; var dateTime = startTime.AddSeconds(episode.Arc.Ctime); @@ -275,9 +270,7 @@ public class VideoInfoService : IInfoService } // 查询、保存封面 - var storageCover = new StorageCover(); var coverUrl = _videoView.Pic; - var cover = storageCover.GetCover(_videoView.Aid, _videoView.Bvid, _videoView.Cid, coverUrl); // 分区 var videoZone = string.Empty; @@ -302,17 +295,13 @@ public class VideoInfoService : IInfoService // 获取用户头像 string upName; - string header; - if (_videoView.Owner != null) + if (_videoView?.Owner != null) { upName = _videoView.Owner.Name; - var storageHeader = new StorageHeader(); - header = storageHeader.GetHeader(_videoView.Owner.Mid, _videoView.Owner.Name, _videoView.Owner.Face); } else { upName = ""; - header = null; } // 为videoInfoView赋值 @@ -320,8 +309,6 @@ public class VideoInfoService : IInfoService App.PropertyChangeAsync(() => { videoInfoView.CoverUrl = coverUrl; - - videoInfoView.Cover = cover == null ? null : new Bitmap(cover); videoInfoView.Title = _videoView.Title; // 分区id @@ -329,7 +316,7 @@ public class VideoInfoService : IInfoService videoInfoView.VideoZone = videoZone; - var startTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1)); // 当地时区 + var startTime = TimeZoneInfo.ConvertTimeFromUtc(new DateTime(1970, 1, 1), TimeZoneInfo.Local); // 当地时区 var dateTime = startTime.AddSeconds(_videoView.Pubdate); videoInfoView.CreateTime = dateTime.ToString("yyyy-MM-dd HH:mm:ss"); @@ -341,19 +328,10 @@ public class VideoInfoService : IInfoService videoInfoView.ShareNumber = Format.FormatNumber(_videoView.Stat.Share); videoInfoView.ReplyNumber = Format.FormatNumber(_videoView.Stat.Reply); videoInfoView.Description = _videoView.Desc; + videoInfoView.UpHeader = _videoView.Owner.Face ?? ""; + videoInfoView.UpperMid = _videoView.Owner.Mid; videoInfoView.UpName = upName; - if (header != null) - { - var storageHeader = new StorageHeader(); - videoInfoView.UpHeader = storageHeader.GetHeaderThumbnail(header, 48, 48); - - videoInfoView.UpperMid = _videoView.Owner.Mid; - } - else - { - videoInfoView.UpHeader = null; - } }); return videoInfoView; diff --git a/DownKyi/ViewModels/Dialogs/ViewDownloadSetterViewModel.cs b/DownKyi/ViewModels/Dialogs/ViewDownloadSetterViewModel.cs index 09f379b..0af8843 100644 --- a/DownKyi/ViewModels/Dialogs/ViewDownloadSetterViewModel.cs +++ b/DownKyi/ViewModels/Dialogs/ViewDownloadSetterViewModel.cs @@ -16,7 +16,7 @@ namespace DownKyi.ViewModels.Dialogs; public class ViewDownloadSetterViewModel : BaseDialogViewModel { public const string Tag = "DialogDownloadSetter"; - private readonly IEventAggregator eventAggregator; + private readonly IEventAggregator _eventAggregator; // 历史文件夹的数量 private const int MaxDirectoryListCount = 20; @@ -134,7 +134,7 @@ public class ViewDownloadSetterViewModel : BaseDialogViewModel public ViewDownloadSetterViewModel(IEventAggregator eventAggregator) { - this.eventAggregator = eventAggregator; + _eventAggregator = eventAggregator; #region 属性初始化 @@ -175,7 +175,7 @@ public class ViewDownloadSetterViewModel : BaseDialogViewModel Directory = directory; // 是否使用默认下载目录 - IsDefaultDownloadDirectory = SettingsManager.GetInstance().IsUseSaveVideoRootPath() == AllowStatus.YES; + IsDefaultDownloadDirectory = SettingsManager.GetInstance().GetIsUseSaveVideoRootPath() == AllowStatus.Yes; #endregion } @@ -196,7 +196,7 @@ public class ViewDownloadSetterViewModel : BaseDialogViewModel if (directory == null) { - eventAggregator.GetEvent().Publish(DictionaryResource.GetString("WarningNullDirectory")); + _eventAggregator.GetEvent().Publish(DictionaryResource.GetString("WarningNullDirectory")); Directory = string.Empty; } else @@ -372,7 +372,7 @@ public class ViewDownloadSetterViewModel : BaseDialogViewModel } // 设此文件夹为默认下载文件夹 - SettingsManager.GetInstance().IsUseSaveVideoRootPath(IsDefaultDownloadDirectory ? AllowStatus.YES : AllowStatus.NO); + SettingsManager.GetInstance().SetIsUseSaveVideoRootPath(IsDefaultDownloadDirectory ? AllowStatus.Yes : AllowStatus.No); // 将Directory移动到第一项 // 如果直接在ComboBox中选择的就需要 diff --git a/DownKyi/ViewModels/Dialogs/ViewParsingSelectorViewModel.cs b/DownKyi/ViewModels/Dialogs/ViewParsingSelectorViewModel.cs index 342e452..2eb8701 100644 --- a/DownKyi/ViewModels/Dialogs/ViewParsingSelectorViewModel.cs +++ b/DownKyi/ViewModels/Dialogs/ViewParsingSelectorViewModel.cs @@ -29,7 +29,7 @@ public class ViewParsingSelectorViewModel : BaseDialogViewModel // 解析范围 var parseScope = SettingsManager.GetInstance().GetParseScope(); - IsParseDefault = parseScope != ParseScope.NONE; + IsParseDefault = parseScope != ParseScope.None; #endregion } @@ -46,11 +46,11 @@ public class ViewParsingSelectorViewModel : BaseDialogViewModel /// private void ExecuteParseSelectedItemCommand() { - SetParseScopeSetting(ParseScope.SELECTED_ITEM); + SetParseScopeSetting(ParseScope.SelectedItem); IDialogParameters parameters = new DialogParameters { - { "parseScope", ParseScope.SELECTED_ITEM } + { "parseScope", ParseScope.SelectedItem } }; RaiseRequestClose(new DialogResult(ButtonResult.OK, parameters)); @@ -66,11 +66,11 @@ public class ViewParsingSelectorViewModel : BaseDialogViewModel /// private void ExecuteParseCurrentSectionCommand() { - SetParseScopeSetting(ParseScope.CURRENT_SECTION); + SetParseScopeSetting(ParseScope.CurrentSection); IDialogParameters parameters = new DialogParameters { - { "parseScope", ParseScope.CURRENT_SECTION } + { "parseScope", ParseScope.CurrentSection } }; RaiseRequestClose(new DialogResult(ButtonResult.OK, parameters)); @@ -86,11 +86,11 @@ public class ViewParsingSelectorViewModel : BaseDialogViewModel /// private void ExecuteParseAllCommand() { - SetParseScopeSetting(ParseScope.ALL); + SetParseScopeSetting(ParseScope.All); IDialogParameters parameters = new DialogParameters { - { "parseScope", ParseScope.ALL } + { "parseScope", ParseScope.All } }; RaiseRequestClose(new DialogResult(ButtonResult.OK, parameters)); @@ -104,6 +104,6 @@ public class ViewParsingSelectorViewModel : BaseDialogViewModel /// private void SetParseScopeSetting(ParseScope parseScope) { - SettingsManager.GetInstance().SetParseScope(IsParseDefault ? parseScope : ParseScope.NONE); + SettingsManager.GetInstance().SetParseScope(IsParseDefault ? parseScope : ParseScope.None); } } \ No newline at end of file diff --git a/DownKyi/ViewModels/DownloadManager/DownloadedItem.cs b/DownKyi/ViewModels/DownloadManager/DownloadedItem.cs index fafd2d5..9747e82 100644 --- a/DownKyi/ViewModels/DownloadManager/DownloadedItem.cs +++ b/DownKyi/ViewModels/DownloadManager/DownloadedItem.cs @@ -17,7 +17,7 @@ namespace DownKyi.ViewModels.DownloadManager { } - public DownloadedItem(IDialogService dialogService) : base(dialogService) + public DownloadedItem(IDialogService? dialogService) : base(dialogService) { // 打开文件夹按钮 OpenFolder = ButtonIcon.Instance().Folder; @@ -93,7 +93,7 @@ namespace DownKyi.ViewModels.DownloadManager public DelegateCommand OpenFolderCommand => _openFolderCommand ??= new DelegateCommand(ExecuteOpenFolderCommand); - private static IReadOnlyDictionary FileSuffixMap = new Dictionary + private static readonly IReadOnlyDictionary FileSuffixMap = new Dictionary { { "downloadVideo", new[] { ".mp4", ".flv" } }, { "downloadAudio", new[] { ".aac", ".mp3" } }, @@ -101,6 +101,7 @@ namespace DownKyi.ViewModels.DownloadManager { "downloadDanmaku", new[] { ".ass" } }, { "downloadSubtitle", new[] { ".srt" } } }; + /// /// 打开文件夹事件 /// @@ -110,22 +111,21 @@ namespace DownKyi.ViewModels.DownloadManager { return; } + var downLoadContents = DownloadBase.NeedDownloadContent.Where(e => e.Value == true).Select(e => e.Key); var fileSuffixes = downLoadContents - .Where(content => FileSuffixMap.ContainsKey(content)) - .SelectMany(content => FileSuffixMap[content]) - .ToArray(); - if (fileSuffixes.Length > 0) + .Where(content => FileSuffixMap.ContainsKey(content)) + .SelectMany(content => FileSuffixMap[content]) + .ToArray(); + if (fileSuffixes.Length <= 0) return; + foreach (var suffix in fileSuffixes) { - foreach (var suffix in fileSuffixes) + var videoPath = $"{DownloadBase.FilePath}{suffix}"; + var fileInfo = new FileInfo(videoPath); + if (File.Exists(fileInfo.FullName) && fileInfo.DirectoryName != null) { - var videoPath = $"{DownloadBase.FilePath}{suffix}"; - var fileInfo = new FileInfo(videoPath); - if (File.Exists(fileInfo.FullName) && fileInfo.DirectoryName != null) - { - PlatformHelper.OpenFolder(fileInfo.DirectoryName); - return; - } + PlatformHelper.OpenFolder(fileInfo.DirectoryName); + return; } } // eventAggregator.GetEvent().Publish("没有找到视频文件,可能被删除或移动!"); diff --git a/DownKyi/ViewModels/DownloadManager/DownloadingItem.cs b/DownKyi/ViewModels/DownloadManager/DownloadingItem.cs index 0b6397f..afa1245 100644 --- a/DownKyi/ViewModels/DownloadManager/DownloadingItem.cs +++ b/DownKyi/ViewModels/DownloadManager/DownloadingItem.cs @@ -27,13 +27,13 @@ namespace DownKyi.ViewModels.DownloadManager } // model数据 - private Downloading downloading; + private Downloading _downloading; public Downloading Downloading { - get => downloading; + get => _downloading; set { - downloading = value; + _downloading = value; switch (value.DownloadStatus) { diff --git a/DownKyi/ViewModels/DownloadManager/ViewDownloadFinishedViewModel.cs b/DownKyi/ViewModels/DownloadManager/ViewDownloadFinishedViewModel.cs index 77ff2de..35d3367 100644 --- a/DownKyi/ViewModels/DownloadManager/ViewDownloadFinishedViewModel.cs +++ b/DownKyi/ViewModels/DownloadManager/ViewDownloadFinishedViewModel.cs @@ -127,7 +127,7 @@ namespace DownKyi.ViewModels.DownloadManager { App.PropertyChangeAsync(() => { - App.DownloadedList.Remove(item); + App.DownloadedList?.Remove(item); }); } }); diff --git a/DownKyi/ViewModels/DownloadManager/ViewDownloadingViewModel.cs b/DownKyi/ViewModels/DownloadManager/ViewDownloadingViewModel.cs index 6d3e3ce..1295836 100644 --- a/DownKyi/ViewModels/DownloadManager/ViewDownloadingViewModel.cs +++ b/DownKyi/ViewModels/DownloadManager/ViewDownloadingViewModel.cs @@ -88,8 +88,6 @@ namespace DownKyi.ViewModels.DownloadManager break; case DownloadStatus.DownloadFailed: break; - default: - break; } } } @@ -133,8 +131,6 @@ namespace DownKyi.ViewModels.DownloadManager downloading.Downloading.DownloadStatus = DownloadStatus.WaitForDownload; downloading.DownloadStatusTitle = DictionaryResource.GetString("Waiting"); break; - default: - break; } downloading.StartOrPause = ButtonIcon.Instance().Pause; @@ -167,7 +163,7 @@ namespace DownKyi.ViewModels.DownloadManager var list = DownloadingList.ToList(); foreach (var item in list) { - App.PropertyChangeAsync(() => { App.DownloadingList.Remove(item); }); + App.PropertyChangeAsync(() => { App.DownloadingList?.Remove(item); }); } }); } diff --git a/DownKyi/ViewModels/Friends/ViewFollowerViewModel.cs b/DownKyi/ViewModels/Friends/ViewFollowerViewModel.cs index 75cadd1..8303203 100644 --- a/DownKyi/ViewModels/Friends/ViewFollowerViewModel.cs +++ b/DownKyi/ViewModels/Friends/ViewFollowerViewModel.cs @@ -99,9 +99,6 @@ public class ViewFollowerViewModel : ViewModelBase #endregion } - #region 命令申明 - - #endregion private void LoadContent(List contents) { @@ -110,9 +107,7 @@ public class ViewFollowerViewModel : ViewModelBase NoDataVisibility = false; foreach (var item in contents) { - var storageHeader = new StorageHeader(); - var header = storageHeader.GetHeaderThumbnail(item.Mid, item.Name, item.Face, 64, 64); - PropertyChangeAsync(() => { Contents.Add(new FriendInfo(EventAggregator) { Mid = item.Mid, Header = header, Name = item.Name, Sign = item.Sign }); }); + PropertyChangeAsync(() => { Contents.Add(new FriendInfo(EventAggregator) { Mid = item.Mid, Header = item.Face, Name = item.Name, Sign = item.Sign }); }); } } @@ -161,14 +156,7 @@ public class ViewFollowerViewModel : ViewModelBase else { var page = (int)Math.Ceiling((double)data.Total / NumberInPage); - if (page > 5) - { - Pager.Count = 5; - } - else - { - Pager.Count = page; - } + Pager.Count = page > 5 ? 5 : page; } ContentVisibility = true; @@ -229,17 +217,15 @@ public class ViewFollowerViewModel : ViewModelBase // true表示加载PageFriends后第一次进入此页面 // false表示从headerTable的item点击进入的 var isFirst = navigationContext.Parameters.GetValue("isFirst"); - if (isFirst) - { - InitView(); + if (!isFirst) return; + InitView(); - //UpdateContent(1); + //UpdateContent(1); - // 页面选择 - Pager = new CustomPagerViewModel(1, (int)Math.Ceiling((double)1 / NumberInPage)); - Pager.CurrentChanged += OnCurrentChanged_Pager; - Pager.CountChanged += OnCountChanged_Pager; - Pager.Current = 1; - } + // 页面选择 + Pager = new CustomPagerViewModel(1, (int)Math.Ceiling((double)1 / NumberInPage)); + Pager.CurrentChanged += OnCurrentChanged_Pager; + Pager.CountChanged += OnCountChanged_Pager; + Pager.Current = 1; } } \ No newline at end of file diff --git a/DownKyi/ViewModels/Friends/ViewFollowingViewModel.cs b/DownKyi/ViewModels/Friends/ViewFollowingViewModel.cs index a23dffa..9b55f3c 100644 --- a/DownKyi/ViewModels/Friends/ViewFollowingViewModel.cs +++ b/DownKyi/ViewModels/Friends/ViewFollowingViewModel.cs @@ -279,9 +279,7 @@ public class ViewFollowingViewModel : ViewModelBase ContentNoDataVisibility = false; foreach (var item in contents) { - var storageHeader = new StorageHeader(); - var header = storageHeader.GetHeaderThumbnail(item.Mid, item.Name, item.Face, 64, 64); - PropertyChangeAsync(() => { Contents.Add(new FriendInfo(EventAggregator) { Mid = item.Mid, Header = header, Name = item.Name, Sign = item.Sign }); }); + PropertyChangeAsync(() => { Contents.Add(new FriendInfo(EventAggregator) { Mid = item.Mid, Header = item.Face, Name = item.Name, Sign = item.Sign }); }); } } @@ -354,19 +352,12 @@ public class ViewFollowingViewModel : ViewModelBase var tab = TabHeaders[SelectTabId]; - bool isSucceed; - switch (tab.Id) + var isSucceed = tab.Id switch { - case -1: - isSucceed = await LoadAllFollowings(current, NumberInPage); - break; - case -2: - isSucceed = await LoadWhispers(current, NumberInPage); - break; - default: - isSucceed = await LoadFollowingGroupContent(tab.Id, current, NumberInPage); - break; - } + -1 => await LoadAllFollowings(current, NumberInPage), + -2 => await LoadWhispers(current, NumberInPage), + _ => await LoadFollowingGroupContent(tab.Id, current, NumberInPage) + }; if (isSucceed) { @@ -424,7 +415,7 @@ public class ViewFollowingViewModel : ViewModelBase var isFirst = navigationContext.Parameters.GetValue("isFirst"); if (isFirst) { - async void Init() + async Task Init() { InitView(); // 初始化左侧列表 diff --git a/DownKyi/ViewModels/MainWindowViewModel.cs b/DownKyi/ViewModels/MainWindowViewModel.cs index c5bd076..0b920a7 100644 --- a/DownKyi/ViewModels/MainWindowViewModel.cs +++ b/DownKyi/ViewModels/MainWindowViewModel.cs @@ -137,8 +137,8 @@ public class MainWindowViewModel : BindableBase #endregion - var isListenClipboard = SettingsManager.GetInstance().IsListenClipboard(); - if (isListenClipboard != AllowStatus.YES) + var isListenClipboard = SettingsManager.GetInstance().GetIsListenClipboard(); + if (isListenClipboard != AllowStatus.Yes) { return; } diff --git a/DownKyi/ViewModels/PageViewModels/BangumiFollowMedia.cs b/DownKyi/ViewModels/PageViewModels/BangumiFollowMedia.cs index 5822d17..da32df8 100644 --- a/DownKyi/ViewModels/PageViewModels/BangumiFollowMedia.cs +++ b/DownKyi/ViewModels/PageViewModels/BangumiFollowMedia.cs @@ -9,11 +9,11 @@ namespace DownKyi.ViewModels.PageViewModels; public class BangumiFollowMedia : BindableBase { - protected readonly IEventAggregator eventAggregator; + protected readonly IEventAggregator EventAggregator; public BangumiFollowMedia(IEventAggregator eventAggregator) { - this.eventAggregator = eventAggregator; + this.EventAggregator = eventAggregator; } // media id @@ -34,9 +34,9 @@ public class BangumiFollowMedia : BindableBase } // 封面 - private Bitmap cover; + private string cover; - public Bitmap Cover + public string Cover { get => cover; set => SetProperty(ref cover, value); @@ -121,12 +121,12 @@ public class BangumiFollowMedia : BindableBase /// private void ExecuteTitleCommand(object parameter) { - if (!(parameter is string tag)) + if (parameter is not string tag) { return; } - NavigateToView.NavigationView(eventAggregator, ViewVideoDetailViewModel.Tag, tag, + NavigateToView.NavigationView(EventAggregator, ViewVideoDetailViewModel.Tag, tag, $"{ParseEntrance.BangumiMediaUrl}md{MediaId}"); } diff --git a/DownKyi/ViewModels/PageViewModels/ChannelMedia.cs b/DownKyi/ViewModels/PageViewModels/ChannelMedia.cs index 81176f0..ebe8ce9 100644 --- a/DownKyi/ViewModels/PageViewModels/ChannelMedia.cs +++ b/DownKyi/ViewModels/PageViewModels/ChannelMedia.cs @@ -21,52 +21,52 @@ public class ChannelMedia : BindableBase #region 页面属性申明 - private bool isSelected; + private bool _isSelected; public bool IsSelected { - get => isSelected; - set => SetProperty(ref isSelected, value); + get => _isSelected; + set => SetProperty(ref _isSelected, value); } - private Bitmap cover; + private string _cover; - public Bitmap Cover + public string Cover { - get => cover; - set => SetProperty(ref cover, value); + get => _cover; + set => SetProperty(ref _cover, value); } - private string title; + private string _title; public string Title { - get => title; - set => SetProperty(ref title, value); + get => _title; + set => SetProperty(ref _title, value); } - private string duration; + private string _duration; public string Duration { - get => duration; - set => SetProperty(ref duration, value); + get => _duration; + set => SetProperty(ref _duration, value); } - private string playNumber; + private string _playNumber; public string PlayNumber { - get => playNumber; - set => SetProperty(ref playNumber, value); + get => _playNumber; + set => SetProperty(ref _playNumber, value); } - private string createTime; + private string _createTime; public string CreateTime { - get => createTime; - set => SetProperty(ref createTime, value); + get => _createTime; + set => SetProperty(ref _createTime, value); } #endregion @@ -74,10 +74,9 @@ public class ChannelMedia : BindableBase #region 命令申明 // 视频标题点击事件 - private DelegateCommand titleCommand; + private DelegateCommand _titleCommand; - public DelegateCommand TitleCommand => - titleCommand ?? (titleCommand = new DelegateCommand(ExecuteTitleCommand)); + public DelegateCommand TitleCommand => _titleCommand ?? (_titleCommand = new DelegateCommand(ExecuteTitleCommand)); /// /// 视频标题点击事件 @@ -85,7 +84,7 @@ public class ChannelMedia : BindableBase /// private void ExecuteTitleCommand(object parameter) { - if (!(parameter is string tag)) + if (parameter is not string tag) { return; } diff --git a/DownKyi/ViewModels/PageViewModels/Favorites.cs b/DownKyi/ViewModels/PageViewModels/Favorites.cs index 2a8a2f8..dfa2a32 100644 --- a/DownKyi/ViewModels/PageViewModels/Favorites.cs +++ b/DownKyi/ViewModels/PageViewModels/Favorites.cs @@ -7,16 +7,16 @@ namespace DownKyi.ViewModels.PageViewModels; public class Favorites : BindableBase { - public string CoverUrl { get; set; } + private string coverUrl; + + public string CoverUrl + { + get => coverUrl; + set => SetProperty(ref coverUrl, value); + } + public long UpperMid { get; set; } - private Bitmap cover; - - public Bitmap Cover - { - get => cover; - set => SetProperty(ref cover, value); - } private string title; @@ -122,9 +122,9 @@ public class Favorites : BindableBase set => SetProperty(ref upName, value); } - private Bitmap upHeader; + private string upHeader; - public Bitmap UpHeader + public string UpHeader { get => upHeader; set => SetProperty(ref upHeader, value); @@ -136,13 +136,13 @@ public class Favorites : BindableBase Play = NormalIcon.Instance().Play; Play.Fill = DictionaryResource.GetColor("ColorTextGrey2"); - + Like = NormalIcon.Instance().Like; Like.Fill = DictionaryResource.GetColor("ColorTextGrey2"); - + Favorite = NormalIcon.Instance().Favorite; Favorite.Fill = DictionaryResource.GetColor("ColorTextGrey2"); - + Share = NormalIcon.Instance().Share; Share.Fill = DictionaryResource.GetColor("ColorTextGrey2"); diff --git a/DownKyi/ViewModels/PageViewModels/FavoritesMedia.cs b/DownKyi/ViewModels/PageViewModels/FavoritesMedia.cs index 6b697a9..8bec1cf 100644 --- a/DownKyi/ViewModels/PageViewModels/FavoritesMedia.cs +++ b/DownKyi/ViewModels/PageViewModels/FavoritesMedia.cs @@ -9,11 +9,11 @@ namespace DownKyi.ViewModels.PageViewModels; public class FavoritesMedia : BindableBase { - protected readonly IEventAggregator eventAggregator; + protected readonly IEventAggregator EventAggregator; public FavoritesMedia(IEventAggregator eventAggregator) { - this.eventAggregator = eventAggregator; + EventAggregator = eventAggregator; } public long Avid { get; set; } @@ -38,9 +38,9 @@ public class FavoritesMedia : BindableBase set => SetProperty(ref order, value); } - private Bitmap cover; + private string cover; - public Bitmap Cover + public string Cover { get => cover; set => SetProperty(ref cover, value); @@ -115,10 +115,9 @@ public class FavoritesMedia : BindableBase #region 命令申明 // 视频标题点击事件 - private DelegateCommand titleCommand; + private DelegateCommand _titleCommand; - public DelegateCommand TitleCommand => - titleCommand ?? (titleCommand = new DelegateCommand(ExecuteTitleCommand)); + public DelegateCommand TitleCommand => _titleCommand ??= new DelegateCommand(ExecuteTitleCommand); /// /// 视频标题点击事件 @@ -126,21 +125,19 @@ public class FavoritesMedia : BindableBase /// private void ExecuteTitleCommand(object parameter) { - if (!(parameter is string tag)) + if (parameter is not string tag) { return; } - NavigateToView.NavigationView(eventAggregator, ViewVideoDetailViewModel.Tag, tag, + NavigateToView.NavigationView(EventAggregator, ViewVideoDetailViewModel.Tag, tag, $"{ParseEntrance.VideoUrl}{Bvid}"); } // 视频的UP主点击事件 - private DelegateCommand videoUpperCommand; + private DelegateCommand _videoUpperCommand; - public DelegateCommand VideoUpperCommand => videoUpperCommand ?? - (videoUpperCommand = - new DelegateCommand(ExecuteVideoUpperCommand)); + public DelegateCommand VideoUpperCommand => _videoUpperCommand ??= new DelegateCommand(ExecuteVideoUpperCommand); /// /// 视频的UP主点击事件 @@ -148,12 +145,12 @@ public class FavoritesMedia : BindableBase /// private void ExecuteVideoUpperCommand(object parameter) { - if (!(parameter is string tag)) + if (parameter is not string tag) { return; } - // NavigateToView.NavigateToViewUserSpace(eventAggregator, tag, UpMid); + NavigateToView.NavigateToViewUserSpace(EventAggregator, tag, UpMid); } #endregion diff --git a/DownKyi/ViewModels/PageViewModels/FriendInfo.cs b/DownKyi/ViewModels/PageViewModels/FriendInfo.cs index 849805f..7be5d19 100644 --- a/DownKyi/ViewModels/PageViewModels/FriendInfo.cs +++ b/DownKyi/ViewModels/PageViewModels/FriendInfo.cs @@ -8,39 +8,39 @@ namespace DownKyi.ViewModels.PageViewModels; public class FriendInfo : BindableBase { - protected readonly IEventAggregator eventAggregator; + protected readonly IEventAggregator EventAggregator; public FriendInfo(IEventAggregator eventAggregator) { - this.eventAggregator = eventAggregator; + this.EventAggregator = eventAggregator; } public long Mid { get; set; } #region 页面属性申明 - private Bitmap header; + private string _header; - public Bitmap Header + public string Header { - get => header; - set => SetProperty(ref header, value); + get => _header; + set => SetProperty(ref _header, value); } - private string name; + private string _name; public string Name { - get => name; - set => SetProperty(ref name, value); + get => _name; + set => SetProperty(ref _name, value); } - private string sign; + private string _sign; public string Sign { - get => sign; - set => SetProperty(ref sign, value); + get => _sign; + set => SetProperty(ref _sign, value); } #endregion @@ -48,10 +48,9 @@ public class FriendInfo : BindableBase #region 命令申明 // 视频标题点击事件 - private DelegateCommand userCommand; + private DelegateCommand _userCommand; - public DelegateCommand UserCommand => - userCommand ?? (userCommand = new DelegateCommand(ExecuteUserCommand)); + public DelegateCommand UserCommand => _userCommand ??= new DelegateCommand(ExecuteUserCommand); /// /// 视频标题点击事件 @@ -59,12 +58,12 @@ public class FriendInfo : BindableBase /// private void ExecuteUserCommand(object parameter) { - if (!(parameter is string tag)) + if (parameter is not string tag) { return; } - NavigateToView.NavigationView(eventAggregator, ViewUserSpaceViewModel.Tag, tag, Mid); + NavigateToView.NavigationView(EventAggregator, ViewUserSpaceViewModel.Tag, tag, Mid); } #endregion diff --git a/DownKyi/ViewModels/PageViewModels/HistoryMedia.cs b/DownKyi/ViewModels/PageViewModels/HistoryMedia.cs index c5d3ecd..9e79ae4 100644 --- a/DownKyi/ViewModels/PageViewModels/HistoryMedia.cs +++ b/DownKyi/ViewModels/PageViewModels/HistoryMedia.cs @@ -9,11 +9,11 @@ namespace DownKyi.ViewModels.PageViewModels; public class HistoryMedia : BindableBase { - protected readonly IEventAggregator eventAggregator; + protected readonly IEventAggregator EventAggregator; public HistoryMedia(IEventAggregator eventAggregator) { - this.eventAggregator = eventAggregator; + EventAggregator = eventAggregator; } // bvid @@ -31,120 +31,120 @@ public class HistoryMedia : BindableBase #region 页面属性申明 // 是否选中 - private bool isSelected; + private bool _isSelected; public bool IsSelected { - get => isSelected; - set => SetProperty(ref isSelected, value); + get => _isSelected; + set => SetProperty(ref _isSelected, value); } // 封面 - private Bitmap cover; + private string _cover; - public Bitmap Cover + public string Cover { - get => cover; - set => SetProperty(ref cover, value); + get => _cover; + set => SetProperty(ref _cover, value); } // 视频标题 - private string title; + private string _title; public string Title { - get => title; - set => SetProperty(ref title, value); + get => _title; + set => SetProperty(ref _title, value); } // 分P的标题 - private string subTitle; + private string _subTitle; public string SubTitle { - get => subTitle; - set => SetProperty(ref subTitle, value); + get => _subTitle; + set => SetProperty(ref _subTitle, value); } // 时长 - private long duration; + private long _duration; public long Duration { - get => duration; - set => SetProperty(ref duration, value); + get => _duration; + set => SetProperty(ref _duration, value); } // tag标签 - private string tagName; + private string _tagName; public string TagName { - get => tagName; - set => SetProperty(ref tagName, value); + get => _tagName; + set => SetProperty(ref _tagName, value); } // new_desc 剧集或分P描述 - private string partdesc; + private string _partdesc; public string Partdesc { - get => partdesc; - set => SetProperty(ref partdesc, value); + get => _partdesc; + set => SetProperty(ref _partdesc, value); } // 观看进度 - private string progress; + private string _progress; public string Progress { - get => progress; - set => SetProperty(ref progress, value); + get => _progress; + set => SetProperty(ref _progress, value); } // 观看平台 - private VectorImage platform; + private VectorImage _platform; public VectorImage Platform { - get => platform; - set => SetProperty(ref platform, value); + get => _platform; + set => SetProperty(ref _platform, value); } // UP主的昵称 - private string upName; + private string _upName; public string UpName { - get => upName; - set => SetProperty(ref upName, value); + get => _upName; + set => SetProperty(ref _upName, value); } // UP主的头像 - private Bitmap upHeader; + private string _upHeader; - public Bitmap UpHeader + public string UpHeader { - get => upHeader; - set => SetProperty(ref upHeader, value); + get => _upHeader; + set => SetProperty(ref _upHeader, value); } // 是否显示Partdesc - private bool partdescVisibility; + private bool _partdescVisibility; public bool PartdescVisibility { - get => partdescVisibility; - set => SetProperty(ref partdescVisibility, value); + get => _partdescVisibility; + set => SetProperty(ref _partdescVisibility, value); } // 是否显示UP主信息和分区信息 - private bool upAndTagVisibility; + private bool _upAndTagVisibility; public bool UpAndTagVisibility { - get => upAndTagVisibility; - set => SetProperty(ref upAndTagVisibility, value); + get => _upAndTagVisibility; + set => SetProperty(ref _upAndTagVisibility, value); } #endregion @@ -152,10 +152,9 @@ public class HistoryMedia : BindableBase #region 命令申明 // 视频标题点击事件 - private DelegateCommand titleCommand; + private DelegateCommand _titleCommand; - public DelegateCommand TitleCommand => - titleCommand ?? (titleCommand = new DelegateCommand(ExecuteTitleCommand)); + public DelegateCommand TitleCommand => _titleCommand ??= new DelegateCommand(ExecuteTitleCommand); /// /// 视频标题点击事件 @@ -163,19 +162,18 @@ public class HistoryMedia : BindableBase /// private void ExecuteTitleCommand(object parameter) { - if (!(parameter is string tag)) + if (parameter is not string tag) { return; } - NavigateToView.NavigationView(eventAggregator, ViewVideoDetailViewModel.Tag, tag, Url); + NavigateToView.NavigationView(EventAggregator, ViewVideoDetailViewModel.Tag, tag, Url); } // UP主头像点击事件 - private DelegateCommand upCommand; + private DelegateCommand _upCommand; - public DelegateCommand UpCommand => - upCommand ?? (upCommand = new DelegateCommand(ExecuteUpCommand)); + public DelegateCommand UpCommand => _upCommand ??= new DelegateCommand(ExecuteUpCommand); /// /// UP主头像点击事件 @@ -183,12 +181,12 @@ public class HistoryMedia : BindableBase /// private void ExecuteUpCommand(object parameter) { - if (!(parameter is string tag)) + if (parameter is not string tag) { return; } - NavigateToView.NavigateToViewUserSpace(eventAggregator, tag, UpMid); + NavigateToView.NavigateToViewUserSpace(EventAggregator, tag, UpMid); } #endregion diff --git a/DownKyi/ViewModels/PageViewModels/PublicationMedia.cs b/DownKyi/ViewModels/PageViewModels/PublicationMedia.cs index 4e9ade9..c5c306e 100644 --- a/DownKyi/ViewModels/PageViewModels/PublicationMedia.cs +++ b/DownKyi/ViewModels/PageViewModels/PublicationMedia.cs @@ -9,65 +9,72 @@ namespace DownKyi.ViewModels.PageViewModels; public class PublicationMedia : BindableBase { - protected readonly IEventAggregator eventAggregator; + protected readonly IEventAggregator EventAggregator; public PublicationMedia(IEventAggregator eventAggregator) { - this.eventAggregator = eventAggregator; + this.EventAggregator = eventAggregator; + } + + private string _coverUrl; + + public string CoverUrl + { + get => _coverUrl; + set => SetProperty(ref _coverUrl, value); } - public string CoverUrl { get; set; } public long Avid { get; set; } public string Bvid { get; set; } #region 页面属性申明 - private bool isSelected; + private bool _isSelected; public bool IsSelected { - get => isSelected; - set => SetProperty(ref isSelected, value); + get => _isSelected; + set => SetProperty(ref _isSelected, value); } - private Bitmap cover; + private Bitmap _cover; public Bitmap Cover { - get => cover; - set => SetProperty(ref cover, value); + get => _cover; + set => SetProperty(ref _cover, value); } - private string title; + private string _title; public string Title { - get => title; - set => SetProperty(ref title, value); + get => _title; + set => SetProperty(ref _title, value); } - private string duration; + private string _duration; public string Duration { - get => duration; - set => SetProperty(ref duration, value); + get => _duration; + set => SetProperty(ref _duration, value); } - private string playNumber; + private string _playNumber; public string PlayNumber { - get => playNumber; - set => SetProperty(ref playNumber, value); + get => _playNumber; + set => SetProperty(ref _playNumber, value); } - private string createTime; + private string _createTime; public string CreateTime { - get => createTime; - set => SetProperty(ref createTime, value); + get => _createTime; + set => SetProperty(ref _createTime, value); } #endregion @@ -75,10 +82,9 @@ public class PublicationMedia : BindableBase #region 命令申明 // 视频标题点击事件 - private DelegateCommand titleCommand; + private DelegateCommand _titleCommand; - public DelegateCommand TitleCommand => - titleCommand ?? (titleCommand = new DelegateCommand(ExecuteTitleCommand)); + public DelegateCommand TitleCommand => _titleCommand ??= new DelegateCommand(ExecuteTitleCommand); /// /// 视频标题点击事件 @@ -86,12 +92,12 @@ public class PublicationMedia : BindableBase /// private void ExecuteTitleCommand(object parameter) { - if (!(parameter is string tag)) + if (parameter is not string tag) { return; } - NavigateToView.NavigationView(eventAggregator, ViewVideoDetailViewModel.Tag, tag, + NavigateToView.NavigationView(EventAggregator, ViewVideoDetailViewModel.Tag, tag, $"{ParseEntrance.VideoUrl}{Bvid}"); //string url = "https://www.bilibili.com/video/" + tag; //System.Diagnostics.Process.Start(url); diff --git a/DownKyi/ViewModels/PageViewModels/SpaceItem.cs b/DownKyi/ViewModels/PageViewModels/SpaceItem.cs index 9c456bc..ee78fa7 100644 --- a/DownKyi/ViewModels/PageViewModels/SpaceItem.cs +++ b/DownKyi/ViewModels/PageViewModels/SpaceItem.cs @@ -5,12 +5,12 @@ namespace DownKyi.ViewModels.PageViewModels; public class SpaceItem : BindableBase { - private bool isEnabled; + private bool _isEnabled; public bool IsEnabled { - get => isEnabled; - set => SetProperty(ref isEnabled, value); + get => _isEnabled; + set => SetProperty(ref _isEnabled, value); } private VectorImage image; diff --git a/DownKyi/ViewModels/PageViewModels/ToViewMedia.cs b/DownKyi/ViewModels/PageViewModels/ToViewMedia.cs index 62f3346..f02ff9d 100644 --- a/DownKyi/ViewModels/PageViewModels/ToViewMedia.cs +++ b/DownKyi/ViewModels/PageViewModels/ToViewMedia.cs @@ -9,11 +9,11 @@ namespace DownKyi.ViewModels.PageViewModels; public class ToViewMedia : BindableBase { - protected readonly IEventAggregator eventAggregator; + protected readonly IEventAggregator EventAggregator; public ToViewMedia(IEventAggregator eventAggregator) { - this.eventAggregator = eventAggregator; + EventAggregator = eventAggregator; } // aid @@ -28,48 +28,48 @@ public class ToViewMedia : BindableBase #region 页面属性申明 // 是否选中 - private bool isSelected; + private bool _isSelected; public bool IsSelected { - get => isSelected; - set => SetProperty(ref isSelected, value); + get => _isSelected; + set => SetProperty(ref _isSelected, value); } // 封面 - private Bitmap cover; + private string _cover; - public Bitmap Cover + public string Cover { - get => cover; - set => SetProperty(ref cover, value); + get => _cover; + set => SetProperty(ref _cover, value); } // 视频标题 - private string title; + private string _title; public string Title { - get => title; - set => SetProperty(ref title, value); + get => _title; + set => SetProperty(ref _title, value); } // UP主的昵称 - private string upName; + private string _upName; public string UpName { - get => upName; - set => SetProperty(ref upName, value); + get => _upName; + set => SetProperty(ref _upName, value); } // UP主的头像 - private Bitmap upHeader; + private string _upHeader; - public Bitmap UpHeader + public string UpHeader { - get => upHeader; - set => SetProperty(ref upHeader, value); + get => _upHeader; + set => SetProperty(ref _upHeader, value); } #endregion @@ -77,10 +77,9 @@ public class ToViewMedia : BindableBase #region 命令申明 // 视频标题点击事件 - private DelegateCommand titleCommand; + private DelegateCommand _titleCommand; - public DelegateCommand TitleCommand => - titleCommand ?? (titleCommand = new DelegateCommand(ExecuteTitleCommand)); + public DelegateCommand TitleCommand => _titleCommand ??= new DelegateCommand(ExecuteTitleCommand); /// /// 视频标题点击事件 @@ -93,14 +92,13 @@ public class ToViewMedia : BindableBase return; } - NavigateToView.NavigationView(eventAggregator, ViewVideoDetailViewModel.Tag, tag, $"{ParseEntrance.VideoUrl}{Bvid}"); + NavigateToView.NavigationView(EventAggregator, ViewVideoDetailViewModel.Tag, tag, $"{ParseEntrance.VideoUrl}{Bvid}"); } // UP主头像点击事件 - private DelegateCommand upCommand; + private DelegateCommand _upCommand; - public DelegateCommand UpCommand => - upCommand ?? (upCommand = new DelegateCommand(ExecuteUpCommand)); + public DelegateCommand UpCommand => _upCommand ??= new DelegateCommand(ExecuteUpCommand); /// /// UP主头像点击事件 @@ -108,12 +106,12 @@ public class ToViewMedia : BindableBase /// private void ExecuteUpCommand(object parameter) { - if (!(parameter is string tag)) + if (parameter is not string tag) { return; } - // NavigateToView.NavigateToViewUserSpace(eventAggregator, tag, UpMid); + NavigateToView.NavigateToViewUserSpace(EventAggregator, tag, UpMid); } #endregion diff --git a/DownKyi/ViewModels/PageViewModels/VideoInfoView.cs b/DownKyi/ViewModels/PageViewModels/VideoInfoView.cs index 78ab1af..52082b1 100644 --- a/DownKyi/ViewModels/PageViewModels/VideoInfoView.cs +++ b/DownKyi/ViewModels/PageViewModels/VideoInfoView.cs @@ -5,119 +5,118 @@ namespace DownKyi.ViewModels.PageViewModels; public class VideoInfoView : BindableBase { - public string CoverUrl { get; set; } + private string _coverUrl; + + public string CoverUrl + { + get => _coverUrl; + set => SetProperty(ref _coverUrl, value); + } + public long UpperMid { get; set; } public int TypeId { get; set; } - private Bitmap cover; - - public Bitmap Cover - { - get => cover; - set => SetProperty(ref cover, value); - } - - private string title; + private string _title; public string Title { - get => title; - set => SetProperty(ref title, value); + get => _title; + set => SetProperty(ref _title, value); } - private string videoZone; + private string _videoZone; public string VideoZone { - get => videoZone; - set => SetProperty(ref videoZone, value); + get => _videoZone; + set => SetProperty(ref _videoZone, value); } - private string createTime; + private string _createTime; public string CreateTime { - get => createTime; - set => SetProperty(ref createTime, value); + get => _createTime; + set => SetProperty(ref _createTime, value); } - private string playNumber; + private string _playNumber; public string PlayNumber { - get => playNumber; - set => SetProperty(ref playNumber, value); + get => _playNumber; + set => SetProperty(ref _playNumber, value); } - private string danmakuNumber; + private string _danmakuNumber; public string DanmakuNumber { - get => danmakuNumber; - set => SetProperty(ref danmakuNumber, value); + get => _danmakuNumber; + set => SetProperty(ref _danmakuNumber, value); } - private string likeNumber; + private string _likeNumber; public string LikeNumber { - get => likeNumber; - set => SetProperty(ref likeNumber, value); + get => _likeNumber; + set => SetProperty(ref _likeNumber, value); } - private string coinNumber; + private string _coinNumber; public string CoinNumber { - get => coinNumber; - set => SetProperty(ref coinNumber, value); + get => _coinNumber; + set => SetProperty(ref _coinNumber, value); } - private string favoriteNumber; + private string _favoriteNumber; public string FavoriteNumber { - get => favoriteNumber; - set => SetProperty(ref favoriteNumber, value); + get => _favoriteNumber; + set => SetProperty(ref _favoriteNumber, value); } - private string shareNumber; + private string _shareNumber; public string ShareNumber { - get => shareNumber; - set => SetProperty(ref shareNumber, value); + get => _shareNumber; + set => SetProperty(ref _shareNumber, value); } - private string replyNumber; + private string _replyNumber; public string ReplyNumber { - get => replyNumber; - set => SetProperty(ref replyNumber, value); + get => _replyNumber; + set => SetProperty(ref _replyNumber, value); } - private string description; + private string _description; public string Description { - get => description; - set => SetProperty(ref description, value); + get => _description; + set => SetProperty(ref _description, value); } - private string upName; + private string _upName; public string UpName { - get => upName; - set => SetProperty(ref upName, value); + get => _upName; + set => SetProperty(ref _upName, value); } - private Bitmap upHeader; + private string _upHeader; - public Bitmap UpHeader + public string UpHeader { - get => upHeader; - set => SetProperty(ref upHeader, value); + get => _upHeader; + set => SetProperty(ref _upHeader, value); } } \ No newline at end of file diff --git a/DownKyi/ViewModels/PageViewModels/VideoPage.cs b/DownKyi/ViewModels/PageViewModels/VideoPage.cs index 70e3ea5..6e88c77 100644 --- a/DownKyi/ViewModels/PageViewModels/VideoPage.cs +++ b/DownKyi/ViewModels/PageViewModels/VideoPage.cs @@ -95,11 +95,9 @@ public class VideoPage : BindableBase #region // 视频画质选择事件 - private DelegateCommand videoQualitySelectedCommand; + private DelegateCommand _videoQualitySelectedCommand; - public DelegateCommand VideoQualitySelectedCommand => videoQualitySelectedCommand ?? - (videoQualitySelectedCommand = - new DelegateCommand(ExecuteVideoQualitySelectedCommand)); + public DelegateCommand VideoQualitySelectedCommand => _videoQualitySelectedCommand ??= new DelegateCommand(ExecuteVideoQualitySelectedCommand); /// /// 视频画质选择事件 diff --git a/DownKyi/ViewModels/PageViewModels/VideoQuality.cs b/DownKyi/ViewModels/PageViewModels/VideoQuality.cs index 282a721..0b97e02 100644 --- a/DownKyi/ViewModels/PageViewModels/VideoQuality.cs +++ b/DownKyi/ViewModels/PageViewModels/VideoQuality.cs @@ -5,40 +5,40 @@ namespace DownKyi.ViewModels.PageViewModels; public class VideoQuality : BindableBase { - private int quality; + private int _quality; public int Quality { - get => quality; - set => SetProperty(ref quality, value); + get => _quality; + set => SetProperty(ref _quality, value); } - private string qualityFormat; + private string _qualityFormat; public string QualityFormat { - get => qualityFormat; - set => SetProperty(ref qualityFormat, value); + get => _qualityFormat; + set => SetProperty(ref _qualityFormat, value); } - private List videoCodecList; + private List _videoCodecList; public List VideoCodecList { - get => videoCodecList; - set => SetProperty(ref videoCodecList, value); + get => _videoCodecList; + set => SetProperty(ref _videoCodecList, value); } - private string selectedVideoCodec; + private string _selectedVideoCodec; public string SelectedVideoCodec { - get => selectedVideoCodec; + get => _selectedVideoCodec; set { if (value != null) { - SetProperty(ref selectedVideoCodec, value); + SetProperty(ref _selectedVideoCodec, value); } } } diff --git a/DownKyi/ViewModels/PageViewModels/VideoSection.cs b/DownKyi/ViewModels/PageViewModels/VideoSection.cs index 620a2db..75446a4 100644 --- a/DownKyi/ViewModels/PageViewModels/VideoSection.cs +++ b/DownKyi/ViewModels/PageViewModels/VideoSection.cs @@ -7,27 +7,27 @@ public class VideoSection : BindableBase { public long Id { get; set; } - private string title; + private string _title; public string Title { - get => title; - set => SetProperty(ref title, value); + get => _title; + set => SetProperty(ref _title, value); } - private bool isSelected; + private bool _isSelected; public bool IsSelected { - get => isSelected; - set => SetProperty(ref isSelected, value); + get => _isSelected; + set => SetProperty(ref _isSelected, value); } - private List videoPages; + private List _videoPages; public List VideoPages { - get => videoPages; - set => SetProperty(ref videoPages, value); + get => _videoPages; + set => SetProperty(ref _videoPages, value); } } \ No newline at end of file diff --git a/DownKyi/ViewModels/Settings/DisplayFileNamePart.cs b/DownKyi/ViewModels/Settings/DisplayFileNamePart.cs index 96c038b..f27089c 100644 --- a/DownKyi/ViewModels/Settings/DisplayFileNamePart.cs +++ b/DownKyi/ViewModels/Settings/DisplayFileNamePart.cs @@ -7,11 +7,11 @@ public class DisplayFileNamePart : BindableBase { public FileNamePart Id { get; set; } - private string title; + private string _title; public string Title { - get => title; - set => SetProperty(ref title, value); + get => _title; + set => SetProperty(ref _title, value); } } \ No newline at end of file diff --git a/DownKyi/ViewModels/Settings/ViewAboutViewModel.cs b/DownKyi/ViewModels/Settings/ViewAboutViewModel.cs index 7b11e18..a304e45 100644 --- a/DownKyi/ViewModels/Settings/ViewAboutViewModel.cs +++ b/DownKyi/ViewModels/Settings/ViewAboutViewModel.cs @@ -60,7 +60,7 @@ public class ViewAboutViewModel : ViewModelBase { #region 属性初始化 - AppInfo app = new AppInfo(); + var app = new AppInfo(); AppName = app.Name; AppVersion = app.VersionName; @@ -78,12 +78,12 @@ public class ViewAboutViewModel : ViewModelBase _isOnNavigatedTo = true; // 是否接收测试版更新 - var isReceiveBetaVersion = SettingsManager.GetInstance().IsReceiveBetaVersion(); - IsReceiveBetaVersion = isReceiveBetaVersion == AllowStatus.YES; + var isReceiveBetaVersion = SettingsManager.GetInstance().GetIsReceiveBetaVersion(); + IsReceiveBetaVersion = isReceiveBetaVersion == AllowStatus.Yes; // 是否在启动时自动检查更新 var isAutoUpdateWhenLaunch = SettingsManager.GetInstance().GetAutoUpdateWhenLaunch(); - AutoUpdateWhenLaunch = isAutoUpdateWhenLaunch == AllowStatus.YES; + AutoUpdateWhenLaunch = isAutoUpdateWhenLaunch == AllowStatus.Yes; _isOnNavigatedTo = false; } @@ -116,7 +116,7 @@ public class ViewAboutViewModel : ViewModelBase { if (_isCheckVersion) return; _isCheckVersion = true; - (Version? version, string? body) = await new VersionCheckerService().GetLatestVersion(); + var (version, body) = await new VersionCheckerService().GetLatestVersion(); if(version is null) { EventAggregator.GetEvent().Publish("检查失败,请稍后重试~"); @@ -162,43 +162,39 @@ public class ViewAboutViewModel : ViewModelBase // 是否接收测试版更新事件 private DelegateCommand? _receiveBetaVersionCommand; - public DelegateCommand ReceiveBetaVersionCommand => - _receiveBetaVersionCommand ??= new DelegateCommand(ExecuteReceiveBetaVersionCommand); + public DelegateCommand ReceiveBetaVersionCommand => _receiveBetaVersionCommand ??= new DelegateCommand(ExecuteReceiveBetaVersionCommand); /// /// 是否接收测试版更新事件 /// private void ExecuteReceiveBetaVersionCommand() { - AllowStatus isReceiveBetaVersion = IsReceiveBetaVersion ? AllowStatus.YES : AllowStatus.NO; + var isReceiveBetaVersion = IsReceiveBetaVersion ? AllowStatus.Yes : AllowStatus.No; - bool isSucceed = SettingsManager.GetInstance().IsReceiveBetaVersion(isReceiveBetaVersion); + var isSucceed = SettingsManager.GetInstance().SetIsReceiveBetaVersion(isReceiveBetaVersion); PublishTip(isSucceed); } // 是否在启动时自动检查更新事件 private DelegateCommand? _autoUpdateWhenLaunchCommand; - public DelegateCommand AutoUpdateWhenLaunchCommand => - _autoUpdateWhenLaunchCommand ??= new DelegateCommand(ExecuteAutoUpdateWhenLaunchCommand); + public DelegateCommand AutoUpdateWhenLaunchCommand => _autoUpdateWhenLaunchCommand ??= new DelegateCommand(ExecuteAutoUpdateWhenLaunchCommand); /// /// 是否在启动时自动检查更新事件 /// private void ExecuteAutoUpdateWhenLaunchCommand() { - AllowStatus isAutoUpdateWhenLaunch = AutoUpdateWhenLaunch ? AllowStatus.YES : AllowStatus.NO; + var isAutoUpdateWhenLaunch = AutoUpdateWhenLaunch ? AllowStatus.Yes : AllowStatus.No; - bool isSucceed = SettingsManager.GetInstance().SetAutoUpdateWhenLaunch(isAutoUpdateWhenLaunch); + var isSucceed = SettingsManager.GetInstance().SetAutoUpdateWhenLaunch(isAutoUpdateWhenLaunch); PublishTip(isSucceed); } // Brotli.NET许可证查看事件 - private DelegateCommand brotliLicenseCommand; + private DelegateCommand _brotliLicenseCommand; - public DelegateCommand BrotliLicenseCommand => brotliLicenseCommand ?? - (brotliLicenseCommand = - new DelegateCommand(ExecuteBrotliLicenseCommand)); + public DelegateCommand BrotliLicenseCommand => _brotliLicenseCommand ??= new DelegateCommand(ExecuteBrotliLicenseCommand); /// /// Brotli.NET许可证查看事件 @@ -209,11 +205,9 @@ public class ViewAboutViewModel : ViewModelBase } // Google.Protobuf许可证查看事件 - private DelegateCommand protobufLicenseCommand; + private DelegateCommand _protobufLicenseCommand; - public DelegateCommand ProtobufLicenseCommand => protobufLicenseCommand ?? - (protobufLicenseCommand = - new DelegateCommand(ExecuteProtobufLicenseCommand)); + public DelegateCommand ProtobufLicenseCommand => _protobufLicenseCommand ??= new DelegateCommand(ExecuteProtobufLicenseCommand); /// /// Google.Protobuf许可证查看事件 @@ -224,11 +218,9 @@ public class ViewAboutViewModel : ViewModelBase } // Newtonsoft.Json许可证查看事件 - private DelegateCommand newtonsoftLicenseCommand; + private DelegateCommand _newtonsoftLicenseCommand; - public DelegateCommand NewtonsoftLicenseCommand => newtonsoftLicenseCommand ?? - (newtonsoftLicenseCommand = - new DelegateCommand(ExecuteNewtonsoftLicenseCommand)); + public DelegateCommand NewtonsoftLicenseCommand => _newtonsoftLicenseCommand ??= new DelegateCommand(ExecuteNewtonsoftLicenseCommand); /// /// Newtonsoft.Json许可证查看事件 @@ -239,11 +231,9 @@ public class ViewAboutViewModel : ViewModelBase } // Prism.DryIoc许可证查看事件 - private DelegateCommand prismLicenseCommand; + private DelegateCommand _prismLicenseCommand; - public DelegateCommand PrismLicenseCommand => prismLicenseCommand ?? - (prismLicenseCommand = - new DelegateCommand(ExecutePrismLicenseCommand)); + public DelegateCommand PrismLicenseCommand => _prismLicenseCommand ??= new DelegateCommand(ExecutePrismLicenseCommand); /// /// Prism.DryIoc许可证查看事件 @@ -254,11 +244,9 @@ public class ViewAboutViewModel : ViewModelBase } // QRCoder许可证查看事件 - private DelegateCommand qRCoderLicenseCommand; + private DelegateCommand _qRCoderLicenseCommand; - public DelegateCommand QRCoderLicenseCommand => qRCoderLicenseCommand ?? - (qRCoderLicenseCommand = - new DelegateCommand(ExecuteQRCoderLicenseCommand)); + public DelegateCommand QRCoderLicenseCommand => _qRCoderLicenseCommand ??= new DelegateCommand(ExecuteQRCoderLicenseCommand); /// /// QRCoder许可证查看事件 @@ -269,11 +257,9 @@ public class ViewAboutViewModel : ViewModelBase } // System.Data.SQLite.Core许可证查看事件 - private DelegateCommand sQLiteLicenseCommand; + private DelegateCommand _sQLiteLicenseCommand; - public DelegateCommand SQLiteLicenseCommand => sQLiteLicenseCommand ?? - (sQLiteLicenseCommand = - new DelegateCommand(ExecuteSQLiteLicenseCommand)); + public DelegateCommand SQLiteLicenseCommand => _sQLiteLicenseCommand ??= new DelegateCommand(ExecuteSQLiteLicenseCommand); /// /// System.Data.SQLite.Core许可证查看事件 @@ -284,10 +270,9 @@ public class ViewAboutViewModel : ViewModelBase } // Aria2c许可证查看事件 - private DelegateCommand ariaLicenseCommand; + private DelegateCommand _ariaLicenseCommand; - public DelegateCommand AriaLicenseCommand => - ariaLicenseCommand ?? (ariaLicenseCommand = new DelegateCommand(ExecuteAriaLicenseCommand)); + public DelegateCommand AriaLicenseCommand => _ariaLicenseCommand ??= new DelegateCommand(ExecuteAriaLicenseCommand); /// /// Aria2c许可证查看事件 @@ -298,11 +283,9 @@ public class ViewAboutViewModel : ViewModelBase } // FFmpeg许可证查看事件 - private DelegateCommand fFmpegLicenseCommand; + private DelegateCommand _fFmpegLicenseCommand; - public DelegateCommand FFmpegLicenseCommand => fFmpegLicenseCommand ?? - (fFmpegLicenseCommand = - new DelegateCommand(ExecuteFFmpegLicenseCommand)); + public DelegateCommand FFmpegLicenseCommand => _fFmpegLicenseCommand ??= new DelegateCommand(ExecuteFFmpegLicenseCommand); /// /// FFmpeg许可证查看事件 diff --git a/DownKyi/ViewModels/Settings/ViewBasicViewModel.cs b/DownKyi/ViewModels/Settings/ViewBasicViewModel.cs index 917017b..cbd6d6d 100644 --- a/DownKyi/ViewModels/Settings/ViewBasicViewModel.cs +++ b/DownKyi/ViewModels/Settings/ViewBasicViewModel.cs @@ -139,10 +139,10 @@ public class ViewBasicViewModel : ViewModelBase // 解析范围 ParseScopes = new List { - new() { Name = DictionaryResource.GetString("ParseNone"), ParseScope = ParseScope.NONE }, - new() { Name = DictionaryResource.GetString("ParseSelectedItem"), ParseScope = ParseScope.SELECTED_ITEM }, - new() { Name = DictionaryResource.GetString("ParseCurrentSection"), ParseScope = ParseScope.CURRENT_SECTION }, - new() { Name = DictionaryResource.GetString("ParseAll"), ParseScope = ParseScope.ALL } + new() { Name = DictionaryResource.GetString("ParseNone"), ParseScope = ParseScope.None }, + new() { Name = DictionaryResource.GetString("ParseSelectedItem"), ParseScope = ParseScope.SelectedItem }, + new() { Name = DictionaryResource.GetString("ParseCurrentSection"), ParseScope = ParseScope.CurrentSection }, + new() { Name = DictionaryResource.GetString("ParseAll"), ParseScope = ParseScope.All } }; RepeatDownloadStrategy = new List @@ -185,20 +185,20 @@ public class ViewBasicViewModel : ViewModelBase SetAfterDownloadOperation(afterDownload); // 是否监听剪贴板 - var isListenClipboard = SettingsManager.GetInstance().IsListenClipboard(); - ListenClipboard = isListenClipboard == AllowStatus.YES; + var isListenClipboard = SettingsManager.GetInstance().GetIsListenClipboard(); + ListenClipboard = isListenClipboard == AllowStatus.Yes; // 是否自动解析视频 - var isAutoParseVideo = SettingsManager.GetInstance().IsAutoParseVideo(); - AutoParseVideo = isAutoParseVideo == AllowStatus.YES; + var isAutoParseVideo = SettingsManager.GetInstance().GetIsAutoParseVideo(); + AutoParseVideo = isAutoParseVideo == AllowStatus.Yes; // 解析范围 var parseScope = SettingsManager.GetInstance().GetParseScope(); SelectedParseScope = ParseScopes.FirstOrDefault(t => { return t.ParseScope == parseScope; }); // 解析后是否自动下载解析视频 - var isAutoDownloadAll = SettingsManager.GetInstance().IsAutoDownloadAll(); - AutoDownloadAll = isAutoDownloadAll == AllowStatus.YES; + var isAutoDownloadAll = SettingsManager.GetInstance().GetIsAutoDownloadAll(); + AutoDownloadAll = isAutoDownloadAll == AllowStatus.Yes; // 重复下载策略 var repeatDownloadStrategy = SettingsManager.GetInstance().GetRepeatDownloadStrategy(); @@ -250,16 +250,16 @@ public class ViewBasicViewModel : ViewModelBase switch (parameter) { case "None": - afterDownload = AfterDownloadOperation.NONE; + afterDownload = AfterDownloadOperation.None; break; case "CloseApp": - afterDownload = AfterDownloadOperation.CLOSE_APP; + afterDownload = AfterDownloadOperation.CloseApp; break; case "CloseSystem": - afterDownload = AfterDownloadOperation.CLOSE_SYSTEM; + afterDownload = AfterDownloadOperation.CloseSystem; break; default: - afterDownload = AfterDownloadOperation.NONE; + afterDownload = AfterDownloadOperation.None; break; } @@ -277,9 +277,9 @@ public class ViewBasicViewModel : ViewModelBase /// private void ExecuteListenClipboardCommand() { - var isListenClipboard = ListenClipboard ? AllowStatus.YES : AllowStatus.NO; + var isListenClipboard = ListenClipboard ? AllowStatus.Yes : AllowStatus.No; - var isSucceed = SettingsManager.GetInstance().IsListenClipboard(isListenClipboard); + var isSucceed = SettingsManager.GetInstance().SetIsListenClipboard(isListenClipboard); PublishTip(isSucceed); } @@ -292,9 +292,9 @@ public class ViewBasicViewModel : ViewModelBase /// private void ExecuteAutoParseVideoCommand() { - var isAutoParseVideo = AutoParseVideo ? AllowStatus.YES : AllowStatus.NO; + var isAutoParseVideo = AutoParseVideo ? AllowStatus.Yes : AllowStatus.No; - var isSucceed = SettingsManager.GetInstance().IsAutoParseVideo(isAutoParseVideo); + var isSucceed = SettingsManager.GetInstance().SetIsAutoParseVideo(isAutoParseVideo); PublishTip(isSucceed); } @@ -328,9 +328,9 @@ public class ViewBasicViewModel : ViewModelBase /// private void ExecuteAutoDownloadAllCommand() { - var isAutoDownloadAll = AutoDownloadAll ? AllowStatus.YES : AllowStatus.NO; + var isAutoDownloadAll = AutoDownloadAll ? AllowStatus.Yes : AllowStatus.No; - var isSucceed = SettingsManager.GetInstance().IsAutoDownloadAll(isAutoDownloadAll); + var isSucceed = SettingsManager.GetInstance().SetIsAutoDownloadAll(isAutoDownloadAll); PublishTip(isSucceed); } @@ -374,15 +374,15 @@ public class ViewBasicViewModel : ViewModelBase { switch (afterDownload) { - case AfterDownloadOperation.NONE: + case AfterDownloadOperation.None: None = true; break; - case AfterDownloadOperation.OPEN_FOLDER: + case AfterDownloadOperation.OpenFolder: break; - case AfterDownloadOperation.CLOSE_APP: + case AfterDownloadOperation.CloseApp: CloseApp = true; break; - case AfterDownloadOperation.CLOSE_SYSTEM: + case AfterDownloadOperation.CloseSystem: CloseSystem = true; break; } @@ -399,13 +399,6 @@ public class ViewBasicViewModel : ViewModelBase return; } - if (isSucceed) - { - EventAggregator.GetEvent().Publish(DictionaryResource.GetString("TipSettingUpdated")); - } - else - { - EventAggregator.GetEvent().Publish(DictionaryResource.GetString("TipSettingFailed")); - } + EventAggregator.GetEvent().Publish(isSucceed ? DictionaryResource.GetString("TipSettingUpdated") : DictionaryResource.GetString("TipSettingFailed")); } } \ No newline at end of file diff --git a/DownKyi/ViewModels/Settings/ViewDanmakuViewModel.cs b/DownKyi/ViewModels/Settings/ViewDanmakuViewModel.cs index 26b3e63..f76bc6d 100644 --- a/DownKyi/ViewModels/Settings/ViewDanmakuViewModel.cs +++ b/DownKyi/ViewModels/Settings/ViewDanmakuViewModel.cs @@ -15,96 +15,96 @@ public class ViewDanmakuViewModel : ViewModelBase { public const string Tag = "PageSettingsDanmaku"; - private bool isOnNavigatedTo; + private bool _isOnNavigatedTo; #region 页面属性申明 - private bool topFilter; + private bool _topFilter; public bool TopFilter { - get { return topFilter; } - set { SetProperty(ref topFilter, value); } + get => _topFilter; + set => SetProperty(ref _topFilter, value); } - private bool bottomFilter; + private bool _bottomFilter; public bool BottomFilter { - get { return bottomFilter; } - set { SetProperty(ref bottomFilter, value); } + get => _bottomFilter; + set => SetProperty(ref _bottomFilter, value); } - private bool scrollFilter; + private bool _scrollFilter; public bool ScrollFilter { - get { return scrollFilter; } - set { SetProperty(ref scrollFilter, value); } + get => _scrollFilter; + set => SetProperty(ref _scrollFilter, value); } - private int screenWidth; + private int _screenWidth; public int ScreenWidth { - get { return screenWidth; } - set { SetProperty(ref screenWidth, value); } + get => _screenWidth; + set => SetProperty(ref _screenWidth, value); } - private int screenHeight; + private int _screenHeight; public int ScreenHeight { - get { return screenHeight; } - set { SetProperty(ref screenHeight, value); } + get => _screenHeight; + set => SetProperty(ref _screenHeight, value); } - private List fonts; + private List _fonts; public List Fonts { - get { return fonts; } - set { SetProperty(ref fonts, value); } + get => _fonts; + set => SetProperty(ref _fonts, value); } - private string selectedFont; + private string _selectedFont; public string SelectedFont { - get { return selectedFont; } - set { SetProperty(ref selectedFont, value); } + get => _selectedFont; + set => SetProperty(ref _selectedFont, value); } - private int fontSize; + private int _fontSize; public int FontSize { - get { return fontSize; } - set { SetProperty(ref fontSize, value); } + get => _fontSize; + set => SetProperty(ref _fontSize, value); } - private int lineCount; + private int _lineCount; public int LineCount { - get { return lineCount; } - set { SetProperty(ref lineCount, value); } + get => _lineCount; + set => SetProperty(ref _lineCount, value); } - private bool sync; + private bool _sync; public bool Sync { - get { return sync; } - set { SetProperty(ref sync, value); } + get => _sync; + set => SetProperty(ref _sync, value); } - private bool async; + private bool _async; public bool Async { - get { return async; } - set { SetProperty(ref async, value); } + get => _async; + set => SetProperty(ref _async, value); } #endregion @@ -115,7 +115,7 @@ public class ViewDanmakuViewModel : ViewModelBase // 弹幕字体 Fonts = new List(); - var fontCollection = FontManager.Current.SystemFonts.Select(x=>x.Name); + var fontCollection = FontManager.Current.SystemFonts.Select(x => x.Name); foreach (var font in fontCollection) { Fonts.Add(font); @@ -132,19 +132,19 @@ public class ViewDanmakuViewModel : ViewModelBase { base.OnNavigatedTo(navigationContext); - isOnNavigatedTo = true; + _isOnNavigatedTo = true; // 屏蔽顶部弹幕 - AllowStatus danmakuTopFilter = SettingsManager.GetInstance().GetDanmakuTopFilter(); - TopFilter = danmakuTopFilter == AllowStatus.YES; + var danmakuTopFilter = SettingsManager.GetInstance().GetDanmakuTopFilter(); + TopFilter = danmakuTopFilter == AllowStatus.Yes; // 屏蔽底部弹幕 - AllowStatus danmakuBottomFilter = SettingsManager.GetInstance().GetDanmakuBottomFilter(); - BottomFilter = danmakuBottomFilter == AllowStatus.YES; + var danmakuBottomFilter = SettingsManager.GetInstance().GetDanmakuBottomFilter(); + BottomFilter = danmakuBottomFilter == AllowStatus.Yes; // 屏蔽滚动弹幕 - AllowStatus danmakuScrollFilter = SettingsManager.GetInstance().GetDanmakuScrollFilter(); - ScrollFilter = danmakuScrollFilter == AllowStatus.YES; + var danmakuScrollFilter = SettingsManager.GetInstance().GetDanmakuScrollFilter(); + ScrollFilter = danmakuScrollFilter == AllowStatus.Yes; // 分辨率-宽 ScreenWidth = SettingsManager.GetInstance().GetDanmakuScreenWidth(); @@ -153,7 +153,7 @@ public class ViewDanmakuViewModel : ViewModelBase ScreenHeight = SettingsManager.GetInstance().GetDanmakuScreenHeight(); // 弹幕字体 - string danmakuFont = SettingsManager.GetInstance().GetDanmakuFontName(); + var danmakuFont = SettingsManager.GetInstance().GetDanmakuFontName(); if (danmakuFont != null && Fonts.Contains(danmakuFont)) { // 只有系统中存在当前设置的字体,才能显示 @@ -167,73 +167,66 @@ public class ViewDanmakuViewModel : ViewModelBase LineCount = SettingsManager.GetInstance().GetDanmakuLineCount(); // 弹幕布局算法 - DanmakuLayoutAlgorithm layoutAlgorithm = SettingsManager.GetInstance().GetDanmakuLayoutAlgorithm(); + var layoutAlgorithm = SettingsManager.GetInstance().GetDanmakuLayoutAlgorithm(); SetLayoutAlgorithm(layoutAlgorithm); - isOnNavigatedTo = false; + _isOnNavigatedTo = false; } #region 命令申明 // 屏蔽顶部弹幕事件 - private DelegateCommand topFilterCommand; + private DelegateCommand _topFilterCommand; - public DelegateCommand TopFilterCommand => - topFilterCommand ?? (topFilterCommand = new DelegateCommand(ExecuteTopFilterCommand)); + public DelegateCommand TopFilterCommand => _topFilterCommand ??= new DelegateCommand(ExecuteTopFilterCommand); /// /// 屏蔽顶部弹幕事件 /// private void ExecuteTopFilterCommand() { - AllowStatus isTopFilter = TopFilter ? AllowStatus.YES : AllowStatus.NO; + var isTopFilter = TopFilter ? AllowStatus.Yes : AllowStatus.No; - bool isSucceed = SettingsManager.GetInstance().SetDanmakuTopFilter(isTopFilter); + var isSucceed = SettingsManager.GetInstance().SetDanmakuTopFilter(isTopFilter); PublishTip(isSucceed); } // 屏蔽底部弹幕事件 - private DelegateCommand bottomFilterCommand; + private DelegateCommand _bottomFilterCommand; - public DelegateCommand BottomFilterCommand => bottomFilterCommand ?? - (bottomFilterCommand = - new DelegateCommand(ExecuteBottomFilterCommand)); + public DelegateCommand BottomFilterCommand => _bottomFilterCommand ??= new DelegateCommand(ExecuteBottomFilterCommand); /// /// 屏蔽底部弹幕事件 /// private void ExecuteBottomFilterCommand() { - AllowStatus isBottomFilter = BottomFilter ? AllowStatus.YES : AllowStatus.NO; + var isBottomFilter = BottomFilter ? AllowStatus.Yes : AllowStatus.No; - bool isSucceed = SettingsManager.GetInstance().SetDanmakuBottomFilter(isBottomFilter); + var isSucceed = SettingsManager.GetInstance().SetDanmakuBottomFilter(isBottomFilter); PublishTip(isSucceed); } // 屏蔽滚动弹幕事件 - private DelegateCommand scrollFilterCommand; + private DelegateCommand _scrollFilterCommand; - public DelegateCommand ScrollFilterCommand => scrollFilterCommand ?? - (scrollFilterCommand = - new DelegateCommand(ExecuteScrollFilterCommand)); + public DelegateCommand ScrollFilterCommand => _scrollFilterCommand ??= new DelegateCommand(ExecuteScrollFilterCommand); /// /// 屏蔽滚动弹幕事件 /// private void ExecuteScrollFilterCommand() { - AllowStatus isScrollFilter = ScrollFilter ? AllowStatus.YES : AllowStatus.NO; + var isScrollFilter = ScrollFilter ? AllowStatus.Yes : AllowStatus.No; - bool isSucceed = SettingsManager.GetInstance().SetDanmakuScrollFilter(isScrollFilter); + var isSucceed = SettingsManager.GetInstance().SetDanmakuScrollFilter(isScrollFilter); PublishTip(isSucceed); } // 设置分辨率-宽事件 - private DelegateCommand screenWidthCommand; + private DelegateCommand _screenWidthCommand; - public DelegateCommand ScreenWidthCommand => screenWidthCommand ?? - (screenWidthCommand = - new DelegateCommand(ExecuteScreenWidthCommand)); + public DelegateCommand ScreenWidthCommand => _screenWidthCommand ??= new DelegateCommand(ExecuteScreenWidthCommand); /// /// 设置分辨率-宽事件 @@ -241,19 +234,17 @@ public class ViewDanmakuViewModel : ViewModelBase /// private void ExecuteScreenWidthCommand(string parameter) { - int width = (int)Number.GetInt(parameter); + var width = (int)Number.GetInt(parameter); ScreenWidth = width; - bool isSucceed = SettingsManager.GetInstance().SetDanmakuScreenWidth(ScreenWidth); + var isSucceed = SettingsManager.GetInstance().SetDanmakuScreenWidth(ScreenWidth); PublishTip(isSucceed); } // 设置分辨率-高事件 - private DelegateCommand screenHeightCommand; + private DelegateCommand _screenHeightCommand; - public DelegateCommand ScreenHeightCommand => screenHeightCommand ?? - (screenHeightCommand = - new DelegateCommand(ExecuteScreenHeightCommand)); + public DelegateCommand ScreenHeightCommand => _screenHeightCommand ??= new DelegateCommand(ExecuteScreenHeightCommand); /// /// 设置分辨率-高事件 @@ -261,19 +252,17 @@ public class ViewDanmakuViewModel : ViewModelBase /// private void ExecuteScreenHeightCommand(string parameter) { - int height = (int)Number.GetInt(parameter); + var height = (int)Number.GetInt(parameter); ScreenHeight = height; - bool isSucceed = SettingsManager.GetInstance().SetDanmakuScreenHeight(ScreenHeight); + var isSucceed = SettingsManager.GetInstance().SetDanmakuScreenHeight(ScreenHeight); PublishTip(isSucceed); } // 弹幕字体选择事件 - private DelegateCommand fontSelectCommand; + private DelegateCommand _fontSelectCommand; - public DelegateCommand FontSelectCommand => fontSelectCommand ?? - (fontSelectCommand = - new DelegateCommand(ExecuteFontSelectCommand)); + public DelegateCommand FontSelectCommand => _fontSelectCommand ??= new DelegateCommand(ExecuteFontSelectCommand); /// /// 弹幕字体选择事件 @@ -281,15 +270,14 @@ public class ViewDanmakuViewModel : ViewModelBase /// private void ExecuteFontSelectCommand(string parameter) { - bool isSucceed = SettingsManager.GetInstance().SetDanmakuFontName(parameter); + var isSucceed = SettingsManager.GetInstance().SetDanmakuFontName(parameter); PublishTip(isSucceed); } // 弹幕字体大小事件 - private DelegateCommand fontSizeCommand; + private DelegateCommand _fontSizeCommand; - public DelegateCommand FontSizeCommand => - fontSizeCommand ?? (fontSizeCommand = new DelegateCommand(ExecuteFontSizeCommand)); + public DelegateCommand FontSizeCommand => _fontSizeCommand ??= new DelegateCommand(ExecuteFontSizeCommand); /// /// 弹幕字体大小事件 @@ -297,18 +285,17 @@ public class ViewDanmakuViewModel : ViewModelBase /// private void ExecuteFontSizeCommand(string parameter) { - int fontSize = (int)Number.GetInt(parameter); + var fontSize = (int)Number.GetInt(parameter); FontSize = fontSize; - bool isSucceed = SettingsManager.GetInstance().SetDanmakuFontSize(FontSize); + var isSucceed = SettingsManager.GetInstance().SetDanmakuFontSize(FontSize); PublishTip(isSucceed); } // 弹幕限制行数事件 - private DelegateCommand lineCountCommand; + private DelegateCommand _lineCountCommand; - public DelegateCommand LineCountCommand => - lineCountCommand ?? (lineCountCommand = new DelegateCommand(ExecuteLineCountCommand)); + public DelegateCommand LineCountCommand => _lineCountCommand ??= new DelegateCommand(ExecuteLineCountCommand); /// /// 弹幕限制行数事件 @@ -316,20 +303,17 @@ public class ViewDanmakuViewModel : ViewModelBase /// private void ExecuteLineCountCommand(string parameter) { - int lineCount = (int)Number.GetInt(parameter); + var lineCount = (int)Number.GetInt(parameter); LineCount = lineCount; - bool isSucceed = SettingsManager.GetInstance().SetDanmakuLineCount(LineCount); + var isSucceed = SettingsManager.GetInstance().SetDanmakuLineCount(LineCount); PublishTip(isSucceed); } // 弹幕布局算法事件 - private DelegateCommand layoutAlgorithmCommand; + private DelegateCommand _layoutAlgorithmCommand; - public DelegateCommand LayoutAlgorithmCommand => layoutAlgorithmCommand ?? - (layoutAlgorithmCommand = - new DelegateCommand( - ExecuteLayoutAlgorithmCommand)); + public DelegateCommand LayoutAlgorithmCommand => _layoutAlgorithmCommand ??= new DelegateCommand(ExecuteLayoutAlgorithmCommand); /// /// 弹幕布局算法事件 @@ -337,21 +321,14 @@ public class ViewDanmakuViewModel : ViewModelBase /// private void ExecuteLayoutAlgorithmCommand(string parameter) { - DanmakuLayoutAlgorithm layoutAlgorithm; - switch (parameter) + var layoutAlgorithm = parameter switch { - case "Sync": - layoutAlgorithm = DanmakuLayoutAlgorithm.SYNC; - break; - case "Async": - layoutAlgorithm = DanmakuLayoutAlgorithm.ASYNC; - break; - default: - layoutAlgorithm = DanmakuLayoutAlgorithm.SYNC; - break; - } + "Sync" => DanmakuLayoutAlgorithm.Sync, + "Async" => DanmakuLayoutAlgorithm.Async, + _ => DanmakuLayoutAlgorithm.Sync + }; - bool isSucceed = SettingsManager.GetInstance().SetDanmakuLayoutAlgorithm(layoutAlgorithm); + var isSucceed = SettingsManager.GetInstance().SetDanmakuLayoutAlgorithm(layoutAlgorithm); PublishTip(isSucceed); if (isSucceed) @@ -370,15 +347,15 @@ public class ViewDanmakuViewModel : ViewModelBase { switch (layoutAlgorithm) { - case DanmakuLayoutAlgorithm.SYNC: + case DanmakuLayoutAlgorithm.Sync: Sync = true; Async = false; break; - case DanmakuLayoutAlgorithm.ASYNC: + case DanmakuLayoutAlgorithm.Async: Sync = false; Async = true; break; - case DanmakuLayoutAlgorithm.NONE: + case DanmakuLayoutAlgorithm.None: Sync = false; Async = false; break; @@ -393,18 +370,11 @@ public class ViewDanmakuViewModel : ViewModelBase /// private void PublishTip(bool isSucceed) { - if (isOnNavigatedTo) + if (_isOnNavigatedTo) { return; } - if (isSucceed) - { - EventAggregator.GetEvent().Publish(DictionaryResource.GetString("TipSettingUpdated")); - } - else - { - EventAggregator.GetEvent().Publish(DictionaryResource.GetString("TipSettingFailed")); - } + EventAggregator.GetEvent().Publish(isSucceed ? DictionaryResource.GetString("TipSettingUpdated") : DictionaryResource.GetString("TipSettingFailed")); } } \ No newline at end of file diff --git a/DownKyi/ViewModels/Settings/ViewNetworkViewModel.cs b/DownKyi/ViewModels/Settings/ViewNetworkViewModel.cs index 8a1396f..fe1259c 100644 --- a/DownKyi/ViewModels/Settings/ViewNetworkViewModel.cs +++ b/DownKyi/ViewModels/Settings/ViewNetworkViewModel.cs @@ -19,232 +19,232 @@ public class ViewNetworkViewModel : ViewModelBase { public const string Tag = "PageSettingsNetwork"; - private bool isOnNavigatedTo; + private bool _isOnNavigatedTo; #region 页面属性申明 - private bool useSSL; + private bool _useSsl; - public bool UseSSL + public bool UseSsl { - get => useSSL; - set => SetProperty(ref useSSL, value); + get => _useSsl; + set => SetProperty(ref _useSsl, value); } - private string userAgent; + private string _userAgent; public string UserAgent { - get => userAgent; - set => SetProperty(ref userAgent, value); + get => _userAgent; + set => SetProperty(ref _userAgent, value); } - private bool builtin; + private bool _builtin; public bool Builtin { - get => builtin; - set => SetProperty(ref builtin, value); + get => _builtin; + set => SetProperty(ref _builtin, value); } - private bool aria2c; + private bool _aria2C; - public bool Aria2c + public bool Aria2C { - get => aria2c; - set => SetProperty(ref aria2c, value); + get => _aria2C; + set => SetProperty(ref _aria2C, value); } - private bool customAria2c; + private bool _customAria2C; - public bool CustomAria2c + public bool CustomAria2C { - get => customAria2c; - set => SetProperty(ref customAria2c, value); + get => _customAria2C; + set => SetProperty(ref _customAria2C, value); } - private List maxCurrentDownloads; + private List _maxCurrentDownloads; public List MaxCurrentDownloads { - get => maxCurrentDownloads; - set => SetProperty(ref maxCurrentDownloads, value); + get => _maxCurrentDownloads; + set => SetProperty(ref _maxCurrentDownloads, value); } - private int selectedMaxCurrentDownload; + private int _selectedMaxCurrentDownload; public int SelectedMaxCurrentDownload { - get => selectedMaxCurrentDownload; - set => SetProperty(ref selectedMaxCurrentDownload, value); + get => _selectedMaxCurrentDownload; + set => SetProperty(ref _selectedMaxCurrentDownload, value); } - private List splits; + private List _splits; public List Splits { - get => splits; - set => SetProperty(ref splits, value); + get => _splits; + set => SetProperty(ref _splits, value); } - private int selectedSplit; + private int _selectedSplit; public int SelectedSplit { - get => selectedSplit; - set => SetProperty(ref selectedSplit, value); + get => _selectedSplit; + set => SetProperty(ref _selectedSplit, value); } - private bool isHttpProxy; + private bool _isHttpProxy; public bool IsHttpProxy { - get => isHttpProxy; - set => SetProperty(ref isHttpProxy, value); + get => _isHttpProxy; + set => SetProperty(ref _isHttpProxy, value); } - private string httpProxy; + private string _httpProxy; public string HttpProxy { - get => httpProxy; - set => SetProperty(ref httpProxy, value); + get => _httpProxy; + set => SetProperty(ref _httpProxy, value); } - private int httpProxyPort; + private int _httpProxyPort; public int HttpProxyPort { - get => httpProxyPort; - set => SetProperty(ref httpProxyPort, value); + get => _httpProxyPort; + set => SetProperty(ref _httpProxyPort, value); } - private string ariaHost; + private string _ariaHost; public string AriaHost { - get => ariaHost; - set => SetProperty(ref ariaHost, value); + get => _ariaHost; + set => SetProperty(ref _ariaHost, value); } - private int ariaListenPort; + private int _ariaListenPort; public int AriaListenPort { - get => ariaListenPort; - set => SetProperty(ref ariaListenPort, value); + get => _ariaListenPort; + set => SetProperty(ref _ariaListenPort, value); } - private string ariaToken; + private string _ariaToken; public string AriaToken { - get => ariaToken; - set => SetProperty(ref ariaToken, value); + get => _ariaToken; + set => SetProperty(ref _ariaToken, value); } - private List ariaLogLevels; + private List _ariaLogLevels; public List AriaLogLevels { - get => ariaLogLevels; - set => SetProperty(ref ariaLogLevels, value); + get => _ariaLogLevels; + set => SetProperty(ref _ariaLogLevels, value); } - private string selectedAriaLogLevel; + private string _selectedAriaLogLevel; public string SelectedAriaLogLevel { - get => selectedAriaLogLevel; - set => SetProperty(ref selectedAriaLogLevel, value); + get => _selectedAriaLogLevel; + set => SetProperty(ref _selectedAriaLogLevel, value); } - private List ariaMaxConcurrentDownloads; + private List _ariaMaxConcurrentDownloads; public List AriaMaxConcurrentDownloads { - get => ariaMaxConcurrentDownloads; - set => SetProperty(ref ariaMaxConcurrentDownloads, value); + get => _ariaMaxConcurrentDownloads; + set => SetProperty(ref _ariaMaxConcurrentDownloads, value); } - private int selectedAriaMaxConcurrentDownload; + private int _selectedAriaMaxConcurrentDownload; public int SelectedAriaMaxConcurrentDownload { - get => selectedAriaMaxConcurrentDownload; - set => SetProperty(ref selectedAriaMaxConcurrentDownload, value); + get => _selectedAriaMaxConcurrentDownload; + set => SetProperty(ref _selectedAriaMaxConcurrentDownload, value); } - private List ariaSplits; + private List _ariaSplits; public List AriaSplits { - get => ariaSplits; - set => SetProperty(ref ariaSplits, value); + get => _ariaSplits; + set => SetProperty(ref _ariaSplits, value); } - private int selectedAriaSplit; + private int _selectedAriaSplit; public int SelectedAriaSplit { - get => selectedAriaSplit; - set => SetProperty(ref selectedAriaSplit, value); + get => _selectedAriaSplit; + set => SetProperty(ref _selectedAriaSplit, value); } - private int ariaMaxOverallDownloadLimit; + private int _ariaMaxOverallDownloadLimit; public int AriaMaxOverallDownloadLimit { - get => ariaMaxOverallDownloadLimit; - set => SetProperty(ref ariaMaxOverallDownloadLimit, value); + get => _ariaMaxOverallDownloadLimit; + set => SetProperty(ref _ariaMaxOverallDownloadLimit, value); } - private int ariaMaxDownloadLimit; + private int _ariaMaxDownloadLimit; public int AriaMaxDownloadLimit { - get => ariaMaxDownloadLimit; - set => SetProperty(ref ariaMaxDownloadLimit, value); + get => _ariaMaxDownloadLimit; + set => SetProperty(ref _ariaMaxDownloadLimit, value); } - private bool isAriaHttpProxy; + private bool _isAriaHttpProxy; public bool IsAriaHttpProxy { - get => isAriaHttpProxy; - set => SetProperty(ref isAriaHttpProxy, value); + get => _isAriaHttpProxy; + set => SetProperty(ref _isAriaHttpProxy, value); } - private string ariaHttpProxy; + private string _ariaHttpProxy; public string AriaHttpProxy { - get => ariaHttpProxy; - set => SetProperty(ref ariaHttpProxy, value); + get => _ariaHttpProxy; + set => SetProperty(ref _ariaHttpProxy, value); } - private int ariaHttpProxyPort; + private int _ariaHttpProxyPort; public int AriaHttpProxyPort { - get => ariaHttpProxyPort; - set => SetProperty(ref ariaHttpProxyPort, value); + get => _ariaHttpProxyPort; + set => SetProperty(ref _ariaHttpProxyPort, value); } - private List ariaFileAllocations; + private List _ariaFileAllocations; public List AriaFileAllocations { - get => ariaFileAllocations; - set => SetProperty(ref ariaFileAllocations, value); + get => _ariaFileAllocations; + set => SetProperty(ref _ariaFileAllocations, value); } - private string selectedAriaFileAllocation; + private string _selectedAriaFileAllocation; public string SelectedAriaFileAllocation { - get => selectedAriaFileAllocation; - set => SetProperty(ref selectedAriaFileAllocation, value); + get => _selectedAriaFileAllocation; + set => SetProperty(ref _selectedAriaFileAllocation, value); } #endregion @@ -256,14 +256,14 @@ public class ViewNetworkViewModel : ViewModelBase // builtin同时下载数 MaxCurrentDownloads = new List(); - for (int i = 1; i <= 10; i++) + for (var i = 1; i <= 10; i++) { MaxCurrentDownloads.Add(i); } // builtin最大线程数 Splits = new List(); - for (int i = 1; i <= 10; i++) + for (var i = 1; i <= 10; i++) { Splits.Add(i); } @@ -280,14 +280,14 @@ public class ViewNetworkViewModel : ViewModelBase // Aria同时下载数 AriaMaxConcurrentDownloads = new List(); - for (int i = 1; i <= 10; i++) + for (var i = 1; i <= 10; i++) { AriaMaxConcurrentDownloads.Add(i); } // Aria最大线程数 AriaSplits = new List(); - for (int i = 1; i <= 10; i++) + for (var i = 1; i <= 10; i++) { AriaSplits.Add(i); } @@ -311,11 +311,11 @@ public class ViewNetworkViewModel : ViewModelBase { base.OnNavigatedTo(navigationContext); - isOnNavigatedTo = true; + _isOnNavigatedTo = true; // 启用https - var useSsl = SettingsManager.GetInstance().UseSSL(); - UseSSL = useSsl == AllowStatus.YES; + var useSsl = SettingsManager.GetInstance().GetUseSsl(); + UseSsl = useSsl == AllowStatus.Yes; // UserAgent UserAgent = SettingsManager.GetInstance().GetUserAgent(); @@ -324,16 +324,16 @@ public class ViewNetworkViewModel : ViewModelBase var downloader = SettingsManager.GetInstance().GetDownloader(); switch (downloader) { - case Core.Settings.Downloader.NOT_SET: + case Core.Settings.Downloader.NotSet: break; - case Core.Settings.Downloader.BUILT_IN: + case Core.Settings.Downloader.BuiltIn: Builtin = true; break; - case Core.Settings.Downloader.ARIA: - Aria2c = true; + case Core.Settings.Downloader.Aria: + Aria2C = true; break; - case Core.Settings.Downloader.CUSTOM_ARIA: - CustomAria2c = true; + case Core.Settings.Downloader.CustomAria: + CustomAria2C = true; break; } @@ -344,8 +344,8 @@ public class ViewNetworkViewModel : ViewModelBase SelectedSplit = SettingsManager.GetInstance().GetSplit(); // 是否开启builtin http代理 - var isHttpProxy = SettingsManager.GetInstance().IsHttpProxy(); - IsHttpProxy = isHttpProxy == AllowStatus.YES; + var isHttpProxy = SettingsManager.GetInstance().GetIsHttpProxy(); + IsHttpProxy = isHttpProxy == AllowStatus.Yes; // builtin的http代理的地址 HttpProxy = SettingsManager.GetInstance().GetHttpProxy(); @@ -379,8 +379,8 @@ public class ViewNetworkViewModel : ViewModelBase AriaMaxDownloadLimit = SettingsManager.GetInstance().GetAriaMaxDownloadLimit(); // 是否开启Aria http代理 - var isAriaHttpProxy = SettingsManager.GetInstance().IsAriaHttpProxy(); - IsAriaHttpProxy = isAriaHttpProxy == AllowStatus.YES; + var isAriaHttpProxy = SettingsManager.GetInstance().GetIsAriaHttpProxy(); + IsAriaHttpProxy = isAriaHttpProxy == AllowStatus.Yes; // Aria的http代理的地址 AriaHttpProxy = SettingsManager.GetInstance().GetAriaHttpProxy(); @@ -392,33 +392,31 @@ public class ViewNetworkViewModel : ViewModelBase var ariaFileAllocation = SettingsManager.GetInstance().GetAriaFileAllocation(); SelectedAriaFileAllocation = ariaFileAllocation.ToString("G"); - isOnNavigatedTo = false; + _isOnNavigatedTo = false; } #region 命令申明 // 是否启用https事件 - private DelegateCommand useSSLCommand; + private DelegateCommand? _useSslCommand; - public DelegateCommand UseSSLCommand => - useSSLCommand ?? (useSSLCommand = new DelegateCommand(ExecuteUseSSLCommand)); + public DelegateCommand UseSslCommand => _useSslCommand ??= new DelegateCommand(ExecuteUseSslCommand); /// /// 是否启用https事件 /// - private void ExecuteUseSSLCommand() + private void ExecuteUseSslCommand() { - var useSSL = UseSSL ? AllowStatus.YES : AllowStatus.NO; + var useSsl = UseSsl ? AllowStatus.Yes : AllowStatus.No; - var isSucceed = SettingsManager.GetInstance().UseSSL(useSSL); + var isSucceed = SettingsManager.GetInstance().SetUseSsl(useSsl); PublishTip(isSucceed); } // 设置UserAgent事件 - private DelegateCommand userAgentCommand; + private DelegateCommand? _userAgentCommand; - public DelegateCommand UserAgentCommand => - userAgentCommand ?? (userAgentCommand = new DelegateCommand(ExecuteUserAgentCommand)); + public DelegateCommand UserAgentCommand => _userAgentCommand ??= new DelegateCommand(ExecuteUserAgentCommand); /// /// 设置UserAgent事件 @@ -430,12 +428,9 @@ public class ViewNetworkViewModel : ViewModelBase } // 下载器选择事件 - private DelegateCommand selectDownloaderCommand; + private DelegateCommand? _selectDownloaderCommand; - public DelegateCommand SelectDownloaderCommand => selectDownloaderCommand ?? - (selectDownloaderCommand = - new DelegateCommand( - ExecuteSelectDownloaderCommand)); + public DelegateCommand SelectDownloaderCommand => _selectDownloaderCommand ??= new DelegateCommand(ExecuteSelectDownloaderCommand); /// /// 下载器选择事件 @@ -447,13 +442,13 @@ public class ViewNetworkViewModel : ViewModelBase switch (parameter) { case "Builtin": - downloader = Core.Settings.Downloader.BUILT_IN; + downloader = Core.Settings.Downloader.BuiltIn; break; case "Aria2c": - downloader = Core.Settings.Downloader.ARIA; + downloader = Core.Settings.Downloader.Aria; break; case "CustomAria2c": - downloader = Core.Settings.Downloader.CUSTOM_ARIA; + downloader = Core.Settings.Downloader.CustomAria; break; default: downloader = SettingsManager.GetInstance().GetDownloader(); @@ -478,12 +473,9 @@ public class ViewNetworkViewModel : ViewModelBase } // builtin同时下载数事件 - private DelegateCommand maxCurrentDownloadsCommand; + private DelegateCommand? _maxCurrentDownloadsCommand; - public DelegateCommand MaxCurrentDownloadsCommand => maxCurrentDownloadsCommand ?? - (maxCurrentDownloadsCommand = - new DelegateCommand( - ExecuteMaxCurrentDownloadsCommand)); + public DelegateCommand MaxCurrentDownloadsCommand => _maxCurrentDownloadsCommand ??= new DelegateCommand(ExecuteMaxCurrentDownloadsCommand); /// /// builtin同时下载数事件 @@ -498,10 +490,9 @@ public class ViewNetworkViewModel : ViewModelBase } // builtin最大线程数事件 - private DelegateCommand splitsCommand; + private DelegateCommand? _splitsCommand; - public DelegateCommand SplitsCommand => - splitsCommand ?? (splitsCommand = new DelegateCommand(ExecuteSplitsCommand)); + public DelegateCommand SplitsCommand => _splitsCommand ??= new DelegateCommand(ExecuteSplitsCommand); /// /// builtin最大线程数事件 @@ -516,27 +507,25 @@ public class ViewNetworkViewModel : ViewModelBase } // 是否开启builtin http代理事件 - private DelegateCommand isHttpProxyCommand; + private DelegateCommand? _isHttpProxyCommand; - public DelegateCommand IsHttpProxyCommand => - isHttpProxyCommand ?? (isHttpProxyCommand = new DelegateCommand(ExecuteIsHttpProxyCommand)); + public DelegateCommand IsHttpProxyCommand => _isHttpProxyCommand ??= new DelegateCommand(ExecuteIsHttpProxyCommand); /// /// 是否开启builtin http代理事件 /// private void ExecuteIsHttpProxyCommand() { - var isHttpProxy = IsHttpProxy ? AllowStatus.YES : AllowStatus.NO; + var isHttpProxy = IsHttpProxy ? AllowStatus.Yes : AllowStatus.No; - var isSucceed = SettingsManager.GetInstance().IsHttpProxy(isHttpProxy); + var isSucceed = SettingsManager.GetInstance().SetIsHttpProxy(isHttpProxy); PublishTip(isSucceed); } // builtin的http代理的地址事件 - private DelegateCommand httpProxyCommand; + private DelegateCommand? _httpProxyCommand; - public DelegateCommand HttpProxyCommand => - httpProxyCommand ?? (httpProxyCommand = new DelegateCommand(ExecuteHttpProxyCommand)); + public DelegateCommand HttpProxyCommand => _httpProxyCommand ??= new DelegateCommand(ExecuteHttpProxyCommand); /// /// builtin的http代理的地址事件 @@ -549,12 +538,9 @@ public class ViewNetworkViewModel : ViewModelBase } // builtin的http代理的端口事件 - private DelegateCommand httpProxyPortCommand; + private DelegateCommand? _httpProxyPortCommand; - public DelegateCommand HttpProxyPortCommand => httpProxyPortCommand ?? - (httpProxyPortCommand = - new DelegateCommand( - ExecuteHttpProxyPortCommand)); + public DelegateCommand HttpProxyPortCommand => _httpProxyPortCommand ??= new DelegateCommand(ExecuteHttpProxyPortCommand); /// /// builtin的http代理的端口事件 @@ -570,10 +556,9 @@ public class ViewNetworkViewModel : ViewModelBase } // Aria服务器host事件 - private DelegateCommand ariaHostCommand; + private DelegateCommand? _ariaHostCommand; - public DelegateCommand AriaHostCommand => - ariaHostCommand ?? (ariaHostCommand = new DelegateCommand(ExecuteAriaHostCommand)); + public DelegateCommand AriaHostCommand => _ariaHostCommand ??= new DelegateCommand(ExecuteAriaHostCommand); /// /// Aria服务器host事件 @@ -587,12 +572,9 @@ public class ViewNetworkViewModel : ViewModelBase } // Aria服务器端口事件 - private DelegateCommand ariaListenPortCommand; + private DelegateCommand? _ariaListenPortCommand; - public DelegateCommand AriaListenPortCommand => ariaListenPortCommand ?? - (ariaListenPortCommand = - new DelegateCommand( - ExecuteAriaListenPortCommand)); + public DelegateCommand AriaListenPortCommand => _ariaListenPortCommand ??= new DelegateCommand(ExecuteAriaListenPortCommand); /// /// Aria服务器端口事件 @@ -608,10 +590,9 @@ public class ViewNetworkViewModel : ViewModelBase } // Aria服务器token事件 - private DelegateCommand ariaTokenCommand; + private DelegateCommand? _ariaTokenCommand; - public DelegateCommand AriaTokenCommand => - ariaTokenCommand ?? (ariaTokenCommand = new DelegateCommand(ExecuteAriaTokenCommand)); + public DelegateCommand AriaTokenCommand => _ariaTokenCommand ??= new DelegateCommand(ExecuteAriaTokenCommand); /// /// Aria服务器token事件 @@ -625,12 +606,9 @@ public class ViewNetworkViewModel : ViewModelBase } // Aria的日志等级事件 - private DelegateCommand ariaLogLevelsCommand; + private DelegateCommand? _ariaLogLevelsCommand; - public DelegateCommand AriaLogLevelsCommand => ariaLogLevelsCommand ?? - (ariaLogLevelsCommand = - new DelegateCommand( - ExecuteAriaLogLevelsCommand)); + public DelegateCommand AriaLogLevelsCommand => _ariaLogLevelsCommand ??= new DelegateCommand(ExecuteAriaLogLevelsCommand); /// /// Aria的日志等级事件 @@ -653,51 +631,47 @@ public class ViewNetworkViewModel : ViewModelBase } // Aria同时下载数事件 - private DelegateCommand ariaMaxConcurrentDownloadsCommand; + private DelegateCommand? _ariaMaxConcurrentDownloadsCommand; - public DelegateCommand AriaMaxConcurrentDownloadsCommand => ariaMaxConcurrentDownloadsCommand ?? - (ariaMaxConcurrentDownloadsCommand = - new DelegateCommand( - ExecuteAriaMaxConcurrentDownloadsCommand)); + public DelegateCommand AriaMaxConcurrentDownloadsCommand => + _ariaMaxConcurrentDownloadsCommand ??= new DelegateCommand(ExecuteAriaMaxConcurrentDownloadsCommand); /// /// Aria同时下载数事件 /// /// - private void ExecuteAriaMaxConcurrentDownloadsCommand(object parameter) + private void ExecuteAriaMaxConcurrentDownloadsCommand(object? parameter) { - // SelectedAriaMaxConcurrentDownload = (int)parameter; + if (parameter == null) return; + SelectedAriaMaxConcurrentDownload = (int)parameter; var isSucceed = SettingsManager.GetInstance().SetMaxCurrentDownloads(SelectedAriaMaxConcurrentDownload); PublishTip(isSucceed); } // Aria最大线程数事件 - private DelegateCommand ariaSplitsCommand; + private DelegateCommand? _ariaSplitsCommand; - public DelegateCommand AriaSplitsCommand => ariaSplitsCommand ?? - (ariaSplitsCommand = - new DelegateCommand(ExecuteAriaSplitsCommand)); + public DelegateCommand AriaSplitsCommand => _ariaSplitsCommand ??= new DelegateCommand(ExecuteAriaSplitsCommand); /// /// Aria最大线程数事件 /// /// - private void ExecuteAriaSplitsCommand(object parameter) + private void ExecuteAriaSplitsCommand(object? parameter) { - // SelectedAriaSplit = (int)parameter; + if (parameter == null) return; + SelectedAriaSplit = (int)parameter; var isSucceed = SettingsManager.GetInstance().SetAriaSplit(SelectedAriaSplit); PublishTip(isSucceed); } // Aria下载速度限制事件 - private DelegateCommand ariaMaxOverallDownloadLimitCommand; + private DelegateCommand? _ariaMaxOverallDownloadLimitCommand; - public DelegateCommand AriaMaxOverallDownloadLimitCommand => ariaMaxOverallDownloadLimitCommand ?? - (ariaMaxOverallDownloadLimitCommand = - new DelegateCommand( - ExecuteAriaMaxOverallDownloadLimitCommand)); + public DelegateCommand AriaMaxOverallDownloadLimitCommand => _ariaMaxOverallDownloadLimitCommand ??= new DelegateCommand( + ExecuteAriaMaxOverallDownloadLimitCommand); /// /// Aria下载速度限制事件 @@ -713,12 +687,9 @@ public class ViewNetworkViewModel : ViewModelBase } // Aria下载单文件速度限制事件 - private DelegateCommand ariaMaxDownloadLimitCommand; + private DelegateCommand? _ariaMaxDownloadLimitCommand; - public DelegateCommand AriaMaxDownloadLimitCommand => ariaMaxDownloadLimitCommand ?? - (ariaMaxDownloadLimitCommand = - new DelegateCommand( - ExecuteAriaMaxDownloadLimitCommand)); + public DelegateCommand AriaMaxDownloadLimitCommand => _ariaMaxDownloadLimitCommand ??= new DelegateCommand(ExecuteAriaMaxDownloadLimitCommand); /// /// Aria下载单文件速度限制事件 @@ -726,38 +697,33 @@ public class ViewNetworkViewModel : ViewModelBase /// private void ExecuteAriaMaxDownloadLimitCommand(string parameter) { - int downloadLimit = (int)Number.GetInt(parameter); + var downloadLimit = (int)Number.GetInt(parameter); AriaMaxDownloadLimit = downloadLimit; - bool isSucceed = SettingsManager.GetInstance().SetAriaMaxDownloadLimit(AriaMaxDownloadLimit); + var isSucceed = SettingsManager.GetInstance().SetAriaMaxDownloadLimit(AriaMaxDownloadLimit); PublishTip(isSucceed); } // 是否开启Aria http代理事件 - private DelegateCommand isAriaHttpProxyCommand; + private DelegateCommand? _isAriaHttpProxyCommand; - public DelegateCommand IsAriaHttpProxyCommand => isAriaHttpProxyCommand ?? - (isAriaHttpProxyCommand = - new DelegateCommand(ExecuteIsAriaHttpProxyCommand)); + public DelegateCommand IsAriaHttpProxyCommand => _isAriaHttpProxyCommand ??= new DelegateCommand(ExecuteIsAriaHttpProxyCommand); /// /// 是否开启Aria http代理事件 /// private void ExecuteIsAriaHttpProxyCommand() { - AllowStatus isAriaHttpProxy = IsAriaHttpProxy ? AllowStatus.YES : AllowStatus.NO; + var isAriaHttpProxy = IsAriaHttpProxy ? AllowStatus.Yes : AllowStatus.No; - bool isSucceed = SettingsManager.GetInstance().IsAriaHttpProxy(isAriaHttpProxy); + var isSucceed = SettingsManager.GetInstance().SetIsAriaHttpProxy(isAriaHttpProxy); PublishTip(isSucceed); } // Aria的http代理的地址事件 - private DelegateCommand ariaHttpProxyCommand; + private DelegateCommand? _ariaHttpProxyCommand; - public DelegateCommand AriaHttpProxyCommand => ariaHttpProxyCommand ?? - (ariaHttpProxyCommand = - new DelegateCommand( - ExecuteAriaHttpProxyCommand)); + public DelegateCommand AriaHttpProxyCommand => _ariaHttpProxyCommand ??= new DelegateCommand(ExecuteAriaHttpProxyCommand); /// /// Aria的http代理的地址事件 @@ -765,17 +731,14 @@ public class ViewNetworkViewModel : ViewModelBase /// private void ExecuteAriaHttpProxyCommand(string parameter) { - bool isSucceed = SettingsManager.GetInstance().SetAriaHttpProxy(parameter); + var isSucceed = SettingsManager.GetInstance().SetAriaHttpProxy(parameter); PublishTip(isSucceed); } // Aria的http代理的端口事件 - private DelegateCommand ariaHttpProxyPortCommand; + private DelegateCommand? _ariaHttpProxyPortCommand; - public DelegateCommand AriaHttpProxyPortCommand => ariaHttpProxyPortCommand ?? - (ariaHttpProxyPortCommand = - new DelegateCommand( - ExecuteAriaHttpProxyPortCommand)); + public DelegateCommand AriaHttpProxyPortCommand => _ariaHttpProxyPortCommand ??= new DelegateCommand(ExecuteAriaHttpProxyPortCommand); /// /// Aria的http代理的端口事件 @@ -783,20 +746,17 @@ public class ViewNetworkViewModel : ViewModelBase /// private void ExecuteAriaHttpProxyPortCommand(string parameter) { - int httpProxyPort = (int)Number.GetInt(parameter); + var httpProxyPort = (int)Number.GetInt(parameter); AriaHttpProxyPort = httpProxyPort; - bool isSucceed = SettingsManager.GetInstance().SetAriaHttpProxyListenPort(AriaHttpProxyPort); + var isSucceed = SettingsManager.GetInstance().SetAriaHttpProxyListenPort(AriaHttpProxyPort); PublishTip(isSucceed); } // Aria文件预分配事件 - private DelegateCommand ariaFileAllocationsCommand; + private DelegateCommand? _ariaFileAllocationsCommand; - public DelegateCommand AriaFileAllocationsCommand => ariaFileAllocationsCommand ?? - (ariaFileAllocationsCommand = - new DelegateCommand( - ExecuteAriaFileAllocationsCommand)); + public DelegateCommand AriaFileAllocationsCommand => _ariaFileAllocationsCommand ??= new DelegateCommand(ExecuteAriaFileAllocationsCommand); /// /// Aria文件预分配事件 @@ -804,7 +764,7 @@ public class ViewNetworkViewModel : ViewModelBase /// private void ExecuteAriaFileAllocationsCommand(string parameter) { - AriaConfigFileAllocation ariaFileAllocation = parameter switch + var ariaFileAllocation = parameter switch { "NONE" => AriaConfigFileAllocation.NONE, "PREALLOC" => AriaConfigFileAllocation.PREALLOC, @@ -824,18 +784,11 @@ public class ViewNetworkViewModel : ViewModelBase /// private void PublishTip(bool isSucceed) { - if (isOnNavigatedTo) + if (_isOnNavigatedTo) { return; } - if (isSucceed) - { - EventAggregator.GetEvent().Publish(DictionaryResource.GetString("TipSettingUpdated")); - } - else - { - EventAggregator.GetEvent().Publish(DictionaryResource.GetString("TipSettingFailed")); - } + EventAggregator.GetEvent().Publish(isSucceed ? DictionaryResource.GetString("TipSettingUpdated") : DictionaryResource.GetString("TipSettingFailed")); } } \ No newline at end of file diff --git a/DownKyi/ViewModels/Settings/ViewVideoViewModel.cs b/DownKyi/ViewModels/Settings/ViewVideoViewModel.cs index 8dfe9dc..7abbdaa 100644 --- a/DownKyi/ViewModels/Settings/ViewVideoViewModel.cs +++ b/DownKyi/ViewModels/Settings/ViewVideoViewModel.cs @@ -19,32 +19,32 @@ public class ViewVideoViewModel : ViewModelBase { public const string Tag = "PageSettingsVideo"; - private bool isOnNavigatedTo; + private bool _isOnNavigatedTo; #region 页面属性申明 - private List videoCodecs; + private List _videoCodecs; public List VideoCodecs { - get => videoCodecs; - set => SetProperty(ref videoCodecs, value); + get => _videoCodecs; + set => SetProperty(ref _videoCodecs, value); } - private Quality selectedVideoCodec; + private Quality _selectedVideoCodec; public Quality SelectedVideoCodec { - get => selectedVideoCodec; - set => SetProperty(ref selectedVideoCodec, value); + get => _selectedVideoCodec; + set => SetProperty(ref _selectedVideoCodec, value); } - private List videoQualityList; + private List _videoQualityList; public List VideoQualityList { - get => videoQualityList; - set => SetProperty(ref videoQualityList, value); + get => _videoQualityList; + set => SetProperty(ref _videoQualityList, value); } private Quality _selectedVideoQuality; @@ -94,7 +94,7 @@ public class ViewVideoViewModel : ViewModelBase get => _isTranscodingFlvToMp4; set => SetProperty(ref _isTranscodingFlvToMp4, value); } - + private bool _isTranscodingAacToMp3; public bool IsTranscodingAacToMp3 @@ -284,10 +284,10 @@ public class ViewVideoViewModel : ViewModelBase // 文件命名中的序号格式 OrderFormatList = new List { - new() { Name = DictionaryResource.GetString("OrderFormatNatural"), OrderFormat = OrderFormat.NATURAL }, + new() { Name = DictionaryResource.GetString("OrderFormatNatural"), OrderFormat = OrderFormat.Natural }, new() { - Name = DictionaryResource.GetString("OrderFormatLeadingZeros"), OrderFormat = OrderFormat.LEADING_ZEROS + Name = DictionaryResource.GetString("OrderFormatLeadingZeros"), OrderFormat = OrderFormat.LeadingZeros }, }; @@ -302,7 +302,7 @@ public class ViewVideoViewModel : ViewModelBase { base.OnNavigatedTo(navigationContext); - isOnNavigatedTo = true; + _isOnNavigatedTo = true; // 优先下载的视频编码 var videoCodecs = SettingsManager.GetInstance().GetVideoCodecs(); @@ -322,16 +322,16 @@ public class ViewVideoViewModel : ViewModelBase SelectedVideoParseType = VideoParseTypeList.FirstOrDefault(t => t.Id == videoParseType); // 是否下载flv视频后转码为mp4 - var isTranscodingFlvToMp4 = SettingsManager.GetInstance().IsTranscodingFlvToMp4(); - IsTranscodingFlvToMp4 = isTranscodingFlvToMp4 == AllowStatus.YES; - + var isTranscodingFlvToMp4 = SettingsManager.GetInstance().GetIsTranscodingFlvToMp4(); + IsTranscodingFlvToMp4 = isTranscodingFlvToMp4 == AllowStatus.Yes; + // 是否下载aac音频后转码为mp3 - var isTranscodingAacToMp3 = SettingsManager.GetInstance().IsTranscodingAacToMp3(); - IsTranscodingAacToMp3 = isTranscodingAacToMp3 == AllowStatus.YES; + var isTranscodingAacToMp3 = SettingsManager.GetInstance().GetIsTranscodingAacToMp3(); + IsTranscodingAacToMp3 = isTranscodingAacToMp3 == AllowStatus.Yes; // 是否使用默认下载目录 - var isUseSaveVideoRootPath = SettingsManager.GetInstance().IsUseSaveVideoRootPath(); - IsUseDefaultDirectory = isUseSaveVideoRootPath == AllowStatus.YES; + var isUseSaveVideoRootPath = SettingsManager.GetInstance().GetIsUseSaveVideoRootPath(); + IsUseDefaultDirectory = isUseSaveVideoRootPath == AllowStatus.Yes; // 默认下载目录 SaveVideoDirectory = SettingsManager.GetInstance().GetSaveVideoRootPath(); @@ -367,10 +367,10 @@ public class ViewVideoViewModel : ViewModelBase SelectedFileNamePartTimeFormat = SettingsManager.GetInstance().GetFileNamePartTimeFormat(); // 文件命名中的序号格式 - OrderFormat orderFormat = SettingsManager.GetInstance().GetOrderFormat(); + var orderFormat = SettingsManager.GetInstance().GetOrderFormat(); OrderFormatDisplay = OrderFormatList.FirstOrDefault(t => { return t.OrderFormat == orderFormat; }); - isOnNavigatedTo = false; + _isOnNavigatedTo = false; } #region 命令申明 @@ -408,12 +408,12 @@ public class ViewVideoViewModel : ViewModelBase /// private void ExecuteVideoQualityCommand(object parameter) { - if (!(parameter is Quality resolution)) + if (parameter is not Quality resolution) { return; } - bool isSucceed = SettingsManager.GetInstance().SetQuality(resolution.Id); + var isSucceed = SettingsManager.GetInstance().SetQuality(resolution.Id); PublishTip(isSucceed); } @@ -428,12 +428,12 @@ public class ViewVideoViewModel : ViewModelBase /// private void ExecuteAudioQualityCommand(object parameter) { - if (!(parameter is Quality quality)) + if (parameter is not Quality quality) { return; } - bool isSucceed = SettingsManager.GetInstance().SetAudioQuality(quality.Id); + var isSucceed = SettingsManager.GetInstance().SetAudioQuality(quality.Id); PublishTip(isSucceed); } @@ -468,25 +468,25 @@ public class ViewVideoViewModel : ViewModelBase /// private void ExecuteIsTranscodingFlvToMp4Command() { - var isTranscodingFlvToMp4 = IsTranscodingFlvToMp4 ? AllowStatus.YES : AllowStatus.NO; + var isTranscodingFlvToMp4 = IsTranscodingFlvToMp4 ? AllowStatus.Yes : AllowStatus.No; - var isSucceed = SettingsManager.GetInstance().IsTranscodingFlvToMp4(isTranscodingFlvToMp4); + var isSucceed = SettingsManager.GetInstance().SetIsTranscodingFlvToMp4(isTranscodingFlvToMp4); PublishTip(isSucceed); } - + // 是否下载aac音频后转码为mp3事件 private DelegateCommand? _isTranscodingAacToMp3Command; - + public DelegateCommand IsTranscodingAacToMp3Command => _isTranscodingAacToMp3Command ??= new DelegateCommand(ExecuteIsTranscodingAacToMp3Command); - + /// /// 是否下载aac音频后转码为mp3事件 /// private void ExecuteIsTranscodingAacToMp3Command() { - var isTranscodingAacToMp3 = IsTranscodingAacToMp3 ? AllowStatus.YES : AllowStatus.NO; - - var isSucceed = SettingsManager.GetInstance().IsTranscodingAacToMp3(isTranscodingAacToMp3); + var isTranscodingAacToMp3 = IsTranscodingAacToMp3 ? AllowStatus.Yes : AllowStatus.No; + + var isSucceed = SettingsManager.GetInstance().SetIsTranscodingAacToMp3(isTranscodingAacToMp3); PublishTip(isSucceed); } @@ -500,9 +500,9 @@ public class ViewVideoViewModel : ViewModelBase /// private void ExecuteIsUseDefaultDirectoryCommand() { - var isUseDefaultDirectory = IsUseDefaultDirectory ? AllowStatus.YES : AllowStatus.NO; + var isUseDefaultDirectory = IsUseDefaultDirectory ? AllowStatus.Yes : AllowStatus.No; - var isSucceed = SettingsManager.GetInstance().IsUseSaveVideoRootPath(isUseDefaultDirectory); + var isSucceed = SettingsManager.GetInstance().SetIsUseSaveVideoRootPath(isUseDefaultDirectory); PublishTip(isSucceed); } @@ -692,7 +692,7 @@ public class ViewVideoViewModel : ViewModelBase return; } - bool isSucceed = SelectedFileName.Remove((DisplayFileNamePart)parameter); + var isSucceed = SelectedFileName.Remove((DisplayFileNamePart)parameter); if (!isSucceed) { PublishTip(isSucceed); @@ -729,11 +729,7 @@ public class ViewVideoViewModel : ViewModelBase SelectedFileName.Add((DisplayFileNamePart)parameter); - var fileName = new List(); - foreach (var item in SelectedFileName) - { - fileName.Add(item.Id); - } + var fileName = SelectedFileName.Select(item => item.Id).ToList(); var isSucceed = SettingsManager.GetInstance().SetFileNameParts(fileName); PublishTip(isSucceed); @@ -882,20 +878,20 @@ public class ViewVideoViewModel : ViewModelBase { var display = item switch { - FileNamePart.ORDER => DictionaryResource.GetString("DisplayOrder"), - FileNamePart.SECTION => DictionaryResource.GetString("DisplaySection"), - FileNamePart.MAIN_TITLE => DictionaryResource.GetString("DisplayMainTitle"), - FileNamePart.PAGE_TITLE => DictionaryResource.GetString("DisplayPageTitle"), - FileNamePart.VIDEO_ZONE => DictionaryResource.GetString("DisplayVideoZone"), - FileNamePart.AUDIO_QUALITY => DictionaryResource.GetString("DisplayAudioQuality"), - FileNamePart.VIDEO_QUALITY => DictionaryResource.GetString("DisplayVideoQuality"), - FileNamePart.VIDEO_CODEC => DictionaryResource.GetString("DisplayVideoCodec"), - FileNamePart.VIDEO_PUBLISH_TIME => DictionaryResource.GetString("DisplayVideoPublishTime"), - FileNamePart.AVID => "avid", - FileNamePart.BVID => "bvid", - FileNamePart.CID => "cid", - FileNamePart.UP_MID => DictionaryResource.GetString("DisplayUpMid"), - FileNamePart.UP_NAME => DictionaryResource.GetString("DisplayUpName"), + FileNamePart.Order => DictionaryResource.GetString("DisplayOrder"), + FileNamePart.Section => DictionaryResource.GetString("DisplaySection"), + FileNamePart.MainTitle => DictionaryResource.GetString("DisplayMainTitle"), + FileNamePart.PageTitle => DictionaryResource.GetString("DisplayPageTitle"), + FileNamePart.VideoZone => DictionaryResource.GetString("DisplayVideoZone"), + FileNamePart.AudioQuality => DictionaryResource.GetString("DisplayAudioQuality"), + FileNamePart.VideoQuality => DictionaryResource.GetString("DisplayVideoQuality"), + FileNamePart.VideoCodec => DictionaryResource.GetString("DisplayVideoCodec"), + FileNamePart.VideoPublishTime => DictionaryResource.GetString("DisplayVideoPublishTime"), + FileNamePart.Avid => "avid", + FileNamePart.Bvid => "bvid", + FileNamePart.Cid => "cid", + FileNamePart.UpMid => DictionaryResource.GetString("DisplayUpMid"), + FileNamePart.UpName => DictionaryResource.GetString("DisplayUpName"), _ => string.Empty }; @@ -918,18 +914,11 @@ public class ViewVideoViewModel : ViewModelBase /// private void PublishTip(bool isSucceed) { - if (isOnNavigatedTo) + if (_isOnNavigatedTo) { return; } - if (isSucceed) - { - EventAggregator.GetEvent().Publish(DictionaryResource.GetString("TipSettingUpdated")); - } - else - { - EventAggregator.GetEvent().Publish(DictionaryResource.GetString("TipSettingFailed")); - } + EventAggregator.GetEvent().Publish(isSucceed ? DictionaryResource.GetString("TipSettingUpdated") : DictionaryResource.GetString("TipSettingFailed")); } } \ No newline at end of file diff --git a/DownKyi/ViewModels/Toolbox/ViewBiliHelperViewModel.cs b/DownKyi/ViewModels/Toolbox/ViewBiliHelperViewModel.cs index 1fa0f7b..1d38fd2 100644 --- a/DownKyi/ViewModels/Toolbox/ViewBiliHelperViewModel.cs +++ b/DownKyi/ViewModels/Toolbox/ViewBiliHelperViewModel.cs @@ -39,9 +39,9 @@ public class ViewBiliHelperViewModel : ViewModelBase set => SetProperty(ref _danmakuUserId, value); } - private string _userMid; + private string? _userMid; - public string UserMid + public string? UserMid { get => _userMid; set => SetProperty(ref _userMid, value); @@ -68,7 +68,7 @@ public class ViewBiliHelperViewModel : ViewModelBase /// private async void ExecuteAvidCommand(string parameter) { - if (parameter == null) + if (string.IsNullOrEmpty(parameter)) { return; } @@ -98,7 +98,7 @@ public class ViewBiliHelperViewModel : ViewModelBase /// private async void ExecuteBvidCommand(string parameter) { - if (parameter == null) + if (string.IsNullOrEmpty(parameter)) { return; } diff --git a/DownKyi/ViewModels/Toolbox/ViewDelogoViewModel.cs b/DownKyi/ViewModels/Toolbox/ViewDelogoViewModel.cs index 3019eaf..e835997 100644 --- a/DownKyi/ViewModels/Toolbox/ViewDelogoViewModel.cs +++ b/DownKyi/ViewModels/Toolbox/ViewDelogoViewModel.cs @@ -19,9 +19,9 @@ public class ViewDelogoViewModel : ViewModelBase #region 页面属性申明 - private string _videoPath; + private string? _videoPath; - public string VideoPath + public string? VideoPath { get => _videoPath; set => SetProperty(ref _videoPath, value); @@ -120,7 +120,7 @@ public class ViewDelogoViewModel : ViewModelBase return; } - if (VideoPath == "") + if (VideoPath is null or "") { EventAggregator.GetEvent().Publish(DictionaryResource.GetString("TipNoSeletedVideo")); return; @@ -158,10 +158,7 @@ public class ViewDelogoViewModel : ViewModelBase { // 执行去水印程序 _isDelogo = true; - FFMpeg.Instance.Delogo(VideoPath, newFileName, LogoX, LogoY, LogoWidth, LogoHeight, output => - { - Status += output + "\n"; - }); + FFMpeg.Instance.Delogo(VideoPath, newFileName, LogoX, LogoY, LogoWidth, LogoHeight, output => { Status += output + "\n"; }); _isDelogo = false; }); } diff --git a/DownKyi/ViewModels/UserSpace/SeasonsSeries.cs b/DownKyi/ViewModels/UserSpace/SeasonsSeries.cs index 3fcd09e..47e9274 100644 --- a/DownKyi/ViewModels/UserSpace/SeasonsSeries.cs +++ b/DownKyi/ViewModels/UserSpace/SeasonsSeries.cs @@ -8,12 +8,12 @@ public class SeasonsSeries : BindableBase { public long Id { get; set; } - private Bitmap cover; + private string _cover; - public Bitmap Cover + public string Cover { - get => cover; - set => SetProperty(ref cover, value); + get => _cover; + set => SetProperty(ref _cover, value); } private VectorImage typeImage; diff --git a/DownKyi/ViewModels/UserSpace/ViewArchiveViewModel.cs b/DownKyi/ViewModels/UserSpace/ViewArchiveViewModel.cs index 57ebb8c..d9fe6ad 100644 --- a/DownKyi/ViewModels/UserSpace/ViewArchiveViewModel.cs +++ b/DownKyi/ViewModels/UserSpace/ViewArchiveViewModel.cs @@ -18,24 +18,24 @@ public class ViewArchiveViewModel : ViewModelBase { public const string Tag = "PageUserSpaceArchive"; - private long mid = -1; + private long _mid = -1; #region 页面属性申明 - private ObservableCollection publicationZones; + private ObservableCollection _publicationZones; public ObservableCollection PublicationZones { - get => publicationZones; - set => SetProperty(ref publicationZones, value); + get => _publicationZones; + set => SetProperty(ref _publicationZones, value); } - private int selectedItem; + private int _selectedItem; public int SelectedItem { - get => selectedItem; - set => SetProperty(ref selectedItem, value); + get => _selectedItem; + set => SetProperty(ref _selectedItem, value); } #endregion @@ -52,12 +52,9 @@ public class ViewArchiveViewModel : ViewModelBase #region 命令申明 // 视频选择事件 - private DelegateCommand publicationZonesCommand; + private DelegateCommand? _publicationZonesCommand; - public DelegateCommand PublicationZonesCommand => publicationZonesCommand ?? - (publicationZonesCommand = - new DelegateCommand( - ExecutePublicationZonesCommand)); + public DelegateCommand PublicationZonesCommand => _publicationZonesCommand ??= new DelegateCommand(ExecutePublicationZonesCommand); /// /// 视频选择事件 @@ -65,21 +62,20 @@ public class ViewArchiveViewModel : ViewModelBase /// private void ExecutePublicationZonesCommand(object parameter) { - if (!(parameter is PublicationZone zone)) + if (parameter is not PublicationZone zone) { return; } - Dictionary data = new Dictionary + var data = new Dictionary { - { "mid", mid }, + { "mid", _mid }, { "tid", zone.Tid }, { "list", PublicationZones.ToList() } }; // 进入视频页面 - NavigateToView.NavigationView(EventAggregator, ViewPublicationViewModel.Tag, ViewUserSpaceViewModel.Tag, - data); + NavigateToView.NavigationView(EventAggregator, ViewPublicationViewModel.Tag, ViewUserSpaceViewModel.Tag, data); SelectedItem = -1; } @@ -113,15 +109,15 @@ public class ViewArchiveViewModel : ViewModelBase } // 传入mid - mid = navigationContext.Parameters.GetValue("mid"); + _mid = navigationContext.Parameters.GetValue("mid"); - int VideoCount = 0; + var videoCount = 0; foreach (var zone in parameter) { - VideoCount += zone.Count; - string iconKey = VideoZoneIcon.Instance().GetZoneImageKey(zone.Tid); + videoCount += zone.Count; + var iconKey = VideoZoneIcon.Instance().GetZoneImageKey(zone.Tid); - publicationZones.Add(new PublicationZone + _publicationZones.Add(new PublicationZone { Tid = zone.Tid, Icon = DictionaryResource.Get(iconKey), @@ -131,12 +127,12 @@ public class ViewArchiveViewModel : ViewModelBase } // 全部 - publicationZones.Insert(0, new PublicationZone + _publicationZones.Insert(0, new PublicationZone { Tid = 0, Icon = DictionaryResource.Get("videoUpDrawingImage"), Name = DictionaryResource.GetString("AllPublicationZones"), - Count = VideoCount + Count = videoCount }); } } \ No newline at end of file diff --git a/DownKyi/ViewModels/UserSpace/ViewChannelViewModel.cs b/DownKyi/ViewModels/UserSpace/ViewChannelViewModel.cs index 11ae232..fdc3a49 100644 --- a/DownKyi/ViewModels/UserSpace/ViewChannelViewModel.cs +++ b/DownKyi/ViewModels/UserSpace/ViewChannelViewModel.cs @@ -1,11 +1,7 @@ using System; using System.Collections.Generic; using System.Collections.ObjectModel; -using System.Threading.Tasks; -using Avalonia.Media.Imaging; using DownKyi.Core.BiliApi.Users.Models; -using DownKyi.Core.Storage; -using DownKyi.Utils; using Prism.Commands; using Prism.Events; using Prism.Regions; @@ -118,23 +114,10 @@ public class ViewChannelViewModel : ViewModelBase continue; } - Bitmap image = null; - if (channel.Cover == null || channel.Cover == "") - { - image = ImageHelper.LoadFromResource(new Uri($"avares://DownKyi/Resources/video-placeholder.png")); - } - else - { - StorageCover storageCover = new StorageCover(); - string cover = null; - await Task.Run(() => { cover = storageCover.GetCover(channel.Cover); }); - image = storageCover.GetCoverThumbnail(cover, 190, 190); - } - // 当地时区 - DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1)); - DateTime dateCTime = startTime.AddSeconds(channel.Mtime); - string mtime = dateCTime.ToString("yyyy-MM-dd"); + var startTime = TimeZoneInfo.ConvertTimeFromUtc(new DateTime(1970, 1, 1), TimeZoneInfo.Local);; + var dateCTime = startTime.AddSeconds(channel.Mtime); + var mtime = dateCTime.ToString("yyyy-MM-dd"); Channels.Add(new Channel { diff --git a/DownKyi/ViewModels/UserSpace/ViewSeasonsSeriesViewModel.cs b/DownKyi/ViewModels/UserSpace/ViewSeasonsSeriesViewModel.cs index 1063afb..fb7d466 100644 --- a/DownKyi/ViewModels/UserSpace/ViewSeasonsSeriesViewModel.cs +++ b/DownKyi/ViewModels/UserSpace/ViewSeasonsSeriesViewModel.cs @@ -25,20 +25,20 @@ public class ViewSeasonsSeriesViewModel : ViewModelBase #region 页面属性申明 - private ObservableCollection seasonsSeries; + private ObservableCollection _seasonsSeries; public ObservableCollection SeasonsSeries { - get => seasonsSeries; - set => SetProperty(ref seasonsSeries, value); + get => _seasonsSeries; + set => SetProperty(ref _seasonsSeries, value); } - private int selectedItem; + private int _selectedItem; public int SelectedItem { - get => selectedItem; - set => SetProperty(ref selectedItem, value); + get => _selectedItem; + set => SetProperty(ref _selectedItem, value); } #endregion @@ -55,12 +55,9 @@ public class ViewSeasonsSeriesViewModel : ViewModelBase #region 命令申明 // 视频选择事件 - private DelegateCommand seasonsSeriesCommand; + private DelegateCommand _seasonsSeriesCommand; - public DelegateCommand SeasonsSeriesCommand => seasonsSeriesCommand ?? - (seasonsSeriesCommand = - new DelegateCommand( - ExecuteSeasonsSeriesCommand)); + public DelegateCommand SeasonsSeriesCommand => _seasonsSeriesCommand ??= new DelegateCommand(ExecuteSeasonsSeriesCommand); /// /// 视频选择事件 @@ -68,13 +65,13 @@ public class ViewSeasonsSeriesViewModel : ViewModelBase /// private void ExecuteSeasonsSeriesCommand(object parameter) { - if (!(parameter is SeasonsSeries seasonsSeries)) + if (parameter is not SeasonsSeries seasonsSeries) { return; } // 应该用枚举的,偷懒直接用数字 - int type = 0; + var type = 0; if (seasonsSeries.TypeImage == NormalIcon.Instance().SeasonsSeries) { type = 1; @@ -84,7 +81,7 @@ public class ViewSeasonsSeriesViewModel : ViewModelBase type = 2; } - Dictionary data = new Dictionary + var data = new Dictionary { { "mid", mid }, { "id", seasonsSeries.Id }, @@ -94,7 +91,7 @@ public class ViewSeasonsSeriesViewModel : ViewModelBase }; // 进入视频页面 - NavigationParam param = new NavigationParam + var param = new NavigationParam { ViewName = ViewModels.ViewSeasonsSeriesViewModel.Tag, ParentViewName = ViewUserSpaceViewModel.Tag, @@ -119,7 +116,7 @@ public class ViewSeasonsSeriesViewModel : ViewModelBase /// 接收mid参数 /// /// - public async override void OnNavigatedTo(NavigationContext navigationContext) + public override void OnNavigatedTo(NavigationContext navigationContext) { base.OnNavigatedTo(navigationContext); @@ -143,23 +140,20 @@ public class ViewSeasonsSeriesViewModel : ViewModelBase continue; } - Bitmap image = null; + string? image; if (item.Meta.Cover == null || item.Meta.Cover == "") { - image = ImageHelper.LoadFromResource(new Uri("avares://DownKyi/Resources/video-placeholder.png")); + image = "avares://DownKyi/Resources/video-placeholder.png"; } else { - StorageCover storageCover = new StorageCover(); - string cover = null; - await Task.Run(() => { cover = storageCover.GetCover(item.Meta.Cover); }); - image = storageCover.GetCoverThumbnail(cover, 190, 190); + image = item.Meta.Cover; } // 当地时区 - DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1)); - DateTime dateCTime = startTime.AddSeconds(item.Meta.Ptime); - string mtime = dateCTime.ToString("yyyy-MM-dd"); + var startTime = TimeZoneInfo.ConvertTimeFromUtc(new DateTime(1970, 1, 1), TimeZoneInfo.Local); + var dateCTime = startTime.AddSeconds(item.Meta.Ptime); + var mtime = dateCTime.ToString("yyyy-MM-dd"); SeasonsSeries.Add(new SeasonsSeries { @@ -179,23 +173,20 @@ public class ViewSeasonsSeriesViewModel : ViewModelBase continue; } - Bitmap image = null; + string? image; if (item.Meta.Cover == null || item.Meta.Cover == "") { - image = ImageHelper.LoadFromResource(new Uri($"avares://DownKyi/Resources/video-placeholder.png")); + image = "avares://DownKyi/Resources/video-placeholder.png"; } else { - StorageCover storageCover = new StorageCover(); - string cover = null; - await Task.Run(() => { cover = storageCover.GetCover(item.Meta.Cover); }); - image = storageCover.GetCoverThumbnail(cover, 190, 190); + image = item.Meta.Cover; } // 当地时区 - DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1)); - DateTime dateCTime = startTime.AddSeconds(item.Meta.Mtime); - string mtime = dateCTime.ToString("yyyy-MM-dd"); + var startTime = TimeZoneInfo.ConvertTimeFromUtc(new DateTime(1970, 1, 1), TimeZoneInfo.Local);; + var dateCTime = startTime.AddSeconds(item.Meta.Mtime); + var mtime = dateCTime.ToString("yyyy-MM-dd"); SeasonsSeries.Add(new SeasonsSeries { diff --git a/DownKyi/ViewModels/ViewDownloadManagerViewModel.cs b/DownKyi/ViewModels/ViewDownloadManagerViewModel.cs index d0ca4aa..a2823d2 100644 --- a/DownKyi/ViewModels/ViewDownloadManagerViewModel.cs +++ b/DownKyi/ViewModels/ViewDownloadManagerViewModel.cs @@ -14,7 +14,7 @@ public class ViewDownloadManagerViewModel : ViewModelBase { public const string Tag = "PageDownloadManager"; - private readonly IRegionManager regionManager; + private readonly IRegionManager _regionManager; #region 页面属性申明 @@ -39,7 +39,7 @@ public class ViewDownloadManagerViewModel : ViewModelBase public ViewDownloadManagerViewModel(IRegionManager regionManager, IEventAggregator eventAggregator) : base( eventAggregator) { - this.regionManager = regionManager; + _regionManager = regionManager; #region 属性初始化 @@ -101,10 +101,10 @@ public class ViewDownloadManagerViewModel : ViewModelBase switch (tabHeader.Id) { case 0: - regionManager.RequestNavigate("DownloadManagerContentRegion", ViewDownloadingViewModel.Tag, param); + _regionManager.RequestNavigate("DownloadManagerContentRegion", ViewDownloadingViewModel.Tag, param); break; case 1: - regionManager.RequestNavigate("DownloadManagerContentRegion", ViewDownloadFinishedViewModel.Tag, param); + _regionManager.RequestNavigate("DownloadManagerContentRegion", ViewDownloadFinishedViewModel.Tag, param); break; default: break; @@ -124,6 +124,6 @@ public class ViewDownloadManagerViewModel : ViewModelBase //// 进入设置页面时显示的设置项 SelectTabId = 0; - PropertyChangeAsync(() => { regionManager.RequestNavigate("DownloadManagerContentRegion", ViewDownloadingViewModel.Tag, new NavigationParameters()); }); + PropertyChangeAsync(() => { _regionManager.RequestNavigate("DownloadManagerContentRegion", ViewDownloadingViewModel.Tag, new NavigationParameters()); }); } } \ No newline at end of file diff --git a/DownKyi/ViewModels/ViewFriendsViewModel.cs b/DownKyi/ViewModels/ViewFriendsViewModel.cs index 8ef08b1..c661db1 100644 --- a/DownKyi/ViewModels/ViewFriendsViewModel.cs +++ b/DownKyi/ViewModels/ViewFriendsViewModel.cs @@ -15,34 +15,34 @@ namespace DownKyi.ViewModels { public const string Tag = "PageFriends"; - private readonly IRegionManager regionManager; + private readonly IRegionManager _regionManager; 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 ObservableCollection tabHeaders; + private ObservableCollection _tabHeaders; public ObservableCollection TabHeaders { - get => tabHeaders; - set => SetProperty(ref tabHeaders, value); + get => _tabHeaders; + set => SetProperty(ref _tabHeaders, value); } - private int selectTabId = -1; + private int _selectTabId = -1; public int SelectTabId { - get => selectTabId; - set => SetProperty(ref selectTabId, value); + get => _selectTabId; + set => SetProperty(ref _selectTabId, value); } #endregion @@ -50,7 +50,7 @@ namespace DownKyi.ViewModels public ViewFriendsViewModel(IRegionManager regionManager, IEventAggregator eventAggregator) : base( eventAggregator) { - this.regionManager = regionManager; + _regionManager = regionManager; #region 属性初始化 @@ -69,10 +69,9 @@ namespace DownKyi.ViewModels #region 命令申明 // 返回事件 - private DelegateCommand backSpaceCommand; + private DelegateCommand _backSpaceCommand; - public DelegateCommand BackSpaceCommand => - backSpaceCommand ?? (backSpaceCommand = new DelegateCommand(ExecuteBackSpace)); + public DelegateCommand BackSpaceCommand => _backSpaceCommand ??= new DelegateCommand(ExecuteBackSpace); /// /// 返回事件 @@ -83,7 +82,7 @@ namespace DownKyi.ViewModels ArrowBack.Fill = DictionaryResource.GetColor("ColorText"); - NavigationParam parameter = new NavigationParam + var parameter = new NavigationParam { ViewName = ParentView, ParentViewName = null, @@ -93,11 +92,9 @@ namespace DownKyi.ViewModels } // 顶部tab点击事件 - private DelegateCommand tabHeadersCommand; + private DelegateCommand _tabHeadersCommand; - public DelegateCommand TabHeadersCommand => tabHeadersCommand ?? - (tabHeadersCommand = - new DelegateCommand(ExecuteTabHeadersCommand)); + public DelegateCommand TabHeadersCommand => _tabHeadersCommand ??= new DelegateCommand(ExecuteTabHeadersCommand); /// /// 顶部tab点击事件 @@ -105,7 +102,7 @@ namespace DownKyi.ViewModels /// private void ExecuteTabHeadersCommand(object parameter) { - if (!(parameter is TabHeader tabHeader)) + if (parameter is not TabHeader tabHeader) { return; } @@ -136,10 +133,10 @@ namespace DownKyi.ViewModels switch (id) { case 0: - regionManager.RequestNavigate("FriendContentRegion", ViewFollowingViewModel.Tag, param); + _regionManager.RequestNavigate("FriendContentRegion", ViewFollowingViewModel.Tag, param); break; case 1: - regionManager.RequestNavigate("FriendContentRegion", ViewFollowerViewModel.Tag, param); + _regionManager.RequestNavigate("FriendContentRegion", ViewFollowerViewModel.Tag, param); break; } } diff --git a/DownKyi/ViewModels/ViewIndexViewModel.cs b/DownKyi/ViewModels/ViewIndexViewModel.cs index 87c79b1..0ccdfed 100644 --- a/DownKyi/ViewModels/ViewIndexViewModel.cs +++ b/DownKyi/ViewModels/ViewIndexViewModel.cs @@ -3,7 +3,6 @@ using System.IO; using System.Linq; using System.Text.RegularExpressions; using System.Threading.Tasks; -using Avalonia.Media.Imaging; using DownKyi.Core.BiliApi.Users; using DownKyi.Core.BiliApi.Users.Models; using DownKyi.Core.Logging; @@ -40,16 +39,16 @@ public class ViewIndexViewModel : ViewModelBase set => SetProperty(ref _userName, value); } - private Bitmap _header; + private string _header = string.Empty; - public Bitmap Header + public string Header { get => _header; set => SetProperty(ref _header, value); } - private VectorImage _textLogo; + private VectorImage _textLogo = new(); public VectorImage TextLogo { @@ -57,7 +56,7 @@ public class ViewIndexViewModel : ViewModelBase set => SetProperty(ref _textLogo, value); } - private string _inputText; + private string _inputText = string.Empty; public string InputText { @@ -65,7 +64,7 @@ public class ViewIndexViewModel : ViewModelBase set => SetProperty(ref _inputText, value); } - private VectorImage _generalSearch; + private VectorImage _generalSearch = new(); public VectorImage GeneralSearch { @@ -73,7 +72,7 @@ public class ViewIndexViewModel : ViewModelBase set => SetProperty(ref _generalSearch, value); } - private VectorImage _settings; + private VectorImage _settings = new(); public VectorImage Settings { @@ -81,7 +80,7 @@ public class ViewIndexViewModel : ViewModelBase set => SetProperty(ref _settings, value); } - private VectorImage _downloadManager; + private VectorImage _downloadManager = new(); public VectorImage DownloadManager { @@ -89,7 +88,7 @@ public class ViewIndexViewModel : ViewModelBase set => SetProperty(ref _downloadManager, value); } - private VectorImage _toolbox; + private VectorImage _toolbox = new(); public VectorImage Toolbox { @@ -101,7 +100,7 @@ public class ViewIndexViewModel : ViewModelBase public ViewIndexViewModel(IEventAggregator eventAggregator) : base(eventAggregator) { _loginPanelVisibility = true; - Header = ImageHelper.LoadFromResource(new Uri("avares://DownKyi/Resources/default_header.jpg")); + Header = "avares://DownKyi/Resources/default_header.jpg"; TextLogo = LogoIcon.Instance().TextLogo; TextLogo.Fill = DictionaryResource.GetColor("ColorPrimary"); @@ -132,7 +131,7 @@ public class ViewIndexViewModel : ViewModelBase { EnterBili(); } - + // 登录事件 private DelegateCommand? _loginCommand; public DelegateCommand LoginCommand => _loginCommand ??= new DelegateCommand(ExecuteLogin); @@ -142,7 +141,7 @@ public class ViewIndexViewModel : ViewModelBase /// private void ExecuteLogin() { - if (UserName == null) + if (UserName is null or "") { NavigateToView.NavigationView(EventAggregator, ViewLoginViewModel.Tag, Tag, null); } @@ -279,7 +278,7 @@ public class ViewIndexViewModel : ViewModelBase if (!File.Exists(StorageManager.GetLogin())) { LoginPanelVisibility = true; - Header = ImageHelper.LoadFromResource(new Uri("avares://DownKyi/Resources/default_header.jpg")); + Header = "avares://DownKyi/Resources/default_header.jpg"; UserName = null; return; } @@ -288,20 +287,13 @@ public class ViewIndexViewModel : ViewModelBase if (userInfo != null) { - if (userInfo.Face != null) - { - Header = new StorageHeader().GetHeaderThumbnail(userInfo.Mid, userInfo.Name, userInfo.Face, 36, 36); - } - else - { - Header = ImageHelper.LoadFromResource(new Uri("avares://DownKyi/Resources/default_header.jpg")); - } + Header = userInfo.Face ?? "avares://DownKyi/Resources/default_header.jpg"; UserName = userInfo.Name; } else { - Header = ImageHelper.LoadFromResource(new Uri("avares://DownKyi/Resources/default_header.jpg")); + Header = "avares://DownKyi/Resources/default_header.jpg"; UserName = null; } } @@ -323,32 +315,24 @@ public class ViewIndexViewModel : ViewModelBase // 根据传入参数不同执行不同任务 var parameter = navigationContext.Parameters.GetValue("Parameter"); - if (parameter == null) + switch (parameter) { - // 其他情况只更新设置的用户信息,不更新UI - UpdateUserInfo(true); - return; - } - - // 启动 - if (parameter == "start") - { - UpdateUserInfo(); - } - // 从登录页面返回 - else if (parameter == "login") - { - UpdateUserInfo(); - } - // 注销 - else if (parameter == "logout") - { - UpdateUserInfo(); - } - else - { - // 其他情况只更新设置的用户信息,不更新UI - UpdateUserInfo(true); + case null: + // 其他情况只更新设置的用户信息,不更新UI + UpdateUserInfo(true); + return; + // 启动 + case "start": + // 从登录页面返回 + case "login": + // 注销 + case "logout": + UpdateUserInfo(); + break; + default: + // 其他情况只更新设置的用户信息,不更新UI + UpdateUserInfo(true); + break; } } } \ No newline at end of file diff --git a/DownKyi/ViewModels/ViewLoginViewModel.cs b/DownKyi/ViewModels/ViewLoginViewModel.cs index a222777..db46657 100644 --- a/DownKyi/ViewModels/ViewLoginViewModel.cs +++ b/DownKyi/ViewModels/ViewLoginViewModel.cs @@ -53,8 +53,7 @@ public class ViewLoginViewModel : ViewModelBase private DelegateCommand? _backSpaceCommand; - public DelegateCommand BackSpaceCommand => - _backSpaceCommand ??= new DelegateCommand(ExecuteBackSpace); + public DelegateCommand BackSpaceCommand => _backSpaceCommand ??= new DelegateCommand(ExecuteBackSpace); private void ExecuteBackSpace() { @@ -79,7 +78,7 @@ public class ViewLoginViewModel : ViewModelBase { try { - var loginUrl = LoginQR.GetLoginUrl(); + var loginUrl = LoginQr.GetLoginUrl(); if (loginUrl == null) { return; @@ -97,7 +96,7 @@ public class ViewLoginViewModel : ViewModelBase return; } - PropertyChangeAsync(() => { LoginQrCode = LoginQR.GetLoginQRCode(loginUrl.Data.Url); }); + PropertyChangeAsync(() => { LoginQrCode = LoginQr.GetLoginQrCode(loginUrl.Data.Url); }); Console.PrintLine(loginUrl.Data.Url + "\n"); LogManager.Debug(Tag, loginUrl.Data.Url); @@ -120,33 +119,16 @@ public class ViewLoginViewModel : ViewModelBase while (true) { Thread.Sleep(1000); - var loginStatus = LoginQR.GetLoginStatus(oauthKey); + var loginStatus = LoginQr.GetLoginStatus(oauthKey); if (loginStatus == null) { continue; } - Console.PrintLine(loginStatus.Data.Code + "\n" + loginStatus.Data.Message + "\n" + - loginStatus.Data.Url + "\n"); - switch (loginStatus.Data.Code) { - // case -1: - // // 没有这个oauthKey - // - // // 发送通知 - // eventAggregator.GetEvent().Publish(DictionaryResource.GetString("LoginKeyError")); - // LogManager.Info(Tag, DictionaryResource.GetString("LoginKeyError")); - // - // // 取消任务 - // tokenSource.Cancel(); - // - // // 创建新任务 - // PropertyChangeAsync(new Action(() => { Task.Run(Login, (tokenSource = new CancellationTokenSource()).Token); })); - // break; case 86038: - // 不匹配的oauthKey,超时或已确认的oauthKey - + // 二维码已失效 // 发送通知 EventAggregator.GetEvent().Publish(DictionaryResource.GetString("LoginTimeOut")); LogManager.Info(Tag, DictionaryResource.GetString("LoginTimeOut")); @@ -172,8 +154,8 @@ public class ViewLoginViewModel : ViewModelBase // 确认登录 // 发送通知 - EventAggregator.GetEvent().Publish("登录成功"); - // LogManager.Info(Tag, DictionaryResource.GetString("LoginSuccessful")); + EventAggregator.GetEvent().Publish(DictionaryResource.GetString("LoginSuccessful")); + LogManager.Info(Tag, DictionaryResource.GetString("LoginSuccessful")); // 保存登录信息 try @@ -181,8 +163,7 @@ public class ViewLoginViewModel : ViewModelBase var isSucceed = LoginHelper.SaveLoginInfoCookies(loginStatus.Data.Url); if (!isSucceed) { - EventAggregator.GetEvent() - .Publish(DictionaryResource.GetString("LoginFailed")); + EventAggregator.GetEvent().Publish(DictionaryResource.GetString("LoginFailed")); LogManager.Error(Tag, DictionaryResource.GetString("LoginFailed")); } } @@ -192,10 +173,7 @@ public class ViewLoginViewModel : ViewModelBase LogManager.Error(e); EventAggregator.GetEvent().Publish(DictionaryResource.GetString("LoginFailed")); } - - // TODO 其他操作 - - + // 取消任务 Thread.Sleep(3000); PropertyChange(ExecuteBackSpace); diff --git a/DownKyi/ViewModels/ViewModelBase.cs b/DownKyi/ViewModels/ViewModelBase.cs index af9b0b9..dcc28e1 100644 --- a/DownKyi/ViewModels/ViewModelBase.cs +++ b/DownKyi/ViewModels/ViewModelBase.cs @@ -28,7 +28,7 @@ public class ViewModelBase : BindableBase, INavigationAware public virtual void OnNavigatedTo(NavigationContext navigationContext) { Journal = navigationContext.NavigationService.Journal; - string viewName = navigationContext.Parameters.GetValue("Parent"); + var viewName = navigationContext.Parameters.GetValue("Parent"); if (viewName != null) { ParentView = viewName; diff --git a/DownKyi/ViewModels/ViewMyBangumiFollowViewModel.cs b/DownKyi/ViewModels/ViewMyBangumiFollowViewModel.cs index 47ada31..c286014 100644 --- a/DownKyi/ViewModels/ViewMyBangumiFollowViewModel.cs +++ b/DownKyi/ViewModels/ViewMyBangumiFollowViewModel.cs @@ -32,7 +32,7 @@ public class ViewMyBangumiFollowViewModel : ViewModelBase private long _mid = -1; // 每页视频数量,暂时在此写死,以后在设置中增加选项 - private readonly int _videoNumberInPage = 15; + private const int VideoNumberInPage = 15; #region 页面属性申明 @@ -145,7 +145,7 @@ public class ViewMyBangumiFollowViewModel : ViewModelBase public ViewMyBangumiFollowViewModel(IEventAggregator eventAggregator, IDialogService dialogService) : base( eventAggregator) { - this.DialogService = dialogService; + DialogService = dialogService; #region 属性初始化 @@ -345,7 +345,7 @@ public class ViewMyBangumiFollowViewModel : ViewModelBase private async void AddToDownload(bool isOnlySelected) { // 订阅里只有BANGUMI类型 - var addToDownloadService = new AddToDownloadService(PlayStreamType.BANGUMI); + var addToDownloadService = new AddToDownloadService(PlayStreamType.Bangumi); // 选择文件夹 var directory = await addToDownloadService.SetDirectory(DialogService); @@ -367,8 +367,6 @@ public class ViewMyBangumiFollowViewModel : ViewModelBase continue; } - /// 有分P的就下载全部 - // 开启服务 var service = new BangumiInfoService($"{ParseEntrance.BangumiMediaUrl}md{media.MediaId}"); @@ -386,15 +384,9 @@ public class ViewMyBangumiFollowViewModel : ViewModelBase } // 通知用户添加到下载列表的结果 - if (i <= 0) - { - EventAggregator.GetEvent().Publish(DictionaryResource.GetString("TipAddDownloadingZero")); - } - else - { - EventAggregator.GetEvent() - .Publish($"{DictionaryResource.GetString("TipAddDownloadingFinished1")}{i}{DictionaryResource.GetString("TipAddDownloadingFinished2")}"); - } + EventAggregator.GetEvent().Publish(i <= 0 + ? DictionaryResource.GetString("TipAddDownloadingZero") + : $"{DictionaryResource.GetString("TipAddDownloadingFinished1")}{i}{DictionaryResource.GetString("TipAddDownloadingFinished2")}"); } private void OnCountChanged_Pager(int count) @@ -433,8 +425,8 @@ public class ViewMyBangumiFollowViewModel : ViewModelBase { var cancellationToken = _tokenSource.Token; - var bangumiFollows = Core.BiliApi.Users.UserSpace.GetBangumiFollow(_mid, type, current, _videoNumberInPage); - if (bangumiFollows == null || bangumiFollows.List == null || bangumiFollows.List.Count == 0) + var bangumiFollows = Core.BiliApi.Users.UserSpace.GetBangumiFollow(_mid, type, current, VideoNumberInPage); + if (bangumiFollows?.List == null || bangumiFollows.List.Count == 0) { LoadingVisibility = false; NoDataVisibility = true; @@ -442,7 +434,7 @@ public class ViewMyBangumiFollowViewModel : ViewModelBase } // 更新总页码 - Pager.Count = (int)Math.Ceiling((double)bangumiFollows.Total / _videoNumberInPage); + Pager.Count = (int)Math.Ceiling((double)bangumiFollows.Total / VideoNumberInPage); // 更新内容 ContentVisibility = true; @@ -450,20 +442,9 @@ public class ViewMyBangumiFollowViewModel : ViewModelBase { // 查询、保存封面 var coverUrl = bangumiFollow.Cover; - Bitmap cover; - if (coverUrl == null || coverUrl == "") + if (!coverUrl.ToLower().StartsWith("http")) { - cover = null; - } - else - { - if (!coverUrl.ToLower().StartsWith("http")) - { - coverUrl = $"https:{bangumiFollow.Cover}"; - } - - var storageCover = new StorageCover(); - cover = storageCover.GetCoverThumbnail(bangumiFollow.MediaId, bangumiFollow.SeasonId.ToString(), -1, coverUrl, 110, 140); + coverUrl = $"https:{bangumiFollow.Cover}"; } // 地区 @@ -501,9 +482,7 @@ public class ViewMyBangumiFollowViewModel : ViewModelBase SeasonTypeName = bangumiFollow.SeasonTypeName, Area = area, Badge = bangumiFollow.Badge, - Cover = cover ?? - ImageHelper.LoadFromResource( - new Uri($"avares://DownKyi/Resources/video-placeholder.png")), + Cover = coverUrl ?? "avares://DownKyi/Resources/video-placeholder.png", Evaluate = bangumiFollow.Evaluate, IndexShow = indexShow, Progress = progress diff --git a/DownKyi/ViewModels/ViewMyFavoritesViewModel.cs b/DownKyi/ViewModels/ViewMyFavoritesViewModel.cs index 040304b..fbe8559 100644 --- a/DownKyi/ViewModels/ViewMyFavoritesViewModel.cs +++ b/DownKyi/ViewModels/ViewMyFavoritesViewModel.cs @@ -27,158 +27,157 @@ public class ViewMyFavoritesViewModel : ViewModelBase //private readonly IDialogService dialogService; - private CancellationTokenSource tokenSource1; - private CancellationTokenSource tokenSource2; + private CancellationTokenSource _tokenSource1; + private CancellationTokenSource _tokenSource2; - private long mid = -1; + private long _mid = -1; // 每页视频数量,暂时在此写死,以后在设置中增加选项 - private readonly int VideoNumberInPage = 20; + private const int VideoNumberInPage = 20; #region 页面属性申明 - private string pageName = Tag; + private string _pageName = Tag; public string PageName { - get => pageName; - set => SetProperty(ref pageName, value); + get => _pageName; + set => SetProperty(ref _pageName, 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 bool loading; + private bool _loading; public bool Loading { - get => loading; - set => SetProperty(ref loading, value); + get => _loading; + set => SetProperty(ref _loading, 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 noDataVisibility; + private bool _noDataVisibility; public bool NoDataVisibility { - get => noDataVisibility; - set => SetProperty(ref noDataVisibility, value); + get => _noDataVisibility; + set => SetProperty(ref _noDataVisibility, value); } - private bool mediaLoading; + private bool _mediaLoading; public bool MediaLoading { - get => mediaLoading; - set => SetProperty(ref mediaLoading, value); + get => _mediaLoading; + set => SetProperty(ref _mediaLoading, value); } - private bool mediaContentVisibility; + private bool _mediaContentVisibility; public bool MediaContentVisibility { - get => mediaContentVisibility; - set => SetProperty(ref mediaContentVisibility, value); + get => _mediaContentVisibility; + set => SetProperty(ref _mediaContentVisibility, value); } - private bool mediaLoadingVisibility; + private bool _mediaLoadingVisibility; public bool MediaLoadingVisibility { - get => mediaLoadingVisibility; - set => SetProperty(ref mediaLoadingVisibility, value); + get => _mediaLoadingVisibility; + set => SetProperty(ref _mediaLoadingVisibility, value); } - private bool mediaNoDataVisibility; + private bool _mediaNoDataVisibility; public bool MediaNoDataVisibility { - get => mediaNoDataVisibility; - set => SetProperty(ref mediaNoDataVisibility, value); + get => _mediaNoDataVisibility; + set => SetProperty(ref _mediaNoDataVisibility, value); } - private VectorImage arrowBack; + private VectorImage _arrowBack; public VectorImage ArrowBack { - get => arrowBack; - set => SetProperty(ref arrowBack, value); + get => _arrowBack; + set => SetProperty(ref _arrowBack, value); } - private VectorImage downloadManage; + private VectorImage _downloadManage; public VectorImage DownloadManage { - get => downloadManage; - set => SetProperty(ref downloadManage, value); + get => _downloadManage; + set => SetProperty(ref _downloadManage, value); } - private ObservableCollection tabHeaders; + private ObservableCollection _tabHeaders; public ObservableCollection TabHeaders { - get => tabHeaders; - set => SetProperty(ref tabHeaders, value); + get => _tabHeaders; + set => SetProperty(ref _tabHeaders, value); } - private int selectTabId; + private int _selectTabId; public int SelectTabId { - get => selectTabId; - set => SetProperty(ref selectTabId, value); + get => _selectTabId; + set => SetProperty(ref _selectTabId, value); } - private bool isEnabled = true; + private bool _isEnabled = true; public bool IsEnabled { - get => isEnabled; - set => SetProperty(ref isEnabled, value); + get => _isEnabled; + set => SetProperty(ref _isEnabled, value); } - private CustomPagerViewModel pager; + private CustomPagerViewModel _pager; public CustomPagerViewModel Pager { - get => pager; - set => SetProperty(ref pager, value); + get => _pager; + set => SetProperty(ref _pager, value); } - private ObservableCollection medias; + private ObservableCollection _medias; public ObservableCollection Medias { - get => medias; - set => SetProperty(ref medias, value); + get => _medias; + set => SetProperty(ref _medias, value); } - private bool isSelectAll; + private bool _isSelectAll; public bool IsSelectAll { - get => isSelectAll; - set => SetProperty(ref isSelectAll, value); + get => _isSelectAll; + set => SetProperty(ref _isSelectAll, value); } #endregion - public ViewMyFavoritesViewModel(IEventAggregator eventAggregator, IDialogService dialogService) : base( - eventAggregator) + public ViewMyFavoritesViewModel(IEventAggregator eventAggregator, IDialogService dialogService) : base(eventAggregator) { - this.DialogService = dialogService; + DialogService = dialogService; #region 属性初始化 @@ -209,10 +208,9 @@ public class ViewMyFavoritesViewModel : ViewModelBase #region 命令申明 // 返回事件 - private DelegateCommand backSpaceCommand; + private DelegateCommand? _backSpaceCommand; - public DelegateCommand BackSpaceCommand => - backSpaceCommand ?? (backSpaceCommand = new DelegateCommand(ExecuteBackSpace)); + public DelegateCommand BackSpaceCommand => _backSpaceCommand ??= new DelegateCommand(ExecuteBackSpace); /// /// 返回事件 @@ -224,10 +222,10 @@ public class ViewMyFavoritesViewModel : ViewModelBase ArrowBack.Fill = DictionaryResource.GetColor("ColorText"); // 结束任务 - tokenSource1?.Cancel(); - tokenSource2?.Cancel(); + _tokenSource1.Cancel(); + _tokenSource2.Cancel(); - NavigationParam parameter = new NavigationParam + var parameter = new NavigationParam { ViewName = ParentView, ParentViewName = null, @@ -237,18 +235,16 @@ public class ViewMyFavoritesViewModel : ViewModelBase } // 前往下载管理页面 - private DelegateCommand downloadManagerCommand; + private DelegateCommand? _downloadManagerCommand; - public DelegateCommand DownloadManagerCommand => downloadManagerCommand ?? - (downloadManagerCommand = - new DelegateCommand(ExecuteDownloadManagerCommand)); + public DelegateCommand DownloadManagerCommand => _downloadManagerCommand ??= new DelegateCommand(ExecuteDownloadManagerCommand); /// /// 前往下载管理页面 /// private void ExecuteDownloadManagerCommand() { - NavigationParam parameter = new NavigationParam + var parameter = new NavigationParam { ViewName = ViewDownloadManagerViewModel.Tag, ParentViewName = Tag, @@ -258,10 +254,9 @@ public class ViewMyFavoritesViewModel : ViewModelBase } // 左侧tab点击事件 - private DelegateCommand leftTabHeadersCommand; + private DelegateCommand? _leftTabHeadersCommand; - public DelegateCommand LeftTabHeadersCommand => leftTabHeadersCommand ?? (leftTabHeadersCommand = - new DelegateCommand(ExecuteLeftTabHeadersCommand, CanExecuteLeftTabHeadersCommand)); + public DelegateCommand LeftTabHeadersCommand => _leftTabHeadersCommand ??= new DelegateCommand(ExecuteLeftTabHeadersCommand, CanExecuteLeftTabHeadersCommand); /// /// 左侧tab点击事件 @@ -269,7 +264,7 @@ public class ViewMyFavoritesViewModel : ViewModelBase /// private void ExecuteLeftTabHeadersCommand(object parameter) { - if (!(parameter is TabHeader tabHeader)) + if (parameter is not TabHeader tabHeader) { return; } @@ -295,10 +290,9 @@ public class ViewMyFavoritesViewModel : ViewModelBase } // 全选按钮点击事件 - private DelegateCommand selectAllCommand; + private DelegateCommand? _selectAllCommand; - public DelegateCommand SelectAllCommand => - selectAllCommand ?? (selectAllCommand = new DelegateCommand(ExecuteSelectAllCommand)); + public DelegateCommand SelectAllCommand => _selectAllCommand ??= new DelegateCommand(ExecuteSelectAllCommand); /// /// 全选按钮点击事件 @@ -323,10 +317,9 @@ public class ViewMyFavoritesViewModel : ViewModelBase } // 列表选择事件 - private DelegateCommand mediasCommand; + private DelegateCommand? _mediasCommand; - public DelegateCommand MediasCommand => - mediasCommand ?? (mediasCommand = new DelegateCommand(ExecuteMediasCommand)); + public DelegateCommand MediasCommand => _mediasCommand ??= new DelegateCommand(ExecuteMediasCommand); /// /// 列表选择事件 @@ -334,27 +327,18 @@ public class ViewMyFavoritesViewModel : ViewModelBase /// private void ExecuteMediasCommand(object parameter) { - if (!(parameter is IList selectedMedia)) + if (parameter is not IList selectedMedia) { return; } - if (selectedMedia.Count == Medias.Count) - { - IsSelectAll = true; - } - else - { - IsSelectAll = false; - } + IsSelectAll = selectedMedia.Count == Medias.Count; } // 添加选中项到下载列表事件 - private DelegateCommand addToDownloadCommand; + private DelegateCommand? _addToDownloadCommand; - public DelegateCommand AddToDownloadCommand => addToDownloadCommand ?? - (addToDownloadCommand = - new DelegateCommand(ExecuteAddToDownloadCommand)); + public DelegateCommand AddToDownloadCommand => _addToDownloadCommand ??= new DelegateCommand(ExecuteAddToDownloadCommand); /// /// 添加选中项到下载列表事件 @@ -365,11 +349,9 @@ public class ViewMyFavoritesViewModel : ViewModelBase } // 添加所有视频到下载列表事件 - private DelegateCommand addAllToDownloadCommand; + private DelegateCommand? _addAllToDownloadCommand; - public DelegateCommand AddAllToDownloadCommand => addAllToDownloadCommand ?? - (addAllToDownloadCommand = - new DelegateCommand(ExecuteAddAllToDownloadCommand)); + public DelegateCommand AddAllToDownloadCommand => _addAllToDownloadCommand ??= new DelegateCommand(ExecuteAddAllToDownloadCommand); /// /// 添加所有视频到下载列表事件 @@ -388,7 +370,7 @@ public class ViewMyFavoritesViewModel : ViewModelBase private async void AddToDownload(bool isOnlySelected) { // 收藏夹里只有视频 - var addToDownloadService = new AddToDownloadService(PlayStreamType.VIDEO); + var addToDownloadService = new AddToDownloadService(PlayStreamType.Video); // 选择文件夹 var directory = await addToDownloadService.SetDirectory(DialogService); @@ -410,8 +392,6 @@ public class ViewMyFavoritesViewModel : ViewModelBase continue; } - /// 有分P的就下载全部 - // 开启服务 var videoInfoService = new VideoInfoService(media.Bvid); @@ -429,15 +409,9 @@ public class ViewMyFavoritesViewModel : ViewModelBase } // 通知用户添加到下载列表的结果 - if (i <= 0) - { - EventAggregator.GetEvent().Publish(DictionaryResource.GetString("TipAddDownloadingZero")); - } - else - { - EventAggregator.GetEvent() - .Publish($"{DictionaryResource.GetString("TipAddDownloadingFinished1")}{i}{DictionaryResource.GetString("TipAddDownloadingFinished2")}"); - } + EventAggregator.GetEvent().Publish(i <= 0 + ? DictionaryResource.GetString("TipAddDownloadingZero") + : $"{DictionaryResource.GetString("TipAddDownloadingFinished1")}{i}{DictionaryResource.GetString("TipAddDownloadingFinished2")}"); } private void OnCountChanged_Pager(int count) @@ -471,12 +445,11 @@ public class ViewMyFavoritesViewModel : ViewModelBase var tab = TabHeaders[SelectTabId]; - await Task.Run(new Action(() => + await Task.Run(() => { - CancellationToken cancellationToken = tokenSource2.Token; + var cancellationToken = _tokenSource2.Token; - List medias = - FavoritesResource.GetFavoritesMedia(tab.Id, current, VideoNumberInPage); + var medias = FavoritesResource.GetFavoritesMedia(tab.Id, current, VideoNumberInPage); if (medias == null || medias.Count == 0) { MediaContentVisibility = true; @@ -491,7 +464,7 @@ public class ViewMyFavoritesViewModel : ViewModelBase var service = new FavoritesService(); service.GetFavoritesMediaList(medias, Medias, EventAggregator, cancellationToken); - }), (tokenSource2 = new CancellationTokenSource()).Token); + }, (_tokenSource2 = new CancellationTokenSource()).Token); IsEnabled = true; } @@ -529,8 +502,8 @@ public class ViewMyFavoritesViewModel : ViewModelBase base.OnNavigatedTo(navigationContext); // 根据传入参数不同执行不同任务 - mid = navigationContext.Parameters.GetValue("Parameter"); - if (mid == 0) + _mid = navigationContext.Parameters.GetValue("Parameter"); + if (_mid == 0) { return; } @@ -539,12 +512,12 @@ public class ViewMyFavoritesViewModel : ViewModelBase await Task.Run(() => { - CancellationToken cancellationToken = tokenSource1.Token; + var cancellationToken = _tokenSource1.Token; var service = new FavoritesService(); - service.GetCreatedFavorites(mid, TabHeaders, cancellationToken); - service.GetCollectedFavorites(mid, TabHeaders, cancellationToken); - }, (tokenSource1 = new CancellationTokenSource()).Token); + service.GetCreatedFavorites(_mid, TabHeaders, cancellationToken); + service.GetCollectedFavorites(_mid, TabHeaders, cancellationToken); + }, (_tokenSource1 = new CancellationTokenSource()).Token); if (TabHeaders.Count == 0) { diff --git a/DownKyi/ViewModels/ViewMyHistoryViewModel.cs b/DownKyi/ViewModels/ViewMyHistoryViewModel.cs index 36a46a3..ad6392c 100644 --- a/DownKyi/ViewModels/ViewMyHistoryViewModel.cs +++ b/DownKyi/ViewModels/ViewMyHistoryViewModel.cs @@ -1,13 +1,10 @@ -using System; -using System.Collections; +using System.Collections; using System.Collections.ObjectModel; using System.Linq; using System.Threading; using System.Threading.Tasks; -using Avalonia.Media.Imaging; using DownKyi.Core.BiliApi.History; using DownKyi.Core.BiliApi.VideoStream; -using DownKyi.Core.Storage; using DownKyi.Core.Utils; using DownKyi.Events; using DownKyi.Images; @@ -29,7 +26,7 @@ public class ViewMyHistoryViewModel : ViewModelBase private CancellationTokenSource? _tokenSource; // 每页视频数量,暂时在此写死,以后在设置中增加选项 - private readonly int VideoNumberInPage = 30; + private const int VideoNumberInPage = 30; #region 页面属性申明 @@ -266,7 +263,7 @@ public class ViewMyHistoryViewModel : ViewModelBase private async void AddToDownload(bool isOnlySelected) { // BANGUMI类型 - var addToDownloadService = new AddToDownloadService(PlayStreamType.VIDEO); + var addToDownloadService = new AddToDownloadService(PlayStreamType.Video); // 选择文件夹 var directory = await addToDownloadService.SetDirectory(DialogService); @@ -291,16 +288,12 @@ public class ViewMyHistoryViewModel : ViewModelBase // 有分P的就下载全部 // 开启服务 - IInfoService? service = null; - switch (media.Business) + IInfoService? service = media.Business switch { - case "archive": - service = new VideoInfoService(media.Url); - break; - case "pgc": - service = new BangumiInfoService(media.Url); - break; - } + "archive" => new VideoInfoService(media.Url), + "pgc" => new BangumiInfoService(media.Url), + _ => null + }; if (service == null) { @@ -321,16 +314,9 @@ public class ViewMyHistoryViewModel : ViewModelBase } // 通知用户添加到下载列表的结果 - if (i <= 0) - { - EventAggregator.GetEvent().Publish(DictionaryResource.GetString("TipAddDownloadingZero")); - } - else - { - EventAggregator.GetEvent() - .Publish( - $"{DictionaryResource.GetString("TipAddDownloadingFinished1")}{i}{DictionaryResource.GetString("TipAddDownloadingFinished2")}"); - } + EventAggregator.GetEvent().Publish(i <= 0 + ? DictionaryResource.GetString("TipAddDownloadingZero") + : $"{DictionaryResource.GetString("TipAddDownloadingFinished1")}{i}{DictionaryResource.GetString("TipAddDownloadingFinished2")}"); } private async void UpdateHistoryMediaList() @@ -341,10 +327,10 @@ public class ViewMyHistoryViewModel : ViewModelBase await Task.Run(() => { - var cancellationToken = _tokenSource.Token; + var cancellationToken = _tokenSource?.Token; var historyList = History.GetHistory(0, 0, VideoNumberInPage); - if (historyList == null || historyList.List == null || historyList.List.Count == 0) + if (historyList?.List == null || historyList.List.Count == 0) { LoadingVisibility = false; NoDataVisibility = true; @@ -364,103 +350,47 @@ public class ViewMyHistoryViewModel : ViewModelBase } // 播放url - var url = "https://www.bilibili.com"; - switch (history.History.Business) + var url = history.History.Business switch { - case "archive": - url = "https://www.bilibili.com/video/" + history.History.Bvid; - break; - case "pgc": - url = history.Uri; - break; - } + "archive" => "https://www.bilibili.com/video/" + history.History.Bvid, + "pgc" => history.Uri, + _ => "https://www.bilibili.com" + }; // 查询、保存封面 var coverUrl = history.Cover; - Bitmap cover; - if (coverUrl == null || coverUrl == "") + if (!coverUrl.ToLower().StartsWith("http")) { - cover = null; - } - else - { - if (!coverUrl.ToLower().StartsWith("http")) - { - coverUrl = $"https:{history.Cover}"; - } - - var storageCover = new StorageCover(); - cover = storageCover.GetCoverThumbnail(history.History.Oid, history.History.Bvid, - history.History.Cid, coverUrl, 160, 100); + coverUrl = $"https:{history.Cover}"; } // 获取用户头像 - string upName; - Bitmap upHeader; - if (history.AuthorFace != null) - { - upName = history.AuthorName; - StorageHeader storageHeader = new StorageHeader(); - upHeader = storageHeader.GetHeaderThumbnail(history.AuthorMid, upName, history.AuthorFace, 24, 24); - } - else - { - upName = ""; - upHeader = null; - } + var upName = history.AuthorFace != null ? history.AuthorName : ""; // 观看平台 - VectorImage platform; - switch (history.History.Dt) + var platform = history.History.Dt switch { - case 1: - case 3: - case 5: - case 7: + 1 or 3 or 5 or 7 => // 手机端 - platform = NormalIcon.Instance().PlatformMobile; - break; - case 2: + NormalIcon.Instance().PlatformMobile, + 2 => // web端 - platform = NormalIcon.Instance().PlatformPC; - break; - case 4: - case 6: + NormalIcon.Instance().PlatformPC, + 4 or 6 => // pad端 - platform = NormalIcon.Instance().PlatformIpad; - break; - case 33: + NormalIcon.Instance().PlatformIpad, + 33 => // TV端 - platform = NormalIcon.Instance().PlatformTV; - break; - default: - // 其他 - platform = null; - break; - } + NormalIcon.Instance().PlatformTV, + _ => null + }; // 是否显示Partdesc - bool partdescVisibility; - if (history.NewDesc == "") - { - partdescVisibility = false; - } - else - { - partdescVisibility = true; - } + var partdescVisibility = history.NewDesc != ""; // 是否显示UP主信息和分区信息 - bool upAndTagVisibility; - if (history.History.Business == "archive") - { - upAndTagVisibility = true; - } - else - { - upAndTagVisibility = false; - } + var upAndTagVisibility = history.History.Business == "archive"; App.PropertyChangeAsync(() => { @@ -489,9 +419,7 @@ public class ViewMyHistoryViewModel : ViewModelBase Bvid = history.History.Bvid, Url = url, UpMid = history.AuthorMid, - Cover = cover ?? - ImageHelper.LoadFromResource( - new Uri($"avares://DownKyi/Resources/video-placeholder.png")), + Cover = coverUrl ?? "avares://DownKyi/Resources/video-placeholder.png", Title = history.Title, SubTitle = history.ShowTitle, Duration = history.Duration, @@ -500,7 +428,7 @@ public class ViewMyHistoryViewModel : ViewModelBase Progress = progress, Platform = platform, UpName = upName, - UpHeader = upHeader, + UpHeader = history.AuthorFace ?? "", PartdescVisibility = partdescVisibility, UpAndTagVisibility = upAndTagVisibility, @@ -514,7 +442,7 @@ public class ViewMyHistoryViewModel : ViewModelBase }); // 判断是否该结束线程,若为true,跳出循环 - if (cancellationToken.IsCancellationRequested) + if (cancellationToken?.IsCancellationRequested == true) { break; } diff --git a/DownKyi/ViewModels/ViewMySpaceViewModel.cs b/DownKyi/ViewModels/ViewMySpaceViewModel.cs index 759a209..531f7a6 100644 --- a/DownKyi/ViewModels/ViewMySpaceViewModel.cs +++ b/DownKyi/ViewModels/ViewMySpaceViewModel.cs @@ -22,266 +22,267 @@ public class ViewMySpaceViewModel : ViewModelBase { public const string Tag = "PageMySpace"; - private CancellationTokenSource tokenSource; + private CancellationTokenSource _tokenSource; // mid - private long mid = -1; + 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 VectorImage logout; + private VectorImage _logout; public VectorImage Logout { - get => logout; - set => SetProperty(ref logout, value); + get => _logout; + set => SetProperty(ref _logout, 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 string _background; - public Bitmap Background + public string Background { - get => background; - set => SetProperty(ref background, value); + get => _background; + set => SetProperty(ref _background, value); } - private Bitmap header; + private string _header; - public Bitmap Header + public string 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 VectorImage coinIcon; + private VectorImage _coinIcon; public VectorImage CoinIcon { - get => coinIcon; - set => SetProperty(ref coinIcon, value); + get => _coinIcon; + set => SetProperty(ref _coinIcon, value); } - private string coin; + private string _coin; public string Coin { - get => coin; - set => SetProperty(ref coin, value); + get => _coin; + set => SetProperty(ref _coin, value); } - private VectorImage moneyIcon; + private VectorImage _moneyIcon; public VectorImage MoneyIcon { - get => moneyIcon; - set => SetProperty(ref moneyIcon, value); + get => _moneyIcon; + set => SetProperty(ref _moneyIcon, value); } - private string money; + private string _money; public string Money { - get => money; - set => SetProperty(ref money, value); + get => _money; + set => SetProperty(ref _money, value); } - private VectorImage bindingEmail; + private VectorImage _bindingEmail; public VectorImage BindingEmail { - get => bindingEmail; - set => SetProperty(ref bindingEmail, value); + get => _bindingEmail; + set => SetProperty(ref _bindingEmail, value); } - private bool bindingEmailVisibility; + private bool _bindingEmailVisibility; public bool BindingEmailVisibility { - get => bindingEmailVisibility; - set => SetProperty(ref bindingEmailVisibility, value); + get => _bindingEmailVisibility; + set => SetProperty(ref _bindingEmailVisibility, value); } - private VectorImage bindingPhone; + private VectorImage _bindingPhone; public VectorImage BindingPhone { - get => bindingPhone; - set => SetProperty(ref bindingPhone, value); + get => _bindingPhone; + set => SetProperty(ref _bindingPhone, value); } - private bool bindingPhoneVisibility; + private bool _bindingPhoneVisibility; public bool BindingPhoneVisibility { - get => bindingPhoneVisibility; - set => SetProperty(ref bindingPhoneVisibility, value); + get => _bindingPhoneVisibility; + set => SetProperty(ref _bindingPhoneVisibility, value); } - private string levelText; + private string _levelText; public string LevelText { - get => levelText; - set => SetProperty(ref levelText, value); + get => _levelText; + set => SetProperty(ref _levelText, value); } - private string currentExp; + private string _currentExp; public string CurrentExp { - get => currentExp; - set => SetProperty(ref currentExp, value); + get => _currentExp; + set => SetProperty(ref _currentExp, value); } - private int expProgress; + private int _expProgress; public int ExpProgress { - get => expProgress; - set => SetProperty(ref expProgress, value); + get => _expProgress; + set => SetProperty(ref _expProgress, value); } - private int maxExp; + private int _maxExp; public int MaxExp { - get => maxExp; - set => SetProperty(ref maxExp, value); + get => _maxExp; + set => SetProperty(ref _maxExp, value); } - private ObservableCollection statusList; + private ObservableCollection _statusList; public ObservableCollection StatusList { - get => statusList; - set => SetProperty(ref statusList, value); + get => _statusList; + set => SetProperty(ref _statusList, value); } - private ObservableCollection packageList; + private ObservableCollection _packageList; public ObservableCollection PackageList { - get => packageList; - set => SetProperty(ref packageList, value); + get => _packageList; + set => SetProperty(ref _packageList, value); } - private int selectedStatus = -1; + private int _selectedStatus = -1; public int SelectedStatus { - get => selectedStatus; - set => SetProperty(ref selectedStatus, value); + get => _selectedStatus; + set => SetProperty(ref _selectedStatus, value); } - private int selectedPackage = -1; + private int _selectedPackage = -1; public int SelectedPackage { - get => selectedPackage; - set => SetProperty(ref selectedPackage, value); + get => _selectedPackage; + set => SetProperty(ref _selectedPackage, value); } #endregion @@ -322,10 +323,9 @@ public class ViewMySpaceViewModel : ViewModelBase #region 命令申明 // 返回事件 - private DelegateCommand backSpaceCommand; + private DelegateCommand? _backSpaceCommand; - public DelegateCommand BackSpaceCommand => - backSpaceCommand ?? (backSpaceCommand = new DelegateCommand(ExecuteBackSpace)); + public DelegateCommand BackSpaceCommand => _backSpaceCommand ??= new DelegateCommand(ExecuteBackSpace); /// /// 返回事件 @@ -333,9 +333,9 @@ public class ViewMySpaceViewModel : ViewModelBase private void ExecuteBackSpace() { // 结束任务 - tokenSource?.Cancel(); + _tokenSource?.Cancel(); - NavigationParam parameter = new NavigationParam + var parameter = new NavigationParam { ViewName = ParentView, ParentViewName = null, @@ -345,10 +345,9 @@ public class ViewMySpaceViewModel : ViewModelBase } // 退出登录事件 - private DelegateCommand logoutCommand; + private DelegateCommand? _logoutCommand; - public DelegateCommand LogoutCommand => - logoutCommand ?? (logoutCommand = new DelegateCommand(ExecuteLogoutCommand)); + public DelegateCommand LogoutCommand => _logoutCommand ??= new DelegateCommand(ExecuteLogoutCommand); /// /// 退出登录事件 @@ -359,7 +358,7 @@ public class ViewMySpaceViewModel : ViewModelBase LoginHelper.Logout(); // 返回上一页 - NavigationParam parameter = new NavigationParam + var parameter = new NavigationParam { ViewName = ParentView, ParentViewName = null, @@ -369,10 +368,9 @@ public class ViewMySpaceViewModel : ViewModelBase } // 页面选择事件 - private DelegateCommand statusListCommand; + private DelegateCommand? _statusListCommand; - public DelegateCommand StatusListCommand => - statusListCommand ?? (statusListCommand = new DelegateCommand(ExecuteStatusListCommand)); + public DelegateCommand StatusListCommand => _statusListCommand ??= new DelegateCommand(ExecuteStatusListCommand); /// /// 页面选择事件 @@ -384,9 +382,9 @@ public class ViewMySpaceViewModel : ViewModelBase return; } - Dictionary data = new Dictionary + var data = new Dictionary { - { "mid", mid }, + { "mid", _mid }, { "friendId", 0 } }; @@ -412,16 +410,13 @@ public class ViewMySpaceViewModel : ViewModelBase } // 页面选择事件 - private DelegateCommand packageListCommand; + private DelegateCommand _packageListCommand; - public DelegateCommand PackageListCommand => packageListCommand ?? - (packageListCommand = - new DelegateCommand(ExecutePackageListCommand)); + public DelegateCommand PackageListCommand => _packageListCommand ??= new DelegateCommand(ExecutePackageListCommand); /// /// 页面选择事件 /// - /// private void ExecutePackageListCommand() { if (SelectedPackage == -1) @@ -432,16 +427,16 @@ public class ViewMySpaceViewModel : ViewModelBase switch (SelectedPackage) { case 0: - NavigateToView.NavigationView(EventAggregator, ViewMyFavoritesViewModel.Tag, Tag, mid); + NavigateToView.NavigationView(EventAggregator, ViewMyFavoritesViewModel.Tag, Tag, _mid); break; case 1: - NavigateToView.NavigationView(EventAggregator, ViewMyBangumiFollowViewModel.Tag, Tag, mid); + NavigateToView.NavigationView(EventAggregator, ViewMyBangumiFollowViewModel.Tag, Tag, _mid); break; case 2: - NavigateToView.NavigationView(EventAggregator, ViewMyToViewVideoViewModel.Tag, Tag, mid); + NavigateToView.NavigationView(EventAggregator, ViewMyToViewVideoViewModel.Tag, Tag, _mid); break; case 3: - NavigateToView.NavigationView(EventAggregator, ViewMyHistoryViewModel.Tag, Tag, mid); + NavigateToView.NavigationView(EventAggregator, ViewMyHistoryViewModel.Tag, Tag, _mid); break; default: break; @@ -477,18 +472,12 @@ public class ViewMySpaceViewModel : ViewModelBase CurrentExp = "--/--"; StatusList.Clear(); - StatusList.Add(new SpaceItem - { IsEnabled = true, Title = DictionaryResource.GetString("Following"), Subtitle = "--" }); - StatusList.Add(new SpaceItem - { IsEnabled = true, Title = DictionaryResource.GetString("Whisper"), Subtitle = "--" }); - StatusList.Add(new SpaceItem - { IsEnabled = true, Title = DictionaryResource.GetString("Follower"), Subtitle = "--" }); - StatusList.Add(new SpaceItem - { IsEnabled = false, Title = DictionaryResource.GetString("Black"), Subtitle = "--" }); - StatusList.Add(new SpaceItem - { IsEnabled = false, Title = DictionaryResource.GetString("Moral"), Subtitle = "--" }); - StatusList.Add(new SpaceItem - { IsEnabled = false, Title = DictionaryResource.GetString("Silence"), Subtitle = "N/A" }); + StatusList.Add(new SpaceItem { IsEnabled = true, Title = DictionaryResource.GetString("Following"), Subtitle = "--" }); + StatusList.Add(new SpaceItem { IsEnabled = true, Title = DictionaryResource.GetString("Whisper"), Subtitle = "--" }); + StatusList.Add(new SpaceItem { IsEnabled = true, Title = DictionaryResource.GetString("Follower"), Subtitle = "--" }); + StatusList.Add(new SpaceItem { IsEnabled = false, Title = DictionaryResource.GetString("Black"), Subtitle = "--" }); + StatusList.Add(new SpaceItem { IsEnabled = false, Title = DictionaryResource.GetString("Moral"), Subtitle = "--" }); + StatusList.Add(new SpaceItem { IsEnabled = false, Title = DictionaryResource.GetString("Silence"), Subtitle = "N/A" }); PackageList.Clear(); PackageList.Add(new SpaceItem @@ -528,29 +517,20 @@ public class ViewMySpaceViewModel : ViewModelBase /// private async void UpdateSpaceInfo() { - bool isCancel = false; - bool isNoData = true; - Uri toutuUri = null; + var isCancel = false; + var isNoData = true; + string? toutuUri = null; string headerUri = null; - Uri sexUri = null; + Uri? sexUri = null; Uri levelUri = null; await Task.Run(() => { - CancellationToken cancellationToken = tokenSource.Token; + var cancellationToken = _tokenSource.Token; // 背景图片 - SpaceSettings 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}"); - toutuUri = new Uri(toutu); - } - else - { - toutuUri = new Uri("avares://DownKyi/Resources/backgound/9-绿荫秘境.png"); - } + var spaceSettings = Core.BiliApi.Users.UserSpace.GetSpaceSettings(_mid); + toutuUri = spaceSettings != null ? $"https://i0.hdslb.com/{spaceSettings.Toutu.Limg}" : "avares://DownKyi/Resources/backgound/9-绿荫秘境.png"; // 我的用户信息 var myInfo = UserInfo.GetMyInfo(); @@ -559,18 +539,17 @@ public class ViewMySpaceViewModel : ViewModelBase isNoData = false; // 头像 - var storageHeader = new StorageHeader(); - headerUri = storageHeader.GetHeader(mid, myInfo.Name, myInfo.Face); + headerUri = myInfo.Face; // 用户名 UserName = myInfo.Name; // 性别 if (myInfo.Sex == "男") { - sexUri = new Uri($"avares://DownKyi/Resources/sex/male.png"); + sexUri = new Uri("avares://DownKyi/Resources/sex/male.png"); } else if (myInfo.Sex == "女") { - sexUri = new Uri($"avares://DownKyi/Resources/sex/female.png"); + sexUri = new Uri("avares://DownKyi/Resources/sex/female.png"); } // 显示vip信息 @@ -600,18 +579,8 @@ public class ViewMySpaceViewModel : ViewModelBase } // 等级 - PropertyChangeAsync(() => - { - LevelText = $"{DictionaryResource.GetString("Level")}{myInfo.LevelExp.CurrentLevel}"; - }); - if (myInfo.LevelExp.NextExp == -1) - { - CurrentExp = $"{myInfo.LevelExp.CurrentExp}/--"; - } - else - { - CurrentExp = $"{myInfo.LevelExp.CurrentExp}/{myInfo.LevelExp.NextExp}"; - } + PropertyChangeAsync(() => { LevelText = $"{DictionaryResource.GetString("Level")}{myInfo.LevelExp.CurrentLevel}"; }); + CurrentExp = myInfo.LevelExp.NextExp == -1 ? $"{myInfo.LevelExp.CurrentExp}/--" : $"{myInfo.LevelExp.CurrentExp}/{myInfo.LevelExp.NextExp}"; // 经验 MaxExp = myInfo.LevelExp.NextExp; @@ -639,7 +608,7 @@ public class ViewMySpaceViewModel : ViewModelBase { isCancel = true; } - }, (tokenSource = new CancellationTokenSource()).Token); + }, (_tokenSource = new CancellationTokenSource()).Token); // 是否该结束线程 if (isCancel) @@ -663,8 +632,7 @@ public class ViewMySpaceViewModel : ViewModelBase else { // 头像 - var storageHeader = new StorageHeader(); - Header = storageHeader.GetHeaderThumbnail(headerUri, 64, 64); + Header = headerUri; // 性别 Sex = sexUri == null ? null : ImageHelper.LoadFromResource(sexUri); // 等级 @@ -673,7 +641,7 @@ public class ViewMySpaceViewModel : ViewModelBase ArrowBack.Fill = DictionaryResource.GetColor("ColorText"); Logout.Fill = DictionaryResource.GetColor("ColorText"); TopNavigationBg = DictionaryResource.GetColor("ColorMask100"); - Background = ImageHelper.LoadFromResource(toutuUri); + Background = toutuUri ?? ""; ViewVisibility = true; LoadingVisibility = false; @@ -696,18 +664,16 @@ public class ViewMySpaceViewModel : ViewModelBase } //用户的关系状态数 - var relationStat = UserStatus.GetUserRelationStat(mid); - if (relationStat != null) - { - // 关注数 - StatusList[0].Subtitle = relationStat.Following.ToString(); - // 悄悄关注数 - StatusList[1].Subtitle = relationStat.Whisper.ToString(); - // 粉丝数 - StatusList[2].Subtitle = relationStat.Follower.ToString(); - // 黑名单数 - StatusList[3].Subtitle = relationStat.Black.ToString(); - } + var relationStat = UserStatus.GetUserRelationStat(_mid); + if (relationStat == null) return; + // 关注数 + StatusList[0].Subtitle = relationStat.Following.ToString(); + // 悄悄关注数 + StatusList[1].Subtitle = relationStat.Whisper.ToString(); + // 粉丝数 + StatusList[2].Subtitle = relationStat.Follower.ToString(); + // 黑名单数 + StatusList[3].Subtitle = relationStat.Black.ToString(); }); } @@ -720,13 +686,13 @@ public class ViewMySpaceViewModel : ViewModelBase base.OnNavigatedTo(navigationContext); // 根据传入参数不同执行不同任务 - long parameter = navigationContext.Parameters.GetValue("Parameter"); + var parameter = navigationContext.Parameters.GetValue("Parameter"); if (parameter == 0) { return; } - mid = parameter; + _mid = parameter; InitView(); UpdateSpaceInfo(); diff --git a/DownKyi/ViewModels/ViewMyToViewVideoViewModel.cs b/DownKyi/ViewModels/ViewMyToViewVideoViewModel.cs index e05b04c..5555655 100644 --- a/DownKyi/ViewModels/ViewMyToViewVideoViewModel.cs +++ b/DownKyi/ViewModels/ViewMyToViewVideoViewModel.cs @@ -1,13 +1,10 @@ -using System; -using System.Collections; +using System.Collections; using System.Collections.ObjectModel; using System.Linq; using System.Threading; using System.Threading.Tasks; -using Avalonia.Media.Imaging; using DownKyi.Core.BiliApi.History; using DownKyi.Core.BiliApi.VideoStream; -using DownKyi.Core.Storage; using DownKyi.Events; using DownKyi.Images; using DownKyi.PrismExtension.Dialog; @@ -25,80 +22,80 @@ public class ViewMyToViewVideoViewModel : ViewModelBase { public const string Tag = "PageMyToView"; - private CancellationTokenSource tokenSource; + private CancellationTokenSource _tokenSource; #region 页面属性申明 - private string pageName = Tag; + private string _pageName = Tag; public string PageName { - get => pageName; - set => SetProperty(ref pageName, value); + get => _pageName; + set => SetProperty(ref _pageName, value); } - private VectorImage arrowBack; + private VectorImage _arrowBack; public VectorImage ArrowBack { - get => arrowBack; - set => SetProperty(ref arrowBack, value); + get => _arrowBack; + set => SetProperty(ref _arrowBack, value); } - private VectorImage downloadManage; + private VectorImage _downloadManage; public VectorImage DownloadManage { - get => downloadManage; - set => SetProperty(ref downloadManage, value); + get => _downloadManage; + set => SetProperty(ref _downloadManage, 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 ObservableCollection medias; + private ObservableCollection _medias; public ObservableCollection Medias { - get => medias; - set => SetProperty(ref medias, value); + get => _medias; + set => SetProperty(ref _medias, value); } - private bool isSelectAll; + private bool _isSelectAll; public bool IsSelectAll { - get => isSelectAll; - set => SetProperty(ref isSelectAll, value); + get => _isSelectAll; + set => SetProperty(ref _isSelectAll, 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 loadingVisibility; + private bool _loadingVisibility; public bool LoadingVisibility { - get => loadingVisibility; - set => SetProperty(ref loadingVisibility, value); + get => _loadingVisibility; + set => SetProperty(ref _loadingVisibility, value); } - private bool noDataVisibility; + private bool _noDataVisibility; public bool NoDataVisibility { - get => noDataVisibility; - set => SetProperty(ref noDataVisibility, value); + get => _noDataVisibility; + set => SetProperty(ref _noDataVisibility, value); } #endregion @@ -106,7 +103,7 @@ public class ViewMyToViewVideoViewModel : ViewModelBase public ViewMyToViewVideoViewModel(IEventAggregator eventAggregator, IDialogService dialogService) : base( eventAggregator) { - this.DialogService = dialogService; + DialogService = dialogService; #region 属性初始化 @@ -132,10 +129,9 @@ public class ViewMyToViewVideoViewModel : ViewModelBase #region 命令申明 // 返回事件 - private DelegateCommand backSpaceCommand; + private DelegateCommand? _backSpaceCommand; - public DelegateCommand BackSpaceCommand => - backSpaceCommand ?? (backSpaceCommand = new DelegateCommand(ExecuteBackSpace)); + public DelegateCommand BackSpaceCommand => _backSpaceCommand ??= new DelegateCommand(ExecuteBackSpace); /// /// 返回事件 @@ -147,9 +143,9 @@ public class ViewMyToViewVideoViewModel : ViewModelBase ArrowBack.Fill = DictionaryResource.GetColor("ColorText"); // 结束任务 - tokenSource?.Cancel(); + _tokenSource?.Cancel(); - NavigationParam parameter = new NavigationParam + var parameter = new NavigationParam { ViewName = ParentView, ParentViewName = null, @@ -159,18 +155,16 @@ public class ViewMyToViewVideoViewModel : ViewModelBase } // 前往下载管理页面 - private DelegateCommand downloadManagerCommand; + private DelegateCommand? _downloadManagerCommand; - public DelegateCommand DownloadManagerCommand => downloadManagerCommand ?? - (downloadManagerCommand = - new DelegateCommand(ExecuteDownloadManagerCommand)); + public DelegateCommand DownloadManagerCommand => _downloadManagerCommand ??= new DelegateCommand(ExecuteDownloadManagerCommand); /// /// 前往下载管理页面 /// private void ExecuteDownloadManagerCommand() { - NavigationParam parameter = new NavigationParam + var parameter = new NavigationParam { ViewName = ViewDownloadManagerViewModel.Tag, ParentViewName = Tag, @@ -180,10 +174,9 @@ public class ViewMyToViewVideoViewModel : ViewModelBase } // 全选按钮点击事件 - private DelegateCommand selectAllCommand; + private DelegateCommand? _selectAllCommand; - public DelegateCommand SelectAllCommand => - selectAllCommand ?? (selectAllCommand = new DelegateCommand(ExecuteSelectAllCommand)); + public DelegateCommand SelectAllCommand => _selectAllCommand ??= new DelegateCommand(ExecuteSelectAllCommand); /// /// 全选按钮点击事件 @@ -208,10 +201,9 @@ public class ViewMyToViewVideoViewModel : ViewModelBase } // 列表选择事件 - private DelegateCommand mediasCommand; + private DelegateCommand? _mediasCommand; - public DelegateCommand MediasCommand => - mediasCommand ?? (mediasCommand = new DelegateCommand(ExecuteMediasCommand)); + public DelegateCommand MediasCommand => _mediasCommand ??= new DelegateCommand(ExecuteMediasCommand); /// /// 列表选择事件 @@ -219,27 +211,18 @@ public class ViewMyToViewVideoViewModel : ViewModelBase /// private void ExecuteMediasCommand(object parameter) { - if (!(parameter is IList selectedMedia)) + if (parameter is not IList selectedMedia) { return; } - if (selectedMedia.Count == Medias.Count) - { - IsSelectAll = true; - } - else - { - IsSelectAll = false; - } + IsSelectAll = selectedMedia.Count == Medias.Count; } // 添加选中项到下载列表事件 - private DelegateCommand addToDownloadCommand; + private DelegateCommand? _addToDownloadCommand; - public DelegateCommand AddToDownloadCommand => addToDownloadCommand ?? - (addToDownloadCommand = - new DelegateCommand(ExecuteAddToDownloadCommand)); + public DelegateCommand AddToDownloadCommand => _addToDownloadCommand ??= new DelegateCommand(ExecuteAddToDownloadCommand); /// /// 添加选中项到下载列表事件 @@ -250,11 +233,9 @@ public class ViewMyToViewVideoViewModel : ViewModelBase } // 添加所有视频到下载列表事件 - private DelegateCommand addAllToDownloadCommand; + private DelegateCommand? _addAllToDownloadCommand; - public DelegateCommand AddAllToDownloadCommand => addAllToDownloadCommand ?? - (addAllToDownloadCommand = - new DelegateCommand(ExecuteAddAllToDownloadCommand)); + public DelegateCommand AddAllToDownloadCommand => _addAllToDownloadCommand ??= new DelegateCommand(ExecuteAddAllToDownloadCommand); /// /// 添加所有视频到下载列表事件 @@ -273,13 +254,13 @@ public class ViewMyToViewVideoViewModel : ViewModelBase private async void AddToDownload(bool isOnlySelected) { // 稍后再看里只有视频 - AddToDownloadService addToDownloadService = new AddToDownloadService(PlayStreamType.VIDEO); + var addToDownloadService = new AddToDownloadService(PlayStreamType.Video); // 选择文件夹 - string directory = await addToDownloadService.SetDirectory(DialogService); + var directory = await addToDownloadService.SetDirectory(DialogService); // 视频计数 - int i = 0; + var i = 0; await Task.Run(async () => { // 为了避免执行其他操作时, @@ -298,7 +279,7 @@ public class ViewMyToViewVideoViewModel : ViewModelBase /// 有分P的就下载全部 // 开启服务 - VideoInfoService videoInfoService = new VideoInfoService(media.Bvid); + var videoInfoService = new VideoInfoService(media.Bvid); addToDownloadService.SetVideoInfoService(videoInfoService); addToDownloadService.GetVideo(); @@ -314,16 +295,9 @@ public class ViewMyToViewVideoViewModel : ViewModelBase } // 通知用户添加到下载列表的结果 - if (i <= 0) - { - EventAggregator.GetEvent().Publish(DictionaryResource.GetString("TipAddDownloadingZero")); - } - else - { - EventAggregator.GetEvent() - .Publish( - $"{DictionaryResource.GetString("TipAddDownloadingFinished1")}{i}{DictionaryResource.GetString("TipAddDownloadingFinished2")}"); - } + EventAggregator.GetEvent().Publish(i <= 0 + ? DictionaryResource.GetString("TipAddDownloadingZero") + : $"{DictionaryResource.GetString("TipAddDownloadingFinished1")}{i}{DictionaryResource.GetString("TipAddDownloadingFinished2")}"); } private async void UpdateToViewMediaList() @@ -334,7 +308,7 @@ public class ViewMyToViewVideoViewModel : ViewModelBase await Task.Run(() => { - CancellationToken cancellationToken = tokenSource.Token; + CancellationToken cancellationToken = _tokenSource.Token; var toViewList = ToView.GetToView(); if (toViewList == null || toViewList.Count == 0) @@ -347,53 +321,36 @@ public class ViewMyToViewVideoViewModel : ViewModelBase foreach (var toView in toViewList) { // 查询、保存封面 - string coverUrl = toView.Pic; - Bitmap cover; - if (coverUrl == null || coverUrl == "") + var coverUrl = toView.Pic; + if (!coverUrl.ToLower().StartsWith("http")) { - cover = null; - } - else - { - if (!coverUrl.ToLower().StartsWith("http")) - { - coverUrl = $"https:{toView.Pic}"; - } - - StorageCover storageCover = new StorageCover(); - cover = storageCover.GetCoverThumbnail(toView.Aid, toView.Bvid, toView.Cid, coverUrl, 160, 100); + coverUrl = $"https:{toView.Pic}"; } // 获取用户头像 long upMid = -1; string upName; - Bitmap upHeader; if (toView.Owner != null && toView.Owner.Face != null) { upMid = toView.Owner.Mid; upName = toView.Owner.Name; - StorageHeader storageHeader = new StorageHeader(); - upHeader = storageHeader.GetHeaderThumbnail(toView.Owner.Mid, upName, toView.Owner.Face, 24, 24); } else { upName = ""; - upHeader = null; } App.PropertyChangeAsync(() => { - ToViewMedia media = new ToViewMedia(EventAggregator) + var media = new ToViewMedia(EventAggregator) { Aid = toView.Aid, Bvid = toView.Bvid, UpMid = upMid, - Cover = cover ?? - ImageHelper.LoadFromResource( - new Uri($"avares://DownKyi/Resources/video-placeholder.png")), + Cover = coverUrl, Title = toView.Title, UpName = upName, - UpHeader = upHeader + UpHeader = toView.Owner?.Face ?? "" }; Medias.Add(media); @@ -409,7 +366,7 @@ public class ViewMyToViewVideoViewModel : ViewModelBase break; } } - }, (tokenSource = new CancellationTokenSource()).Token); + }, (_tokenSource = new CancellationTokenSource()).Token); } /// @@ -443,7 +400,7 @@ public class ViewMyToViewVideoViewModel : ViewModelBase DownloadManage.Fill = DictionaryResource.GetColor("ColorPrimary"); // 根据传入参数不同执行不同任务 - long mid = navigationContext.Parameters.GetValue("Parameter"); + var mid = navigationContext.Parameters.GetValue("Parameter"); if (mid == 0) { IsSelectAll = false; diff --git a/DownKyi/ViewModels/ViewPublicFavoritesViewModel.cs b/DownKyi/ViewModels/ViewPublicFavoritesViewModel.cs index c2ea66f..9a42598 100644 --- a/DownKyi/ViewModels/ViewPublicFavoritesViewModel.cs +++ b/DownKyi/ViewModels/ViewPublicFavoritesViewModel.cs @@ -22,105 +22,105 @@ public class ViewPublicFavoritesViewModel : ViewModelBase { public const string Tag = "PagePublicFavorites"; - private CancellationTokenSource tokenSource; + private CancellationTokenSource _tokenSource; #region 页面属性申明 - private string pageName = Tag; + private string _pageName = Tag; public string PageName { - get => pageName; - set => SetProperty(ref pageName, value); + get => _pageName; + set => SetProperty(ref _pageName, value); } - private VectorImage arrowBack; + private VectorImage _arrowBack; public VectorImage ArrowBack { - get => arrowBack; - set => SetProperty(ref arrowBack, value); + get => _arrowBack; + set => SetProperty(ref _arrowBack, value); } - private VectorImage downloadManage; + private VectorImage _downloadManage; public VectorImage DownloadManage { - get => downloadManage; - set => SetProperty(ref downloadManage, value); + get => _downloadManage; + set => SetProperty(ref _downloadManage, value); } - private Favorites favorites; + private Favorites _favorites; public Favorites Favorites { - get => favorites; - set => SetProperty(ref favorites, value); + get => _favorites; + set => SetProperty(ref _favorites, value); } - private ObservableCollection favoritesMedias; + private ObservableCollection _favoritesMedias; public ObservableCollection FavoritesMedias { - get => favoritesMedias; - set => SetProperty(ref favoritesMedias, value); + get => _favoritesMedias; + set => SetProperty(ref _favoritesMedias, 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 bool loading; + private bool _loading; public bool Loading { - get => loading; - set => SetProperty(ref loading, value); + get => _loading; + set => SetProperty(ref _loading, 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 noDataVisibility; + private bool _noDataVisibility; public bool NoDataVisibility { - get => noDataVisibility; - set => SetProperty(ref noDataVisibility, value); + get => _noDataVisibility; + set => SetProperty(ref _noDataVisibility, value); } - private bool mediaLoading; + private bool _mediaLoading; public bool MediaLoading { - get => mediaLoading; - set => SetProperty(ref mediaLoading, value); + get => _mediaLoading; + set => SetProperty(ref _mediaLoading, value); } - private bool mediaLoadingVisibility; + private bool _mediaLoadingVisibility; public bool MediaLoadingVisibility { - get => mediaLoadingVisibility; - set => SetProperty(ref mediaLoadingVisibility, value); + get => _mediaLoadingVisibility; + set => SetProperty(ref _mediaLoadingVisibility, value); } - private bool mediaNoDataVisibility; + private bool _mediaNoDataVisibility; public bool MediaNoDataVisibility { - get => mediaNoDataVisibility; - set => SetProperty(ref mediaNoDataVisibility, value); + get => _mediaNoDataVisibility; + set => SetProperty(ref _mediaNoDataVisibility, value); } #endregion @@ -128,7 +128,7 @@ public class ViewPublicFavoritesViewModel : ViewModelBase public ViewPublicFavoritesViewModel(IEventAggregator eventAggregator, IDialogService dialogService) : base( eventAggregator) { - this.DialogService = dialogService; + DialogService = dialogService; #region 属性初始化 @@ -168,7 +168,7 @@ public class ViewPublicFavoritesViewModel : ViewModelBase private void ExecuteBackSpace() { // 结束任务 - tokenSource?.Cancel(); + _tokenSource?.Cancel(); NavigationParam parameter = new NavigationParam { @@ -221,10 +221,10 @@ public class ViewPublicFavoritesViewModel : ViewModelBase /// /// 复制封面URL事件 /// - private void ExecuteCopyCoverUrlCommand() + private async void ExecuteCopyCoverUrlCommand() { // 复制封面url到剪贴板 - // Clipboard.SetText(Favorites.CoverUrl); + await ClipboardManager.SetText(Favorites.CoverUrl); LogManager.Info(Tag, "复制封面url到剪贴板"); } @@ -284,13 +284,13 @@ public class ViewPublicFavoritesViewModel : ViewModelBase private async void AddToDownload(bool isOnlySelected) { // 收藏夹里只有视频 - AddToDownloadService addToDownloadService = new AddToDownloadService(PlayStreamType.VIDEO); + var addToDownloadService = new AddToDownloadService(PlayStreamType.Video); // 选择文件夹 - string directory = await addToDownloadService.SetDirectory(DialogService); + var directory = await addToDownloadService.SetDirectory(DialogService); // 视频计数 - int i = 0; + var i = 0; await Task.Run(async () => { // 为了避免执行其他操作时, @@ -309,7 +309,7 @@ public class ViewPublicFavoritesViewModel : ViewModelBase /// 有分P的就下载全部 // 开启服务 - VideoInfoService videoInfoService = new VideoInfoService(media.Bvid); + var videoInfoService = new VideoInfoService(media.Bvid); addToDownloadService.SetVideoInfoService(videoInfoService); addToDownloadService.GetVideo(); @@ -325,16 +325,9 @@ public class ViewPublicFavoritesViewModel : ViewModelBase } // 通知用户添加到下载列表的结果 - if (i <= 0) - { - EventAggregator.GetEvent().Publish(DictionaryResource.GetString("TipAddDownloadingZero")); - } - else - { - EventAggregator.GetEvent() - .Publish( - $"{DictionaryResource.GetString("TipAddDownloadingFinished1")}{i}{DictionaryResource.GetString("TipAddDownloadingFinished2")}"); - } + EventAggregator.GetEvent().Publish(i <= 0 + ? DictionaryResource.GetString("TipAddDownloadingZero") + : $"{DictionaryResource.GetString("TipAddDownloadingFinished1")}{i}{DictionaryResource.GetString("TipAddDownloadingFinished2")}"); } /// @@ -420,9 +413,9 @@ public class ViewPublicFavoritesViewModel : ViewModelBase InitView(); await Task.Run(() => { - var cancellationToken = tokenSource.Token; + var cancellationToken = _tokenSource.Token; UpdateView(new FavoritesService(), parameter, cancellationToken); - }, (tokenSource = new CancellationTokenSource()).Token); + }, (_tokenSource = new CancellationTokenSource()).Token); } } \ No newline at end of file diff --git a/DownKyi/ViewModels/ViewPublicationViewModel.cs b/DownKyi/ViewModels/ViewPublicationViewModel.cs index 1580500..14e5fb3 100644 --- a/DownKyi/ViewModels/ViewPublicationViewModel.cs +++ b/DownKyi/ViewModels/ViewPublicationViewModel.cs @@ -9,7 +9,6 @@ using System.Threading; using System.Threading.Tasks; using Avalonia.Media.Imaging; using DownKyi.Core.BiliApi.VideoStream; -using DownKyi.Core.Storage; using DownKyi.Core.Utils; using DownKyi.CustomControl; using DownKyi.Events; @@ -35,7 +34,7 @@ namespace DownKyi.ViewModels private long _mid = -1; // 每页视频数量,暂时在此写死,以后在设置中增加选项 - private readonly int _videoNumberInPage = 30; + private const int VideoNumberInPage = 30; #region 页面属性申明 @@ -228,8 +227,7 @@ namespace DownKyi.ViewModels } // 页面选择 - Pager = new CustomPagerViewModel(1, - (int)Math.Ceiling(double.Parse(tabHeader.SubTitle) / _videoNumberInPage)); + Pager = new CustomPagerViewModel(1, (int)Math.Ceiling(double.Parse(tabHeader.SubTitle) / VideoNumberInPage)); Pager.CurrentChanged += OnCurrentChanged_Pager; Pager.CountChanged += OnCountChanged_Pager; Pager.Current = 1; @@ -326,7 +324,7 @@ namespace DownKyi.ViewModels private async void AddToDownload(bool isOnlySelected) { // 收藏夹里只有视频 - var addToDownloadService = new AddToDownloadService(PlayStreamType.VIDEO); + var addToDownloadService = new AddToDownloadService(PlayStreamType.Video); // 选择文件夹 var directory = await addToDownloadService.SetDirectory(DialogService); @@ -356,16 +354,9 @@ namespace DownKyi.ViewModels } // 通知用户添加到下载列表的结果 - if (i <= 0) - { - EventAggregator.GetEvent().Publish(DictionaryResource.GetString("TipAddDownloadingZero")); - } - else - { - EventAggregator.GetEvent() - .Publish( - $"{DictionaryResource.GetString("TipAddDownloadingFinished1")}{i}{DictionaryResource.GetString("TipAddDownloadingFinished2")}"); - } + EventAggregator.GetEvent().Publish(i <= 0 + ? DictionaryResource.GetString("TipAddDownloadingZero") + : $"{DictionaryResource.GetString("TipAddDownloadingFinished1")}{i}{DictionaryResource.GetString("TipAddDownloadingFinished2")}"); } private void OnCountChanged_Pager(int count) @@ -395,14 +386,17 @@ namespace DownKyi.ViewModels var charbuffers = s.ToCharArray(); byte[] buffer; var sb = new StringBuilder(); - for (var i = 0; i < charbuffers.Length; i++) + foreach (var t in charbuffers) { - buffer = Encoding.Unicode.GetBytes(charbuffers[i].ToString()); + buffer = Encoding.Unicode.GetBytes(t.ToString()); sb.Append($"\\u{buffer[1]:X2}{buffer[0]:X2}"); } + return sb.ToString(); } - private readonly Bitmap defaultPic = ImageHelper.LoadFromResource(new Uri("avares://DownKyi/Resources/video-placeholder.png")); + + private readonly Bitmap _defaultPic = ImageHelper.LoadFromResource(new Uri("avares://DownKyi/Resources/video-placeholder.png")); + private async Task UpdatePublication(int current) { _tokenSource?.Cancel(); @@ -413,10 +407,9 @@ namespace DownKyi.ViewModels var cancellationToken = _tokenSource.Token; var tab = TabHeaders[SelectTabId]; - var storageCover = new StorageCover(); - await Task.Run(async () => + await Task.Run(() => { - var publications = Core.BiliApi.Users.UserSpace.GetPublication(_mid, current, _videoNumberInPage, tab.Id); + var publications = Core.BiliApi.Users.UserSpace.GetPublication(_mid, current, VideoNumberInPage, tab.Id); if (publications == null) { // 没有数据,UI提示 @@ -450,7 +443,7 @@ namespace DownKyi.ViewModels play = "--"; } - var startTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1)); // 当地时区 + var startTime = TimeZoneInfo.ConvertTimeFromUtc(new DateTime(1970, 1, 1), TimeZoneInfo.Local); // 当地时区 var dateCTime = startTime.AddSeconds(video.Created); var ctime = dateCTime.ToString("yyyy-MM-dd"); App.PropertyChangeAsync(() => @@ -459,7 +452,7 @@ namespace DownKyi.ViewModels { Avid = video.Aid, Bvid = video.Bvid, - Cover = defaultPic, + Cover = _defaultPic, Duration = video.Length, Title = video.Title, PlayNumber = play, @@ -477,26 +470,10 @@ namespace DownKyi.ViewModels return; } } + IsEnabled = true; - await UpdateMediaCovers(cancellationToken); }, cancellationToken).ContinueWith(t => { }); } - private readonly StorageCover storageCover = new StorageCover(); - private async Task UpdateMediaCovers(CancellationToken cancellationToken) - { - var currentMedias = _medias.ToList(); - var tasks = currentMedias.Select(async media => - { - if (cancellationToken.IsCancellationRequested) - { - return; - } - var coverUrl = $"{media.CoverUrl}@{200}w_{125}h_1c_!web-space-index-myvideo.webp"; - var bitmap = await storageCover.GetCoverAsync(coverUrl) ?? defaultPic; - media.Cover = bitmap; - }); - await Task.WhenAll(tasks); - } /// /// 初始化页面数据 @@ -530,6 +507,7 @@ namespace DownKyi.ViewModels { return; } + InitView(); _mid = (long)parameter["mid"]; @@ -552,7 +530,7 @@ namespace DownKyi.ViewModels // 页面选择 Pager = new CustomPagerViewModel(1, - (int)Math.Ceiling(double.Parse(selectTab.SubTitle) / _videoNumberInPage)); + (int)Math.Ceiling(double.Parse(selectTab.SubTitle) / VideoNumberInPage)); Pager.CurrentChanged += OnCurrentChanged_Pager; Pager.CountChanged += OnCountChanged_Pager; Pager.Current = 1; diff --git a/DownKyi/ViewModels/ViewSeasonsSeriesViewModel.cs b/DownKyi/ViewModels/ViewSeasonsSeriesViewModel.cs index 97b3524..487f096 100644 --- a/DownKyi/ViewModels/ViewSeasonsSeriesViewModel.cs +++ b/DownKyi/ViewModels/ViewSeasonsSeriesViewModel.cs @@ -34,96 +34,96 @@ public class ViewSeasonsSeriesViewModel : ViewModelBase private int type = 0; // 每页视频数量,暂时在此写死,以后在设置中增加选项 - private readonly int VideoNumberInPage = 30; + private const int VideoNumberInPage = 30; #region 页面属性申明 - private string pageName = Tag; + private string _pageName = Tag; public string PageName { - get => pageName; - set => SetProperty(ref pageName, value); + get => _pageName; + set => SetProperty(ref _pageName, 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 loadingVisibility; + private bool _loadingVisibility; public bool LoadingVisibility { - get => loadingVisibility; - set => SetProperty(ref loadingVisibility, value); + get => _loadingVisibility; + set => SetProperty(ref _loadingVisibility, 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 VectorImage arrowBack; + private VectorImage _arrowBack; public VectorImage ArrowBack { - get => arrowBack; - set => SetProperty(ref arrowBack, value); + get => _arrowBack; + set => SetProperty(ref _arrowBack, value); } - private VectorImage downloadManage; + private VectorImage _downloadManage; public VectorImage DownloadManage { - get => downloadManage; - set => SetProperty(ref downloadManage, value); + get => _downloadManage; + set => SetProperty(ref _downloadManage, value); } - private string title; + private string _title; public string Title { - get => title; - set => SetProperty(ref title, value); + get => _title; + set => SetProperty(ref _title, value); } - private bool isEnabled = true; + private bool _isEnabled = true; public bool IsEnabled { - get => isEnabled; - set => SetProperty(ref isEnabled, value); + get => _isEnabled; + set => SetProperty(ref _isEnabled, value); } - private CustomPagerViewModel pager; + private CustomPagerViewModel _pager; public CustomPagerViewModel Pager { - get => pager; - set => SetProperty(ref pager, value); + get => _pager; + set => SetProperty(ref _pager, value); } - private ObservableCollection medias; + private ObservableCollection _medias; public ObservableCollection Medias { - get => medias; - set => SetProperty(ref medias, value); + get => _medias; + set => SetProperty(ref _medias, value); } - private bool isSelectAll; + private bool _isSelectAll; public bool IsSelectAll { - get => isSelectAll; - set => SetProperty(ref isSelectAll, value); + get => _isSelectAll; + set => SetProperty(ref _isSelectAll, value); } #endregion @@ -131,7 +131,7 @@ public class ViewSeasonsSeriesViewModel : ViewModelBase public ViewSeasonsSeriesViewModel(IEventAggregator eventAggregator, IDialogService dialogService) : base( eventAggregator) { - this.DialogService = dialogService; + DialogService = dialogService; #region 属性初始化 @@ -157,10 +157,9 @@ public class ViewSeasonsSeriesViewModel : ViewModelBase #region 命令申明 // 返回事件 - private DelegateCommand backSpaceCommand; + private DelegateCommand _backSpaceCommand; - public DelegateCommand BackSpaceCommand => - backSpaceCommand ?? (backSpaceCommand = new DelegateCommand(ExecuteBackSpace)); + public DelegateCommand BackSpaceCommand => _backSpaceCommand ??= new DelegateCommand(ExecuteBackSpace); /// /// 返回事件 @@ -182,11 +181,9 @@ public class ViewSeasonsSeriesViewModel : ViewModelBase } // 前往下载管理页面 - private DelegateCommand downloadManagerCommand; + private DelegateCommand _downloadManagerCommand; - public DelegateCommand DownloadManagerCommand => downloadManagerCommand ?? - (downloadManagerCommand = - new DelegateCommand(ExecuteDownloadManagerCommand)); + public DelegateCommand DownloadManagerCommand => _downloadManagerCommand ??= new DelegateCommand(ExecuteDownloadManagerCommand); /// /// 前往下载管理页面 @@ -203,11 +200,9 @@ public class ViewSeasonsSeriesViewModel : ViewModelBase } // 全选按钮点击事件 - private DelegateCommand selectAllCommand; + private DelegateCommand _selectAllCommand; - public DelegateCommand SelectAllCommand => selectAllCommand ?? - (selectAllCommand = - new DelegateCommand(ExecuteSelectAllCommand)); + public DelegateCommand SelectAllCommand => _selectAllCommand ??= new DelegateCommand(ExecuteSelectAllCommand); /// /// 全选按钮点击事件 @@ -232,10 +227,9 @@ public class ViewSeasonsSeriesViewModel : ViewModelBase } // 列表选择事件 - private DelegateCommand mediasCommand; + private DelegateCommand _mediasCommand; - public DelegateCommand MediasCommand => - mediasCommand ?? (mediasCommand = new DelegateCommand(ExecuteMediasCommand)); + public DelegateCommand MediasCommand => _mediasCommand ??= new DelegateCommand(ExecuteMediasCommand); /// /// 列表选择事件 @@ -243,27 +237,18 @@ public class ViewSeasonsSeriesViewModel : ViewModelBase /// private void ExecuteMediasCommand(object parameter) { - if (!(parameter is IList selectedMedia)) + if (parameter is not IList selectedMedia) { return; } - if (selectedMedia.Count == Medias.Count) - { - IsSelectAll = true; - } - else - { - IsSelectAll = false; - } + IsSelectAll = selectedMedia.Count == Medias.Count; } // 添加选中项到下载列表事件 - private DelegateCommand addToDownloadCommand; + private DelegateCommand _addToDownloadCommand; - public DelegateCommand AddToDownloadCommand => addToDownloadCommand ?? - (addToDownloadCommand = - new DelegateCommand(ExecuteAddToDownloadCommand)); + public DelegateCommand AddToDownloadCommand => _addToDownloadCommand ??= new DelegateCommand(ExecuteAddToDownloadCommand); /// /// 添加选中项到下载列表事件 @@ -274,11 +259,9 @@ public class ViewSeasonsSeriesViewModel : ViewModelBase } // 添加所有视频到下载列表事件 - private DelegateCommand addAllToDownloadCommand; + private DelegateCommand _addAllToDownloadCommand; - public DelegateCommand AddAllToDownloadCommand => addAllToDownloadCommand ?? - (addAllToDownloadCommand = - new DelegateCommand(ExecuteAddAllToDownloadCommand)); + public DelegateCommand AddAllToDownloadCommand => _addAllToDownloadCommand ??= new DelegateCommand(ExecuteAddAllToDownloadCommand); /// /// 添加所有视频到下载列表事件 @@ -297,13 +280,13 @@ public class ViewSeasonsSeriesViewModel : ViewModelBase private async void AddToDownload(bool isOnlySelected) { // 频道里只有视频 - AddToDownloadService addToDownloadService = new AddToDownloadService(PlayStreamType.VIDEO); + var addToDownloadService = new AddToDownloadService(PlayStreamType.Video); // 选择文件夹 var directory = await addToDownloadService.SetDirectory(DialogService); // 视频计数 - int i = 0; + var i = 0; await Task.Run(async () => { // 为了避免执行其他操作时, @@ -338,16 +321,9 @@ public class ViewSeasonsSeriesViewModel : ViewModelBase } // 通知用户添加到下载列表的结果 - if (i <= 0) - { - EventAggregator.GetEvent().Publish(DictionaryResource.GetString("TipAddDownloadingZero")); - } - else - { - EventAggregator.GetEvent() - .Publish( - $"{DictionaryResource.GetString("TipAddDownloadingFinished1")}{i}{DictionaryResource.GetString("TipAddDownloadingFinished2")}"); - } + EventAggregator.GetEvent().Publish(i <= 0 + ? DictionaryResource.GetString("TipAddDownloadingZero") + : $"{DictionaryResource.GetString("TipAddDownloadingFinished1")}{i}{DictionaryResource.GetString("TipAddDownloadingFinished2")}"); } private void OnCountChanged_Pager(int count) @@ -486,7 +462,7 @@ public class ViewSeasonsSeriesViewModel : ViewModelBase await Task.Run(() => { - CancellationToken cancellationToken = tokenSource.Token; + var cancellationToken = tokenSource.Token; var seasons = Core.BiliApi.Users.UserSpace.GetSeasonsDetail(mid, id, current, VideoNumberInPage); if (seasons == null || seasons.Meta.Total == 0) @@ -505,25 +481,14 @@ public class ViewSeasonsSeriesViewModel : ViewModelBase //} // 查询、保存封面 - string coverUrl = video.Pic; - Bitmap cover; - if (coverUrl == null || coverUrl == "") + var coverUrl = video.Pic; + if (!coverUrl.ToLower().StartsWith("http")) { - cover = null; // new BitmapImage(new Uri($"pack://application:,,,/Resources/video-placeholder.png")); - } - else - { - if (!coverUrl.ToLower().StartsWith("http")) - { - coverUrl = $"https:{video.Pic}"; - } - - StorageCover storageCover = new StorageCover(); - cover = storageCover.GetCoverThumbnail(video.Aid, video.Bvid, -1, coverUrl, 200, 125); + coverUrl = $"https:{video.Pic}"; } // 播放数 - string play = string.Empty; + var play = string.Empty; if (video.Stat != null) { if (video.Stat.View > 0) @@ -540,19 +505,17 @@ public class ViewSeasonsSeriesViewModel : ViewModelBase play = "--"; } - DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1)); // 当地时区 - DateTime dateCTime = startTime.AddSeconds(video.Ctime); - string ctime = dateCTime.ToString("yyyy-MM-dd"); + var startTime = TimeZoneInfo.ConvertTimeFromUtc(new DateTime(1970, 1, 1), TimeZoneInfo.Local); // 当地时区 + var dateCTime = startTime.AddSeconds(video.Ctime); + var ctime = dateCTime.ToString("yyyy-MM-dd"); App.PropertyChangeAsync(new Action(() => { - ChannelMedia media = new ChannelMedia(EventAggregator) + var media = new ChannelMedia(EventAggregator) { Avid = video.Aid, Bvid = video.Bvid, - Cover = cover ?? - ImageHelper.LoadFromResource( - new Uri($"avares://DownKyi/Resources/video-placeholder.png")), + Cover = coverUrl ?? "avares://DownKyi/Resources/video-placeholder.png", Duration = Format.FormatDuration3(video.Duration), Title = video.Title, PlayNumber = play, @@ -583,11 +546,11 @@ public class ViewSeasonsSeriesViewModel : ViewModelBase await Task.Run(() => { - CancellationToken cancellationToken = tokenSource.Token; + var cancellationToken = tokenSource.Token; var meta = Core.BiliApi.Users.UserSpace.GetSeriesMeta(id); var series = Core.BiliApi.Users.UserSpace.GetSeriesDetail(mid, id, current, VideoNumberInPage); - if (series == null || meta.Meta.Total == 0) + if (series == null || meta?.Meta.Total == 0) { // 没有数据,UI提示 LoadingVisibility = false; @@ -603,25 +566,14 @@ public class ViewSeasonsSeriesViewModel : ViewModelBase //} // 查询、保存封面 - string coverUrl = video.Pic; - Bitmap cover; - if (coverUrl == null || coverUrl == "") + var coverUrl = video.Pic; + if (!coverUrl.ToLower().StartsWith("http")) { - cover = null; // new BitmapImage(new Uri($"pack://application:,,,/Resources/video-placeholder.png")); - } - else - { - if (!coverUrl.ToLower().StartsWith("http")) - { - coverUrl = $"https:{video.Pic}"; - } - - StorageCover storageCover = new StorageCover(); - cover = storageCover.GetCoverThumbnail(video.Aid, video.Bvid, -1, coverUrl, 200, 125); + coverUrl = $"https:{video.Pic}"; } // 播放数 - string play = string.Empty; + var play = string.Empty; if (video.Stat != null) { if (video.Stat.View > 0) @@ -638,17 +590,17 @@ public class ViewSeasonsSeriesViewModel : ViewModelBase play = "--"; } - DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1)); // 当地时区 - DateTime dateCTime = startTime.AddSeconds(video.Ctime); - string ctime = dateCTime.ToString("yyyy-MM-dd"); + var startTime = TimeZoneInfo.ConvertTimeFromUtc(new DateTime(1970, 1, 1), TimeZoneInfo.Local); // 当地时区 + var dateCTime = startTime.AddSeconds(video.Ctime); + var ctime = dateCTime.ToString("yyyy-MM-dd"); - App.PropertyChangeAsync(new Action(() => + App.PropertyChangeAsync(() => { - ChannelMedia media = new ChannelMedia(EventAggregator) + var media = new ChannelMedia(EventAggregator) { Avid = video.Aid, Bvid = video.Bvid, - Cover = cover ?? ImageHelper.LoadFromResource(new Uri("avares://DownKyi/Resources/video-placeholder.png")), + Cover = coverUrl ?? "avares://DownKyi/Resources/video-placeholder.png", Duration = Format.FormatDuration3(video.Duration), Title = video.Title, PlayNumber = play, @@ -658,7 +610,7 @@ public class ViewSeasonsSeriesViewModel : ViewModelBase LoadingVisibility = false; NoDataVisibility = false; - })); + }); // 判断是否该结束线程,若为true,跳出循环 if (cancellationToken.IsCancellationRequested) @@ -700,7 +652,7 @@ public class ViewSeasonsSeriesViewModel : ViewModelBase id = (long)parameter["id"]; type = (int)parameter["type"]; Title = (string)parameter["name"]; - int count = (int)parameter["count"]; + var count = (int)parameter["count"]; // 页面选择 Pager = new CustomPagerViewModel(1, (int)Math.Ceiling((double)count / VideoNumberInPage)); diff --git a/DownKyi/ViewModels/ViewSettingsViewModel.cs b/DownKyi/ViewModels/ViewSettingsViewModel.cs index f24b775..a016506 100644 --- a/DownKyi/ViewModels/ViewSettingsViewModel.cs +++ b/DownKyi/ViewModels/ViewSettingsViewModel.cs @@ -14,39 +14,39 @@ public class ViewSettingsViewModel : ViewModelBase { public const string Tag = "PageSettings"; - private readonly IRegionManager regionManager; + private readonly IRegionManager _regionManager; #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 List tabHeaders; + private List _tabHeaders; public List TabHeaders { - get => tabHeaders; - set => SetProperty(ref tabHeaders, value); + get => _tabHeaders; + set => SetProperty(ref _tabHeaders, value); } - private int selectTabId; + private int _selectTabId; public int SelectTabId { - get => selectTabId; - set => SetProperty(ref selectTabId, value); + get => _selectTabId; + set => SetProperty(ref _selectTabId, value); } #endregion public ViewSettingsViewModel(IRegionManager regionManager, IEventAggregator eventAggregator) : base(eventAggregator) { - this.regionManager = regionManager; + _regionManager = regionManager; #region 属性初始化 @@ -68,17 +68,16 @@ public class ViewSettingsViewModel : 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, @@ -88,12 +87,9 @@ public class ViewSettingsViewModel : ViewModelBase } // 左侧tab点击事件 - private DelegateCommand leftTabHeadersCommand; + private DelegateCommand _leftTabHeadersCommand; - public DelegateCommand LeftTabHeadersCommand => leftTabHeadersCommand ?? - (leftTabHeadersCommand = - new DelegateCommand( - ExecuteLeftTabHeadersCommand)); + public DelegateCommand LeftTabHeadersCommand => _leftTabHeadersCommand ??= new DelegateCommand(ExecuteLeftTabHeadersCommand); /// /// 左侧tab点击事件 @@ -101,44 +97,41 @@ public class ViewSettingsViewModel : ViewModelBase /// private void ExecuteLeftTabHeadersCommand(object parameter) { - if (!(parameter is TabHeader tabHeader)) + if (parameter is not TabHeader tabHeader) { return; } - NavigationParameters param = new NavigationParameters(); - switch (tabHeader.Id) { case 0: - regionManager.RequestNavigate("SettingsContentRegion", ViewBasicViewModel.Tag, param); + _regionManager.RequestNavigate("SettingsContentRegion", ViewBasicViewModel.Tag); break; case 1: - regionManager.RequestNavigate("SettingsContentRegion", ViewNetworkViewModel.Tag, param); + _regionManager.RequestNavigate("SettingsContentRegion", ViewNetworkViewModel.Tag); break; case 2: - regionManager.RequestNavigate("SettingsContentRegion", ViewVideoViewModel.Tag, param); + _regionManager.RequestNavigate("SettingsContentRegion", ViewVideoViewModel.Tag); break; case 3: - regionManager.RequestNavigate("SettingsContentRegion", ViewDanmakuViewModel.Tag, param); + _regionManager.RequestNavigate("SettingsContentRegion", ViewDanmakuViewModel.Tag); break; case 4: - regionManager.RequestNavigate("SettingsContentRegion", ViewAboutViewModel.Tag, param); + _regionManager.RequestNavigate("SettingsContentRegion", ViewAboutViewModel.Tag); break; } } - private DelegateCommand loadedCommand; + private DelegateCommand _loadedCommand; - public DelegateCommand LoadedCommand => - loadedCommand ?? (loadedCommand = new DelegateCommand(ExecuteLoadedCommand)); + public DelegateCommand LoadedCommand => _loadedCommand ??= new DelegateCommand(ExecuteLoadedCommand); /// /// region加载完成事件 /// private void ExecuteLoadedCommand() { - regionManager.RequestNavigate("SettingsContentRegion", ViewBasicViewModel.Tag, new NavigationParameters()); + _regionManager.RequestNavigate("SettingsContentRegion", ViewBasicViewModel.Tag); } #endregion @@ -153,12 +146,9 @@ public class ViewSettingsViewModel : ViewModelBase // 进入设置页面时显示的设置项 SelectTabId = 0; - - PropertyChangeAsync(() => - { - regionManager.RequestNavigate("SettingsContentRegion", ViewBasicViewModel.Tag, new NavigationParameters()); - }); - + + PropertyChangeAsync(() => { _regionManager.RequestNavigate("SettingsContentRegion", ViewBasicViewModel.Tag); }); + ArrowBack.Fill = DictionaryResource.GetColor("ColorTextDark"); } } \ No newline at end of file diff --git a/DownKyi/ViewModels/ViewToolboxViewModel.cs b/DownKyi/ViewModels/ViewToolboxViewModel.cs index 9e3fd92..1cc1ca6 100644 --- a/DownKyi/ViewModels/ViewToolboxViewModel.cs +++ b/DownKyi/ViewModels/ViewToolboxViewModel.cs @@ -13,7 +13,7 @@ namespace DownKyi.ViewModels { public const string Tag = "PageToolbox"; - private readonly IRegionManager regionManager; + private readonly IRegionManager _regionManager; #region 页面属性申明 @@ -38,7 +38,7 @@ namespace DownKyi.ViewModels public ViewToolboxViewModel(IRegionManager regionManager, IEventAggregator eventAggregator) : base( eventAggregator) { - this.regionManager = regionManager; + _regionManager = regionManager; #region 属性初始化 @@ -89,18 +89,16 @@ namespace DownKyi.ViewModels return; } - var param = new NavigationParameters(); - switch (tabHeader.Id) { case 0: - regionManager.RequestNavigate("ToolboxContentRegion", ViewBiliHelperViewModel.Tag, param); + _regionManager.RequestNavigate("ToolboxContentRegion", ViewBiliHelperViewModel.Tag); break; case 1: - regionManager.RequestNavigate("ToolboxContentRegion", ViewDelogoViewModel.Tag, param); + _regionManager.RequestNavigate("ToolboxContentRegion", ViewDelogoViewModel.Tag); break; case 2: - regionManager.RequestNavigate("ToolboxContentRegion", ViewExtractMediaViewModel.Tag, param); + _regionManager.RequestNavigate("ToolboxContentRegion", ViewExtractMediaViewModel.Tag); break; } } @@ -117,11 +115,7 @@ namespace DownKyi.ViewModels // 进入设置页面时显示的设置项 SelectTabId = 0; - PropertyChangeAsync(() => - { - regionManager.RequestNavigate("ToolboxContentRegion", ViewBiliHelperViewModel.Tag, - new NavigationParameters()); - }); + PropertyChangeAsync(() => { _regionManager.RequestNavigate("ToolboxContentRegion", ViewBiliHelperViewModel.Tag); }); } } } \ No newline at end of file diff --git a/DownKyi/ViewModels/ViewUserSpaceViewModel.cs b/DownKyi/ViewModels/ViewUserSpaceViewModel.cs index ac583e9..50de80c 100644 --- a/DownKyi/ViewModels/ViewUserSpaceViewModel.cs +++ b/DownKyi/ViewModels/ViewUserSpaceViewModel.cs @@ -84,17 +84,17 @@ public class ViewUserSpaceViewModel : ViewModelBase set => SetProperty(ref _topNavigationBg, value); } - private Bitmap _background; + private string _background; - public Bitmap Background + public string Background { get => _background; set => SetProperty(ref _background, value); } - private Bitmap _header; + private string _header; - public Bitmap Header + public string Header { get => _header; set => SetProperty(ref _header, value); @@ -185,7 +185,7 @@ public class ViewUserSpaceViewModel : ViewModelBase public ViewUserSpaceViewModel(IRegionManager regionManager, IEventAggregator eventAggregator) : base( eventAggregator) { - this._regionManager = regionManager; + _regionManager = regionManager; #region 属性初始化 @@ -277,21 +277,13 @@ public class ViewUserSpaceViewModel : ViewModelBase return; } - Dictionary data = new Dictionary + var data = new Dictionary { { "mid", mid }, { "friendId", 0 } }; - string parentViewName; - if (ParentView == ViewFriendsViewModel.Tag) - { - parentViewName = ViewIndexViewModel.Tag; - } - else - { - parentViewName = Tag; - } + var parentViewName = ParentView == ViewFriendsViewModel.Tag ? ViewIndexViewModel.Tag : Tag; switch (banner.Id) { @@ -347,7 +339,7 @@ public class ViewUserSpaceViewModel : ViewModelBase private async void UpdateSpaceInfo() { var isNoData = true; - Uri? toutuUri = null; + string? toutuUri = null; string? headerUri = null; Uri? sexUri = null; Uri? levelUri = null; @@ -356,16 +348,7 @@ public class ViewUserSpaceViewModel : ViewModelBase { // 背景图片 var spaceSettings = Core.BiliApi.Users.UserSpace.GetSpaceSettings(mid); - if (spaceSettings != null) - { - var storageCover = new StorageCover(); - var toutu = storageCover.GetCover($"https://i0.hdslb.com/{spaceSettings.Toutu.Limg}"); - toutuUri = new Uri(toutu); - } - else - { - toutuUri = new Uri("avares://DownKyi/Resources/backgound/9-绿荫秘境.png"); - } + toutuUri = spaceSettings != null ? $"https://i0.hdslb.com/{spaceSettings.Toutu.Limg}" : "avares://DownKyi/Resources/backgound/9-绿荫秘境.png"; // 用户信息 var userInfo = UserInfo.GetUserInfoForSpace(mid); @@ -374,8 +357,7 @@ public class ViewUserSpaceViewModel : ViewModelBase isNoData = false; // 头像 - var storageHeader = new StorageHeader(); - headerUri = storageHeader.GetHeader(mid, userInfo.Name, userInfo.Face); + headerUri = userInfo.Face; // 用户名 UserName = userInfo.Name; sexUri = userInfo.Sex switch @@ -432,8 +414,7 @@ public class ViewUserSpaceViewModel : ViewModelBase else { // 头像 - var storageHeader = new StorageHeader(); - Header = storageHeader.GetHeaderThumbnail(headerUri, 64, 64); + Header = headerUri; // 性别 Sex = sexUri == null ? null : ImageHelper.LoadFromResource(sexUri); // 等级 @@ -441,7 +422,7 @@ public class ViewUserSpaceViewModel : ViewModelBase ArrowBack.Fill = DictionaryResource.GetColor("ColorText"); TopNavigationBg = DictionaryResource.GetColor("ColorMask100"); - Background = ImageHelper.LoadFromResource(toutuUri); + Background = toutuUri; ViewVisibility = true; LoadingVisibility = false; @@ -453,7 +434,7 @@ public class ViewUserSpaceViewModel : ViewModelBase // 投稿视频 List? publicationTypes = null; await Task.Run(() => { publicationTypes = Core.BiliApi.Users.UserSpace.GetPublicationType(mid); }); - if (publicationTypes != null && publicationTypes.Count > 0) + if (publicationTypes is { Count: > 0 }) { TabLeftBanners.Add(new TabLeftBanner { diff --git a/DownKyi/ViewModels/ViewVideoDetailViewModel.cs b/DownKyi/ViewModels/ViewVideoDetailViewModel.cs index 4c4dd5e..b79c22d 100644 --- a/DownKyi/ViewModels/ViewVideoDetailViewModel.cs +++ b/DownKyi/ViewModels/ViewVideoDetailViewModel.cs @@ -217,11 +217,11 @@ public class ViewVideoDetailViewModel : ViewModelBase foreach (var section in VideoSections) { var cache = CaCheVideoSections.FirstOrDefault(e => e.Id == section.Id); - if (cache != null) - { - var pages = cache.VideoPages.Where(e => e.Name.Contains(InputSearchText)).ToList(); - section.VideoPages = pages; - } + + if (cache == null) continue; + + var pages = cache.VideoPages.Where(e => e.Name.Contains(InputSearchText)).ToList(); + section.VideoPages = pages; } } }); @@ -250,7 +250,7 @@ public class ViewVideoDetailViewModel : ViewModelBase UnityUpdateView(UpdateView, _input, null, true); // 是否自动解析视频 - if (SettingsManager.GetInstance().IsAutoParseVideo() == AllowStatus.YES) + if (SettingsManager.GetInstance().GetIsAutoParseVideo() == AllowStatus.Yes) { PropertyChangeAsync(ExecuteParseAllVideoCommand); } @@ -301,6 +301,7 @@ public class ViewVideoDetailViewModel : ViewModelBase /// private async void ExecuteCopyCoverUrlCommand() { + if (_videoInfoView?.CoverUrl == null) return; // 复制封面url到剪贴板 await ClipboardManager.SetText(_videoInfoView.CoverUrl); LogManager.Info(Tag, "复制封面url到剪贴板"); @@ -361,9 +362,10 @@ public class ViewVideoDetailViewModel : ViewModelBase { return; } + var avids = new HashSet(parameter.Cast().Select(x => x.Cid)); section.VideoPages.ToList().ForEach(videoPage => - videoPage.IsSelected = avids.Contains(videoPage.Cid) + videoPage.IsSelected = avids.Contains(videoPage.Cid) ); IsSelectAll = section.VideoPages.Count == videoPages.Count && section.VideoPages.Count != 0; } @@ -457,7 +459,7 @@ public class ViewVideoDetailViewModel : ViewModelBase var parseScope = SettingsManager.GetInstance().GetParseScope(); // 是否选择了解析范围 - if (parseScope == ParseScope.NONE) + if (parseScope == ParseScope.None) { //打开解析选择器 await DialogService?.ShowDialogAsync(ViewParsingSelectorViewModel.Tag, null, async result => @@ -494,9 +496,9 @@ public class ViewVideoDetailViewModel : ViewModelBase switch (parseScope) { - case ParseScope.NONE: + case ParseScope.None: break; - case ParseScope.SELECTED_ITEM: + case ParseScope.SelectedItem: foreach (var section in VideoSections) { foreach (var page in section.VideoPages) @@ -510,7 +512,7 @@ public class ViewVideoDetailViewModel : ViewModelBase } break; - case ParseScope.CURRENT_SECTION: + case ParseScope.CurrentSection: foreach (var section in VideoSections) { if (section.IsSelected) @@ -524,7 +526,7 @@ public class ViewVideoDetailViewModel : ViewModelBase } break; - case ParseScope.ALL: + case ParseScope.All: foreach (var section in VideoSections) { foreach (var page in section.VideoPages) @@ -551,8 +553,8 @@ public class ViewVideoDetailViewModel : ViewModelBase LoadingVisibility = false; // 解析后是否自动下载解析视频 - var isAutoDownloadAll = SettingsManager.GetInstance().IsAutoDownloadAll(); - if (parseScope != ParseScope.NONE && isAutoDownloadAll == AllowStatus.YES) + var isAutoDownloadAll = SettingsManager.GetInstance().GetIsAutoDownloadAll(); + if (parseScope != ParseScope.None && isAutoDownloadAll == AllowStatus.Yes) { AddToDownload(true); } @@ -731,18 +733,18 @@ public class ViewVideoDetailViewModel : ViewModelBase // 视频 if (ParseEntrance.IsAvUrl(_input) || ParseEntrance.IsBvUrl(_input)) { - addToDownloadService = new AddToDownloadService(PlayStreamType.VIDEO); + addToDownloadService = new AddToDownloadService(PlayStreamType.Video); } // 番剧(电影、电视剧) else if (ParseEntrance.IsBangumiSeasonUrl(_input) || ParseEntrance.IsBangumiEpisodeUrl(_input) || ParseEntrance.IsBangumiMediaUrl(_input)) { - addToDownloadService = new AddToDownloadService(PlayStreamType.BANGUMI); + addToDownloadService = new AddToDownloadService(PlayStreamType.Bangumi); } // 课程 else if (ParseEntrance.IsCheeseSeasonUrl(_input) || ParseEntrance.IsCheeseEpisodeUrl(_input)) { - addToDownloadService = new AddToDownloadService(PlayStreamType.CHEESE); + addToDownloadService = new AddToDownloadService(PlayStreamType.Cheese); } else { diff --git a/DownKyi/Views/Friends/ViewFollower.axaml b/DownKyi/Views/Friends/ViewFollower.axaml index 92d3ddc..1c5883b 100644 --- a/DownKyi/Views/Friends/ViewFollower.axaml +++ b/DownKyi/Views/Friends/ViewFollower.axaml @@ -6,7 +6,8 @@ xmlns:custom="clr-namespace:DownKyi.CustomControl" x:DataType="vmf:ViewFollowerViewModel" xmlns:i="using:Avalonia.Xaml.Interactivity" - xmlns:iac="clr-namespace:Avalonia.Xaml.Interactions.Custom;assembly=Avalonia.Xaml.Interactions.Custom"> + xmlns:iac="clr-namespace:Avalonia.Xaml.Interactions.Custom;assembly=Avalonia.Xaml.Interactions.Custom" + xmlns:asyncImageLoader="clr-namespace:DownKyi.CustomControl.AsyncImageLoader"> @@ -29,7 +30,7 @@ Grid.Column="0" Width="64" Height="64" - Source="{Binding Header}"> + asyncImageLoader:ImageLoader.Source="{Binding Header}"> + xmlns:ia="clr-namespace:Avalonia.Xaml.Interactions.Core;assembly=Avalonia.Xaml.Interactions" + xmlns:asyncImageLoader="clr-namespace:DownKyi.CustomControl.AsyncImageLoader"> @@ -31,7 +32,7 @@ Grid.Column="0" Width="64" Height="64" - Source="{Binding Header}"> + asyncImageLoader:ImageLoader.Source="{Binding Header}"> + IsChecked="{Binding UseSsl, Mode=TwoWay}" /> + IsChecked="{Binding Aria2C}" /> + IsChecked="{Binding CustomAria2C}" /> - - - - - - + + + + + + + + + + + + + + + + + + + + + + - + + xmlns:ia="clr-namespace:Avalonia.Xaml.Interactions.Core;assembly=Avalonia.Xaml.Interactions" + xmlns:asyncImageLoader="clr-namespace:DownKyi.CustomControl.AsyncImageLoader"> - + @@ -25,7 +26,7 @@ Grid.Column="0" Width="36" Height="36" - Source="{Binding Header}"> + asyncImageLoader:ImageLoader.Source="{Binding Header}"> + xmlns:ia="clr-namespace:Avalonia.Xaml.Interactions.Core;assembly=Avalonia.Xaml.Interactions" + xmlns:asyncImageLoader="clr-namespace:DownKyi.CustomControl.AsyncImageLoader"> @@ -34,7 +35,7 @@ CornerRadius="5"> - + diff --git a/DownKyi/Views/ViewMyFavorites.axaml b/DownKyi/Views/ViewMyFavorites.axaml index 2ab03d8..3b52cc9 100644 --- a/DownKyi/Views/ViewMyFavorites.axaml +++ b/DownKyi/Views/ViewMyFavorites.axaml @@ -6,6 +6,7 @@ xmlns:ia="clr-namespace:Avalonia.Xaml.Interactions.Core;assembly=Avalonia.Xaml.Interactions" xmlns:vm="clr-namespace:DownKyi.ViewModels" xmlns:vmp="clr-namespace:DownKyi.ViewModels.PageViewModels" + xmlns:asyncImageLoader="clr-namespace:DownKyi.CustomControl.AsyncImageLoader" x:DataType="vm:ViewMyFavoritesViewModel"> @@ -40,7 +41,7 @@ - + + xmlns:ia="clr-namespace:Avalonia.Xaml.Interactions.Core;assembly=Avalonia.Xaml.Interactions" + xmlns:asyncImageLoader="clr-namespace:DownKyi.CustomControl.AsyncImageLoader"> @@ -40,7 +41,7 @@ CornerRadius="5"> - + @@ -143,7 +144,7 @@ VerticalAlignment="Center" CornerRadius="12"> - + @@ -30,7 +31,7 @@ Grid.Row="0" HorizontalAlignment="Center" VerticalAlignment="Center" - Source="{Binding Background}" + asyncImageLoader:ImageLoader.Source="{Binding Background}" Stretch="UniformToFill" /> @@ -39,7 +40,7 @@ Grid.Column="0" Width="64" Height="64" - Source="{Binding Header}"> + asyncImageLoader:ImageLoader.Source="{Binding Header}"> @@ -29,7 +30,7 @@ CornerRadius="5"> - + @@ -84,7 +85,7 @@ VerticalAlignment="Center" CornerRadius="12"> - + @@ -64,7 +65,7 @@ Grid.Column="0" Margin="10,10,10,10" Orientation="Vertical"> - + @@ -222,7 +223,7 @@ + asyncImageLoader:ImageLoader.Source="{Binding Favorites.UpHeader}"> @@ -26,7 +27,7 @@ CornerRadius="5"> - + @@ -41,7 +42,7 @@ CornerRadius="5"> - + @@ -124,7 +125,7 @@ Grid.Row="0" HorizontalAlignment="Center" VerticalAlignment="Center" - Source="{Binding Background}" + asyncImageLoader:ImageLoader.Source="{Binding Background}" Stretch="UniformToFill" /> @@ -133,7 +134,7 @@ Grid.Column="0" Width="64" Height="64" - Source="{Binding Header}"> + asyncImageLoader:ImageLoader.Source="{Binding Header}"> @@ -96,7 +97,7 @@ MaxWidth="300" VerticalAlignment="Top" DockPanel.Dock="Left" - Source="{Binding VideoInfoView.Cover}"> + asyncImageLoader:ImageLoader.Source="{Binding VideoInfoView.CoverUrl}"> @@ -112,7 +113,7 @@ - + asyncImageLoader:ImageLoader.Source="{Binding VideoInfoView.UpHeader}"> - diff --git a/README.md b/README.md index 7f3db12..393ad76 100644 --- a/README.md +++ b/README.md @@ -32,6 +32,6 @@ ## 免责申明 1. 本软件只提供视频解析,不提供任何资源上传、存储到服务器的功能。 2. 本软件仅解析来自B站的内容,不会对解析到的音视频进行二次编码,部分视频会进行有限的格式转换、拼接等操作。 -3. 本软件解析得到的所有内容均来自B站UP主上传、分享,其版权均归原作者所有。内容提供者、上传者(UP主)应对其提供、上传的内容承担全部责任。 +3. 本软件解析得到的所有内容均来自B站UP主上传、分享,其版权均归原作者所有。内容提供者、上传者(UP主)应对其提供、上传的内容承担全部责任。 4. **本软件提供的所有内容,仅可用作学习交流使用,未经原作者授权,禁止用于其他用途。请在下载24小时内删除。为尊重作者版权,请前往资源的原始发布网站观看,支持原创,谢谢。** 5. 因使用本软件产生的版权问题,软件作者概不负责。 \ No newline at end of file