diff --git a/src/Core/Common.cs b/src/Core/Common.cs
deleted file mode 100644
index 61ac6ab..0000000
--- a/src/Core/Common.cs
+++ /dev/null
@@ -1,440 +0,0 @@
-using System;
-using System.Text.RegularExpressions;
-
-namespace Core
-{
- public static class Common
- {
- // 配置文件所在路径
- public static readonly string ConfigPath = "./Config/";
-
- // 日志、历史等文件所在路径
- public static readonly string RecordPath = "./Config/";
-
- ///
- /// 判断字符串是否以http或https开头,且域名为bilibili.com
- ///
- ///
- ///
- public static bool IsUrl(string input)
- {
- if (input.StartsWith("http://") || input.StartsWith("https://"))
- {
- if (input.Contains("www.bilibili.com")) { return true; }
- else { return false; }
- }
- else { return false; }
- }
-
-
- ///
- /// 判断是否为avid
- ///
- ///
- ///
- public static bool IsAvid(string input)
- {
- if (input.StartsWith("av"))
- {
- bool isInt = Regex.IsMatch(input.Remove(0, 2), @"^\d+$");
- return isInt;
- }
- return false;
- }
-
- ///
- /// 判断是否为bvid
- ///
- ///
- ///
- public static bool IsBvid(string input)
- {
- if (input.StartsWith("BV") && input.Length == 12)
- {
- return true;
- }
- return false;
- }
-
- ///
- /// 判断是否是用户空间的url
- ///
- ///
- ///
- public static bool IsUserSpaceUrl(string input)
- {
- if (input.StartsWith("http://") || input.StartsWith("https://"))
- {
- if (input.Contains("space.bilibili.com"))
- {
- return true;
- }
- else { return false; }
- }
- else { return false; }
- }
-
- ///
- /// 判断是否是用户id
- ///
- ///
- ///
- public static bool IsUserId(string input)
- {
- string inputLower = input.ToLower();
- if (inputLower.StartsWith("uid:"))
- {
- string uid = inputLower.TrimStart(new char[] { 'u', 'i', 'd', ':' });
- return IsInt(uid);
- }
- else if (inputLower.StartsWith("uid"))
- {
- string uid = inputLower.TrimStart(new char[] { 'u', 'i', 'd' });
- return IsInt(uid);
- }
- else { return false; }
- }
-
- ///
- /// 获取用户id
- ///
- ///
- ///
- public static long GetUserId(string url)
- {
- string[] strList = url.Split('?');
- string baseUrl = strList[0];
-
- var match = Regex.Match(baseUrl, @"\d+");
- if (match.Success)
- {
- return GetInt(match.Value);
- }
- else
- {
- return -1;
- }
- }
-
- ///
- /// 从url中解析id,包括bvid和番剧的id
- ///
- ///
- ///
- public static string GetVideoId(string url)
- {
- string[] strList = url.Split('?');
- string baseUrl = strList[0];
-
- string[] str2List = baseUrl.Split('/');
- string id = str2List[str2List.Length - 1];
-
- if (id == "")
- {
- // 字符串末尾
- return str2List[str2List.Length - 2];
- }
-
- return id;
- }
-
- ///
- /// 判断是视频还是番剧
- ///
- ///
- ///
- public static VideoType GetVideoType(string url)
- {
- if (url.ToLower().Contains("/video/bv"))
- {
- return VideoType.VIDEO;
- }
-
- if (url.ToLower().Contains("/video/av"))
- {
- return VideoType.VIDEO_AV;
- }
-
- if (url.ToLower().Contains("/bangumi/play/ss"))
- {
- return VideoType.BANGUMI_SEASON;
- }
-
- if (url.ToLower().Contains("/bangumi/play/ep"))
- {
- return VideoType.BANGUMI_EPISODE;
- }
-
- if (url.ToLower().Contains("/bangumi/media/md"))
- {
- return VideoType.BANGUMI_MEDIA;
- }
-
- if (url.ToLower().Contains("/cheese/play/ss"))
- {
- return VideoType.CHEESE_SEASON;
- }
-
- if (url.ToLower().Contains("/cheese/play/ep"))
- {
- return VideoType.CHEESE_EPISODE;
- }
-
- return VideoType.NONE;
- }
-
- ///
- /// 格式化Duration时间
- ///
- ///
- ///
- public static string FormatDuration(long duration)
- {
- string formatDuration;
- if (duration / 60 > 0)
- {
- long dur = duration / 60;
- if (dur / 60 > 0)
- {
- formatDuration = $"{dur / 60}h{dur % 60}m{duration % 60}s";
- }
- else
- {
- formatDuration = $"{duration / 60}m{duration % 60}s";
- }
- }
- else
- {
- formatDuration = $"{duration}s";
- }
- return formatDuration;
- }
-
- ///
- /// 格式化Duration时间,格式为00:00:00
- ///
- ///
- ///
- public static string FormatDuration2(long duration)
- {
- string formatDuration;
- if (duration / 60 > 0)
- {
- long dur = duration / 60;
- if (dur / 60 > 0)
- {
- formatDuration = string.Format("{0:D2}", dur / 60) + ":" + string.Format("{0:D2}", dur % 60) + ":" + string.Format("{0:D2}", duration % 60);
- }
- else
- {
- formatDuration = "00:" + string.Format("{0:D2}", duration / 60) + ":" + string.Format("{0:D2}", duration % 60);
- }
- }
- else
- {
- formatDuration = "00:00:" + string.Format("{0:D2}", duration);
- }
- return formatDuration;
- }
-
- ///
- /// 格式化Duration时间,格式为00:00
- ///
- ///
- ///
- public static string FormatDuration3(long duration)
- {
- string formatDuration;
- if (duration / 60 > 0)
- {
- long dur = duration / 60;
- if (dur / 60 > 0)
- {
- formatDuration = string.Format("{0:D2}", dur / 60) + ":" + string.Format("{0:D2}", dur % 60) + ":" + string.Format("{0:D2}", duration % 60);
- }
- else
- {
- formatDuration = string.Format("{0:D2}", duration / 60) + ":" + string.Format("{0:D2}", duration % 60);
- }
- }
- else
- {
- formatDuration = "00:" + string.Format("{0:D2}", duration);
- }
- return formatDuration;
- }
-
- ///
- /// 格式化数字,超过10000的数字将单位改为万,超过100000000的数字将单位改为亿,并保留1位小数
- ///
- ///
- ///
- public static string FormatNumber(long number)
- {
- if (number > 99999999)
- {
- return (number / 100000000.0f).ToString("F1") + "亿";
- }
-
- if (number > 9999)
- {
- return (number / 10000.0f).ToString("F1") + "万";
- }
- else
- {
- return number.ToString();
- }
- }
-
- ///
- /// 去除非法字符
- ///
- ///
- ///
- public static string FormatFileName(string originName)
- {
- string destName = originName;
- // Windows中不能作为文件名的字符
- destName = destName.Replace("\\", " ");
- destName = destName.Replace("/", " ");
- destName = destName.Replace(":", " ");
- destName = destName.Replace("*", " ");
- destName = destName.Replace("?", " ");
- destName = destName.Replace("\"", " ");
- destName = destName.Replace("<", " ");
- destName = destName.Replace(">", " ");
- destName = destName.Replace("|", " ");
-
- // 转义字符
- destName = destName.Replace("\a", "");
- destName = destName.Replace("\b", "");
- destName = destName.Replace("\f", "");
- destName = destName.Replace("\n", "");
- destName = destName.Replace("\r", "");
- destName = destName.Replace("\t", "");
- destName = destName.Replace("\v", "");
-
- // 控制字符
- destName = Regex.Replace(destName, @"\p{C}+", string.Empty);
-
- return destName.Trim();
- }
-
- ///
- /// 格式化网速
- ///
- ///
- ///
- public static string FormatSpeed(float speed)
- {
- string formatSpeed;
- if (speed <= 0)
- {
- formatSpeed = "0B/s";
- }
- else if (speed < 1024)
- {
- formatSpeed = speed.ToString("#.##") + "B/s";
- }
- else if (speed < 1024 * 1024)
- {
- formatSpeed = (speed / 1024).ToString("#.##") + "KB/s";
- }
- else
- {
- formatSpeed = (speed / 1024 / 1024).ToString("#.##") + "MB/s";
- }
- return formatSpeed;
- }
-
- ///
- /// 格式化字节大小,可用于文件大小的显示
- ///
- ///
- ///
- public static string FormatFileSize(long fileSize)
- {
- string formatFileSize;
- if (fileSize <= 0)
- {
- formatFileSize = "0B";
- }
- else if (fileSize < 1024)
- {
- formatFileSize = fileSize.ToString() + "B";
- }
- else if (fileSize < 1024 * 1024)
- {
- formatFileSize = (fileSize / 1024.0).ToString("#.##") + "KB";
- }
- else if (fileSize < 1024 * 1024 * 1024)
- {
- formatFileSize = (fileSize / 1024.0 / 1024.0).ToString("#.##") + "MB";
- }
- else
- {
- formatFileSize = (fileSize / 1024.0 / 1024.0 / 1024.0).ToString("#.##") + "GB";
- }
- return formatFileSize;
- }
-
- private static long GetInt(string value)
- {
- if (IsInt(value))
- {
- return long.Parse(value);
- }
- else
- {
- return -1;
- }
- }
-
- private static bool IsInt(string value)
- {
- return Regex.IsMatch(value, @"^\d+$");
- }
-
- }
-
-
- ///
- /// 支持的视频类型
- ///
- public enum VideoType
- {
- NONE,
- VIDEO, // 对应 /video/BV
- VIDEO_AV, // 对应 /video/av
- // BANGUMI, // BANGUMI细分为以下三个部分
- BANGUMI_SEASON, // 对应 /bangumi/play/ss
- BANGUMI_EPISODE, // 对应 /bangumi/play/ep
- BANGUMI_MEDIA, // 对应 /bangumi/media/md
- CHEESE_SEASON, // 对应 /cheese/play/ss
- CHEESE_EPISODE // 对应 /cheese/play/ep
- }
-
- ///
- /// 线程
- ///
- public enum ThreadStatus
- {
- MAIN_UI, // 主线程
- START_PARSE, // 开始解析url
- ADD_ALL_TO_DOWNLOAD,
- START_DOWNLOAD
- }
-
- ///
- /// 视频的编码格式,flv也视为编码放这里
- ///
- [Serializable]
- public enum VideoCodec
- {
- NONE = 1,
- AVC,
- HEVC,
- FLV
- }
-
-}
diff --git a/src/Core/Downloader.cs b/src/Core/Downloader.cs
deleted file mode 100644
index 02e3459..0000000
--- a/src/Core/Downloader.cs
+++ /dev/null
@@ -1,534 +0,0 @@
-using Core.entity;
-using Core.settings;
-using Newtonsoft.Json;
-using System;
-using System.Net;
-using System.Text.RegularExpressions;
-
-namespace Core
-{
- public static class Downloader
- {
- ///
- /// 获得远程文件的大小
- ///
- ///
- ///
- ///
- public static long GetRemoteFileSize(string url, string referer)
- {
- try
- {
- HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
- request.Method = "GET";
- request.Timeout = 30 * 1000;
- request.UserAgent = Utils.GetUserAgent();
- //request.ContentType = "text/html;charset=UTF-8";
- request.Headers["accept-language"] = "zh-CN,zh;q=0.9,en;q=0.8";
- request.Referer = referer;
-
- HttpWebResponse response = (HttpWebResponse)request.GetResponse();
- return response.ContentLength;
- }
- catch (Exception e)
- {
- Console.WriteLine("GetRemoteFileSize()发生异常: {0}", e);
- return 0;
- }
- }
-
- ///
- /// 获得视频详情及播放列表
- ///
- ///
- ///
- public static VideoViewData GetVideoInfo(string bvid, long aid, string referer, bool isBackup = false)
- {
- string url;
- if (bvid != null)
- {
- url = $"https://api.bilibili.com/x/web-interface/view?bvid={bvid}";
- }
- else if (aid >= 0)
- {
- url = $"https://api.bilibili.com/x/web-interface/view?aid={aid}";
- }
- else
- { return null; }
-
- // 采用备用的api,只能获取cid
- if (isBackup)
- {
- string backupUrl = $"https://api.bilibili.com/x/player/pagelist?bvid={bvid}&jsonp=jsonp";
- url = backupUrl;
- }
-
- string response = Utils.RequestWeb(url, referer);
-
- try
- {
- VideoView videoView;
- if (isBackup)
- {
- Pagelist pagelist = JsonConvert.DeserializeObject(response);
-
- videoView = new VideoView
- {
- code = pagelist.code,
- message = pagelist.message,
- ttl = pagelist.ttl
- };
- videoView.data.pages = pagelist.data;
- }
- else
- {
- videoView = JsonConvert.DeserializeObject(response);
- }
-
- if (videoView != null)
- {
- if (videoView.data != null)
- {
- return videoView.data;
- }
- else
- {
- return null;
-
- // 进入备选的url中
- //return GetVideoInfo(bvid, referer, true);
- }
- }
- else
- {
- return null;
- }
- }
- catch (JsonReaderException e)
- {
- Console.WriteLine("GetVideoInfo()发生JsonReader异常: {0}", e);
- return null;
- }
- catch (Exception e)
- {
- Console.WriteLine("GetVideoInfo()发生异常: {0}", e);
- return null;
- }
- }
-
- ///
- /// 通过seasonId获得番剧的剧集详情
- ///
- ///
- ///
- public static BangumiSeasonResult GetBangumiSeason(long seasonId, string referer)
- {
- string url = $"https://api.bilibili.com/pgc/view/web/season?season_id={seasonId}";
- string response = Utils.RequestWeb(url, referer);
-
- try
- {
- BangumiSeason bangumiSeason = JsonConvert.DeserializeObject(response);
- if (bangumiSeason != null) { return bangumiSeason.result; }
- else { return null; }
- }
- catch (JsonReaderException e)
- {
- Console.WriteLine("GetBangumiSeason()发生JsonReader异常: {0}", e);
- return null;
- }
- catch (Exception e)
- {
- Console.WriteLine("GetBangumiSeason()发生异常: {0}", e);
- return null;
- }
- }
-
- public static long GetBangumiSeasonIdByMedia(long mediaId, string referer)
- {
- string url = $"https://api.bilibili.com/pgc/review/user?media_id={mediaId}";
- string response = Utils.RequestWeb(url, referer);
-
- try
- {
- BangumiMedia bangumiMedia = JsonConvert.DeserializeObject(response);
- if (bangumiMedia.result.media != null) { return bangumiMedia.result.media.season_id; }
- else { return 0; }
- }
- catch (JsonReaderException e)
- {
- Console.WriteLine("GetBangumiSeasonIdByMedia()发生JsonReader异常: {0}", e);
- return 0;
- }
- catch (Exception e)
- {
- Console.WriteLine("GetBangumiSeasonIdByMedia()发生异常: {0}", e);
- return 0;
- }
- }
-
- public static long GetBangumiSeasonIdByEpisode(long episode, string referer)
- {
- string url = $"https://www.bilibili.com/bangumi/play/ep{episode}";
- string response = Utils.RequestWeb(url, referer);
-
- // "ssId": 28324,
- string pattern = "\"ssId\":\\s?\\d+,";
- Regex regex = new Regex(pattern);
- Match match = regex.Match(response);
-
- // 删除多余的字符
- string ssId = match.Value.Replace("ssId", "");
- ssId = ssId.Replace("\"", "");
- ssId = ssId.Replace(":", "");
- ssId = ssId.Replace(" ", "");
- ssId = ssId.Replace(",", "");
-
- long seasonId;
- try
- {
- seasonId = long.Parse(ssId);
- }
- catch (FormatException e)
- {
- Console.WriteLine("GetBangumiSeasonIdByEpisode()发生异常: {0}", e);
- return 0;
- }
- return seasonId;
- }
-
- ///
- /// 通过ep_id获得课程的信息
- ///
- ///
- ///
- ///
- public static CheeseSeasonData GetCheeseSeason(long seasonId, long episode, string referer)
- {
- string url = $"https://api.bilibili.com/pugv/view/web/season?";
- if (seasonId != 0)
- {
- url += $"season_id={seasonId}";
- }
- else if (episode != 0)
- {
- url += $"ep_id={episode}";
- }
-
- string response = Utils.RequestWeb(url, referer);
-
- try
- {
- CheeseSeason cheeseSeason = JsonConvert.DeserializeObject(response);
- if (cheeseSeason != null) { return cheeseSeason.data; }
- else { return null; }
- }
- catch (JsonReaderException e)
- {
- Console.WriteLine("GetCheeseSeason()发生JsonReader异常: {0}", e);
- return null;
- }
- catch (Exception e)
- {
- Console.WriteLine("GetCheeseSeason()发生异常: {0}", e);
- return null;
- }
- }
-
- //public static long GetCheeseEpisodeIdBySeasonId(long seasonId, string referer)
- //{
- // string url = $"https://api.bilibili.com/pugv/view/web/ep/list?season_id={seasonId}&pn=1";
- // string response = Utils.RequestWeb(url, referer);
-
- // try
- // {
- // CheeseList cheeseList = JsonConvert.DeserializeObject(response);
- // if (cheeseList.data.items != null && cheeseList.data.items.Count > 0)
- // {
- // return cheeseList.data.items[0].id;
- // }
- // else { return 0; }
- // }
- // catch (JsonReaderException e)
- // {
- // Console.WriteLine("发生异常: {0}", e);
- // return 0;
- // }
- //}
-
- ///
- /// 获得音视频流链接
- ///
- /// 视频的bvid
- /// 视频的cid
- public static PlayUrlData GetStreamInfo(string bvid, long avid, long cid, long episodeId, int quality, string referer, bool isProxy = false, int proxy = 0)
- {
- string baseUrlVideo = "https://api.bilibili.com/x/player/playurl";
- string baseUrlSeason = "https://api.bilibili.com/pgc/player/web/playurl";
- string baseUrlCheese = "https://api.bilibili.com/pugv/player/web/playurl";
- string baseUrl;
- VideoType videoType = Common.GetVideoType(referer);
- switch (videoType)
- {
- case VideoType.VIDEO:
- baseUrl = baseUrlVideo;
- break;
- case VideoType.VIDEO_AV:
- baseUrl = baseUrlVideo;
- break;
- case VideoType.BANGUMI_SEASON:
- baseUrl = baseUrlSeason;
- break;
- case VideoType.BANGUMI_EPISODE:
- baseUrl = baseUrlSeason;
- break;
- case VideoType.BANGUMI_MEDIA:
- baseUrl = baseUrlSeason;
- break;
- case VideoType.CHEESE_SEASON:
- baseUrl = baseUrlCheese;
- break;
- case VideoType.CHEESE_EPISODE:
- baseUrl = baseUrlCheese;
- break;
- default:
- baseUrl = baseUrlVideo;
- break;
- }
- // TODO 没有的参数不加入url
- //string url = $"{baseUrl}?cid={cid}&bvid={bvid}&avid={avid}&ep_id={episodeId}&qn={quality}&otype=json&fourk=1&fnver=0&fnval=16";
- string url = $"{baseUrl}?cid={cid}&qn={quality}&otype=json&fourk=1&fnver=0&fnval=16";
- if (bvid != null)
- {
- url += $"&bvid={bvid}";
- }
- if (avid != 0)
- {
- url += $"&avid={avid}";
- }
- if (episodeId != 0)
- {
- url += $"&ep_id={episodeId}";
- }
-
- // 代理网址
- //https://www.biliplus.com/BPplayurl.php?cid=180873425&qn=116&type=&otype=json&fourk=1&bvid=BV1pV411o7yD&ep_id=317925&fnver=0&fnval=16&module=pgc
- if (isProxy && proxy == 1)
- {
- string proxyUrl1 = "https://www.biliplus.com/BPplayurl.php";
- url = $"{proxyUrl1}?cid={cid}&bvid={bvid}&qn={quality}&otype=json&fourk=1&fnver=0&fnval=16&module=pgc";
- }
- else if (isProxy && proxy == 2)
- {
- string proxyUrl2 = "https://biliplus.ipcjs.top/BPplayurl.php";
- url = $"{proxyUrl2}?cid={cid}&bvid={bvid}&qn={quality}&otype=json&fourk=1&fnver=0&fnval=16&module=pgc";
- }
-
- string response = Utils.RequestWeb(url, referer);
- //Console.WriteLine(response);
-
- try
- {
- PlayUrl playUrl;
- if (isProxy)
- {
- PlayUrlData playUrlData = JsonConvert.DeserializeObject(response);
-
- playUrl = new PlayUrl
- {
- result = playUrlData
- };
- }
- else
- {
- playUrl = JsonConvert.DeserializeObject(response);
- }
-
- if (playUrl != null)
- {
- if (playUrl.data != null) { return playUrl.data; }
- if (playUrl.result != null) { return playUrl.result; }
-
- // 无法从B站获取数据,进入代理网站
- if (Settings.GetInstance().IsLiftingOfRegion() == ALLOW_STATUS.YES)
- {
- switch (proxy)
- {
- case 0:
- return GetStreamInfo(bvid, avid, cid, episodeId, quality, referer, true, 1);
- case 1:
- return GetStreamInfo(bvid, avid, cid, episodeId, quality, referer, true, 2);
- case 2:
- return null;
- }
- }
-
- return null;
- }
- else { return null; }
- }
- catch (JsonReaderException e)
- {
- Console.WriteLine("GetStreamInfo()发生JsonReader异常: {0}", e);
- return null;
- }
- catch (Exception e)
- {
- Console.WriteLine("GetStreamInfo()发生异常: {0}", e);
- return null;
- }
- }
-
- //public static List GetAllDanmaku(long cid, long publishTime, string referer)
- //{
- // List danmakus = new List();
-
- // // 设置视频发布日期
- // DateTime publishDate = new DateTime(1970, 1, 1);
- // publishDate = publishDate.AddSeconds(publishTime);
-
- // // 获得有弹幕的日期date
- // List danmakuDateList = new List();
- // while (true)
- // {
- // string month = publishDate.ToString("yyyy-MM");
- // string url = $"https://api.bilibili.com/x/v2/dm/history/index?type=1&oid={cid}&month={month}";
- // string response = Utils.RequestWeb(url, referer);
-
- // DanmuDate danmakuDate;
- // try
- // {
- // danmakuDate = JsonConvert.DeserializeObject(response);
- // }
- // catch (Exception e)
- // {
- // Console.WriteLine("GetAllDanmaku()发生异常: {0}", e);
- // continue;
- // }
- // if (danmakuDate != null || danmakuDate.data != null) { danmakuDateList.AddRange(danmakuDate.data); }
-
- // if (publishDate.CompareTo(DateTime.Now) > 0) { break; }
- // publishDate = publishDate.AddMonths(1);
- // Thread.Sleep(100);
- // }
-
- // // 获取弹幕
- // foreach (var date in danmakuDateList)
- // {
- // Console.WriteLine(date);
-
- // List danmakusOfOneDay = GetDanmaku(cid, date);
-
- // foreach (Danmaku danmaku in danmakusOfOneDay)
- // {
- // if (danmakus.Find(it => it.DanmuId == danmaku.DanmuId) == null)
- // {
- // danmakus.Add(danmaku);
- // }
- // }
- // }
-
- // // 按弹幕发布时间排序
- // danmakus = danmakus.OrderBy(it => it.Timestamp).ToList();
-
- // return danmakus;
- //}
-
- //public static List GetDanmaku(long cid, string date, string referer)
- //{
- // string url = $"https://api.bilibili.com/x/v2/dm/history?type=1&oid={cid}&date={date}";
- // string response = Utils.RequestWeb(url, referer);
-
- // //
- // // {"code":-101,"message":"账号未登录","ttl":1}
- // if (response.Contains(""))
- // {
- // List danmakus = new List();
-
- // XmlDocument doc = new XmlDocument();
- // doc.LoadXml(response);
- // // 取得节点名为d的XmlNode集合
- // XmlNodeList danmuList = doc.GetElementsByTagName("d");
- // foreach (XmlNode node in danmuList)
- // {
- // // 返回的是文字内容
- // string nodeText = node.InnerText;
- // // 节点p属性值
- // string childValue = node.Attributes["p"].Value;
- // // 拆分属性
- // string[] attrs = childValue.Split(',');
-
- // Danmaku danmaku = new Danmaku
- // {
- // Text = nodeText,
- // Time = float.Parse(attrs[0]),
- // Type = int.Parse(attrs[1]),
- // Fontsize = int.Parse(attrs[2]),
- // Color = long.Parse(attrs[3]),
- // Timestamp = long.Parse(attrs[4]),
- // Pool = int.Parse(attrs[5]),
- // UserId = attrs[6],
- // DanmuId = attrs[7]
- // };
- // danmakus.Add(danmaku);
- // }
-
- // return danmakus;
- // }
- // else
- // {
- // DanmuFromWeb danmu = JsonConvert.DeserializeObject(response);
- // if (danmu != null) { Console.WriteLine(danmu.message); }
- // return null;
- // }
- //}
-
- /////
- ///// 获取弹幕,不需要登录信息,只能获取3000条弹幕
- /////
- /////
- /////
- //public static List GetDanmaku(long cid, string referer)
- //{
- // string url = $"https://api.bilibili.com/x/v1/dm/list.so?oid={cid}";
- // string response = Utils.RequestWeb(url, referer);
-
- // if (response.Contains(""))
- // {
- // List danmakus = new List();
-
- // XmlDocument doc = new XmlDocument();
- // doc.LoadXml(response);
- // // 取得节点名为d的XmlNode集合
- // XmlNodeList danmuList = doc.GetElementsByTagName("d");
- // foreach (XmlNode node in danmuList)
- // {
- // // 返回的是文字内容
- // string nodeText = node.InnerText;
- // // 节点p属性值
- // string childValue = node.Attributes["p"].Value;
- // // 拆分属性
- // string[] attrs = childValue.Split(',');
-
- // Danmaku danmaku = new Danmaku
- // {
- // Text = nodeText,
- // Time = float.Parse(attrs[0]),
- // Type = int.Parse(attrs[1]),
- // Fontsize = int.Parse(attrs[2]),
- // Color = long.Parse(attrs[3]),
- // Timestamp = long.Parse(attrs[4]),
- // Pool = int.Parse(attrs[5]),
- // UserId = attrs[6],
- // DanmuId = attrs[7]
- // };
- // danmakus.Add(danmaku);
- // }
-
- // return danmakus;
- // }
- // return null;
- //}
-
- }
-}
diff --git a/src/Core/FFmpegHelper.cs b/src/Core/FFmpegHelper.cs
deleted file mode 100644
index adfb4d7..0000000
--- a/src/Core/FFmpegHelper.cs
+++ /dev/null
@@ -1,254 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Diagnostics;
-using System.IO;
-using System.Windows;
-using System.Windows.Controls;
-
-namespace Core
-{
- public static class FFmpegHelper
- {
-
- ///
- /// 合并音频和视频
- ///
- ///
- ///
- ///
- public static bool MergeVideo(string video1, string video2, string destVideo)
- {
- string param = $"-i \"{video1}\" -i \"{video2}\" -acodec copy -vcodec copy -f mp4 \"{destVideo}\"";
- if (video1 == null || !File.Exists(video1))
- {
- param = $"-i \"{video2}\" -acodec copy -vcodec copy -f mp4 \"{destVideo}\"";
- }
- if (video2 == null || !File.Exists(video2))
- {
- param = $"-i \"{video1}\" -acodec copy -vcodec copy -f mp4 \"{destVideo}\"";
- }
- if (!File.Exists(video1) && !File.Exists(video2)) { return false; }
-
- // 如果存在
- try { File.Delete(destVideo); }
- catch (IOException e)
- {
- Console.WriteLine("MergeVideo()发生IO异常: {0}", e);
- return false;
- }
-
- ExcuteProcess("ffmpeg.exe", param, null, (s, e) => Console.WriteLine(e.Data));
-
- try
- {
- if (video1 != null) { File.Delete(video1); }
- if (video2 != null) { File.Delete(video2); }
- }
- catch (IOException e)
- {
- Console.WriteLine("MergeVideo()发生IO异常: {0}", e);
- }
-
- return true;
- }
-
- ///
- /// 拼接多个视频
- ///
- ///
- ///
- ///
- ///
- public static bool ConcatVideo(string workingDirectory, List flvFiles, string destVideo)
- {
- // contact的文件名,不包含路径
- string concatFileName = Guid.NewGuid().ToString("N") + "_concat.txt";
- try
- {
- string contact = "";
- foreach (string flv in flvFiles)
- {
- contact += $"file '{flv}'\n";
- }
-
- FileStream fileStream = new FileStream(workingDirectory + "/" + concatFileName, FileMode.Create);
- StreamWriter streamWriter = new StreamWriter(fileStream);
- //开始写入
- streamWriter.Write(contact);
- //清空缓冲区
- streamWriter.Flush();
- //关闭流
- streamWriter.Close();
- fileStream.Close();
- }
- catch (Exception e)
- {
- Console.WriteLine("ConcatVideo()发生异常: {0}", e);
- return false;
- }
-
- // ffmpeg -f concat -safe 0 -i filelist.txt -c copy output.mkv
- // 加上-y,表示如果有同名文件,则默认覆盖
- string param = $"-f concat -safe 0 -i {concatFileName} -c copy \"{destVideo}\" -y";
- ExcuteProcess("ffmpeg.exe", param, workingDirectory, (s, e) => Console.WriteLine(e.Data));
-
- // 删除临时文件
- try
- {
- // 删除concat文件
- File.Delete(workingDirectory + "/" + concatFileName);
-
- foreach (string flv in flvFiles)
- {
- File.Delete(flv);
- }
- }
- catch (Exception e)
- {
- Console.WriteLine("ConcatVideo()发生异常: {0}", e);
- }
-
- return true;
- }
-
- ///
- /// 去水印,非常消耗cpu资源
- ///
- ///
- ///
- ///
- ///
- ///
- ///
- ///
- ///
- public static void Delogo(string video, string destVideo, int x, int y, int width, int height, TextBox output = null, Window window = null)
- {
- // ffmpeg -i "video.mp4" -vf delogo=x=1670:y=50:w=180:h=70:show=1 "delogo.mp4"
- string param = $"-i \"{video}\" -vf delogo=x={x}:y={y}:w={width}:h={height} \"{destVideo}\" -hide_banner";
- ExcuteProcess("ffmpeg.exe", param,
- null, (s, e) =>
- {
- Console.WriteLine(e.Data);
- if (output != null && window != null)
- {
- window.Dispatcher.Invoke(new Action(() =>
- {
- output.Text += e.Data + "\n";
- output.ScrollToEnd();
- }));
- }
- });
- }
-
- ///
- /// 从一个视频中仅提取音频
- ///
- /// 源视频
- /// 目标音频
- /// 输出信息
- ///
- public static void ExtractAudio(string video, string audio, TextBox output = null, Window window = null)
- {
- // 抽取音频命令
- // ffmpeg -i 3.mp4 -vn -y -acodec copy 3.aac
- // ffmpeg -i 3.mp4 -vn -y -acodec copy 3.m4a
- string param = $"-i \"{video}\" -vn -y -acodec copy \"{audio}\" -hide_banner";
- ExcuteProcess("ffmpeg.exe", param,
- null, (s, e) =>
- {
- Console.WriteLine(e.Data);
- if (output != null && window != null)
- {
- window.Dispatcher.Invoke(new Action(() =>
- {
- output.Text += e.Data + "\n";
- output.ScrollToEnd();
- }));
- }
- });
- }
-
- ///
- /// 从一个视频中仅提取视频
- ///
- /// 源视频
- /// 目标视频
- /// 输出信息
- ///
- public static void ExtractVideo(string video, string destVideo, TextBox output = null, Window window = null)
- {
- // 提取视频 (Extract Video)
- // ffmpeg -i Life.of.Pi.has.subtitles.mkv -vcodec copy –an videoNoAudioSubtitle.mp4
- string param = $"-i \"{video}\" -y -vcodec copy -an \"{destVideo}\" -hide_banner";
- ExcuteProcess("ffmpeg.exe", param,
- null, (s, e) =>
- {
- Console.WriteLine(e.Data);
- if (output != null && window != null)
- {
- window.Dispatcher.Invoke(new Action(() =>
- {
- output.Text += e.Data + "\n";
- output.ScrollToEnd();
- }));
- }
- });
- }
-
- ///
- /// 提取视频的帧,输出为图片
- ///
- ///
- ///
- ///
- public static void ExtractFrame(string video, string image, uint number)
- {
- // 提取帧
- // ffmpeg -i caiyilin.wmv -vframes 1 wm.bmp
- string param = $"-i \"{video}\" -y -vframes {number} \"{image}\"";
- ExcuteProcess("ffmpeg.exe", param, null, (s, e) => Console.WriteLine(e.Data));
- }
-
-
- ///
- /// 执行一个控制台程序
- ///
- /// 程序名称
- /// 参数
- /// 工作路径
- /// 输出重定向
- private static void ExcuteProcess(string exe, string arg, string workingDirectory, DataReceivedEventHandler output)
- {
- using (var p = new Process())
- {
- p.StartInfo.FileName = exe;
- p.StartInfo.Arguments = arg;
-
- // 工作目录
- if (workingDirectory != null)
- {
- p.StartInfo.WorkingDirectory = workingDirectory;
- }
-
- p.StartInfo.UseShellExecute = false; //输出信息重定向
- p.StartInfo.CreateNoWindow = true;
- p.StartInfo.RedirectStandardError = true;
- p.StartInfo.RedirectStandardOutput = true;
-
- // 将 StandardErrorEncoding 改为 UTF-8 才不会出现中文乱码
- p.StartInfo.StandardOutputEncoding = System.Text.Encoding.UTF8;
- p.StartInfo.StandardErrorEncoding = System.Text.Encoding.UTF8;
-
- p.OutputDataReceived += output;
- p.ErrorDataReceived += output;
-
- p.Start(); //启动线程
- p.BeginOutputReadLine();
- p.BeginErrorReadLine();
- p.WaitForExit(); //等待进程结束
- }
- }
- }
-
-}
diff --git a/src/Core/FileDownloadUtil.cs b/src/Core/FileDownloadUtil.cs
deleted file mode 100644
index 5501720..0000000
--- a/src/Core/FileDownloadUtil.cs
+++ /dev/null
@@ -1,198 +0,0 @@
-using System;
-using System.IO;
-using System.Net;
-
-namespace Core
-{
- // from https://www.jianshu.com/p/f31910ed8435
- public class FileDownloadUtil
- {
- private string url; //文件下载网络地址
- private string referer; //访问url的referer
- private string path; //文件下载位置,如d:/download
- private string filename; //文件名,如test.jpg
- private string fileId; //文件ID,文件唯一标识,一般为UUID
-
- private System.Threading.Timer FileTimer; // 定时器
- private readonly int SPD_INTERVAL_SEC = 1; // 每隔多少秒计算一次速度
- private long FileTemp = 0; // 临时储存长度
- private float FileSpeed = 0; // //SPD_INTERVAL_SEC秒下载字节数
-
- // 下载进度回调
- public delegate void ProgressChangedHandler(int progress, string fileId);
- public event ProgressChangedHandler ProgressChanged;
- protected virtual void OnProgressChanged(int progress, string fileId)
- {
- ProgressChanged?.Invoke(progress, fileId);
- }
-
- public delegate void ProgressChanged2Handler(long totalBytes, long totalDownloadedByte, float speed, string fileId);
- public event ProgressChanged2Handler ProgressChanged2;
- protected virtual void OnProgressChanged2(long totalBytes, long totalDownloadedByte, float speed, string fileId)
- {
- ProgressChanged2?.Invoke(totalBytes, totalDownloadedByte, speed, fileId);
- }
-
- // 下载结果回调
- public delegate void DownloadFinishHandler(bool isSuccess, string downloadPath, string fileId, string msg = null);
- public event DownloadFinishHandler DownloadFinish;
- protected virtual void OnDownloadFinish(bool isSuccess, string downloadPath, string fileId, string msg = null)
- {
- DownloadFinish?.Invoke(isSuccess, downloadPath, fileId, msg);
- }
-
- //通过网络链接直接下载任意文件
- public FileDownloadUtil Init(string url, string referer, string path, string filename, string fileId)
- {
- this.url = url;
- this.referer = referer;
- this.path = path;
- this.filename = filename;
- this.fileId = fileId;
-
- return this;
- }
-
- public void Download()
- {
- Download(url, path, filename, fileId);
- }
-
- private void Download(string url, string path, string filename, string fileId)
- {
-
- if (!Directory.Exists(path)) //判断文件夹是否存在
- Directory.CreateDirectory(path);
- path = path + "\\" + filename;
-
- // 临时文件 "bilidownkyi\\"
- string tempFile = Path.GetTempPath() + "downkyi." + Guid.NewGuid().ToString("N");
- //string tempFile = path + ".temp";
-
- try
- {
- if (File.Exists(tempFile))
- {
- File.Delete(tempFile); //存在则删除
- }
- if (File.Exists(path))
- {
- File.Delete(path); //存在则删除
- }
- }
- catch (IOException e)
- {
- Console.WriteLine("Download()发生IO异常: {0}", e);
- }
-
- FileStream fs = null;
- HttpWebRequest request = null;
- HttpWebResponse response = null;
- Stream responseStream = null;
- try
- {
- //创建临时文件
- fs = new FileStream(tempFile, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
- request = WebRequest.Create(url) as HttpWebRequest;
- request.Method = "GET";
- request.Timeout = 60 * 1000;
- request.UserAgent = Utils.GetUserAgent();
- //request.ContentType = "text/html;charset=UTF-8";
- request.Headers["accept-language"] = "zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7";
- //request.Headers["accept-encoding"] = "gzip, deflate, br";
- request.Headers["origin"] = "https://www.bilibili.com";
- request.Referer = referer;
-
- // 构造cookie
- // web端请求视频链接时没有加入cookie
- //if (!url.Contains("getLogin"))
- //{
- // CookieContainer cookies = Login.GetLoginInfoCookies();
- // if (cookies != null)
- // {
- // request.CookieContainer = cookies;
- // }
- //}
-
- //发送请求并获取相应回应数据
- response = request.GetResponse() as HttpWebResponse;
- //直到request.GetResponse()程序才开始向目标网页发送Post请求
- responseStream = response.GetResponseStream();
- byte[] bArr = new byte[1024];
- long totalBytes = response.ContentLength; //通过响应头获取文件大小,前提是响应头有文件大小
- int size = responseStream.Read(bArr, 0, (int)bArr.Length); //读取响应流到bArr,读取大小
- float percent = 0; //用来保存计算好的百分比
- long totalDownloadedByte = 0; //总共下载字节数
-
- FileTimer = new System.Threading.Timer(SpeedTimer, null, 0, SPD_INTERVAL_SEC * 1000);
- while (size > 0) //while (totalBytes > totalDownloadedByte) //while循环读取响应流
- {
- fs.Write(bArr, 0, size); //写到临时文件
- // 定期刷新数据到磁盘,影响下载速度
- //fs.Flush(true);
-
- totalDownloadedByte += size;
- FileTemp += size;
- size = responseStream.Read(bArr, 0, (int)bArr.Length);
- percent = (float)totalDownloadedByte / (float)totalBytes * 100;
-
- // 下载进度回调
- OnProgressChanged((int)percent, fileId);
- OnProgressChanged2(totalBytes, totalDownloadedByte, FileSpeed, fileId);
- }
-
- try
- {
- if (File.Exists(path))
- {
- File.Delete(path); //存在则删除
- }
- }
- catch (IOException e)
- {
- Console.WriteLine("Download()发生IO异常: {0}", e);
- }
-
- if (fs != null)
- fs.Close();
- File.Move(tempFile, path); //重命名为正式文件
- OnDownloadFinish(true, path, fileId, null); //下载完成,成功回调
- }
- catch (Exception ex)
- {
- Console.WriteLine("Download()发生异常: {0}", ex);
- OnDownloadFinish(false, null, fileId, ex.Message); //下载完成,失败回调
- }
- finally
- {
- if (fs != null)
- fs.Close();
- if (request != null)
- request.Abort();
- if (response != null)
- response.Close();
- if (responseStream != null)
- responseStream.Close();
-
- try
- {
- if (File.Exists(tempFile))
- {
- File.Delete(tempFile); //存在则删除
- }
- }
- catch (IOException e)
- {
- Console.WriteLine("Download()发生IO异常: {0}", e);
- }
- }
- }
-
- private void SpeedTimer(object state)
- {
- FileSpeed = FileTemp / SPD_INTERVAL_SEC; //SPD_INTERVAL_SEC秒下载字节数,
- FileTemp = 0; //清空临时储存
- }
-
- }
-}
diff --git a/src/Core/UserSpaceOld.cs b/src/Core/UserSpaceOld.cs
deleted file mode 100644
index 88bd659..0000000
--- a/src/Core/UserSpaceOld.cs
+++ /dev/null
@@ -1,148 +0,0 @@
-using Core.entity;
-using Newtonsoft.Json;
-using System;
-using System.Collections.Generic;
-
-namespace Core
-{
- public static class UserSpaceOld
- {
-
- ///
- /// 获取我创建的收藏夹
- ///
- ///
- ///
- public static FavFolderData GetCreatedFavFolder(long mid)
- {
- string url = $"https://api.bilibili.com/x/v3/fav/folder/created/list?up_mid={mid}&ps=50";
- return GetAllFavFolder(url);
- }
-
- ///
- /// 获取我收藏的收藏夹
- ///
- ///
- ///
- public static FavFolderData GetCollectedFavFolder(long mid)
- {
- string url = $"https://api.bilibili.com/x/v3/fav/folder/collected/list?up_mid={mid}&ps=50";
- return GetAllFavFolder(url);
- }
-
- private static FavFolderData GetAllFavFolder(string baseUrl)
- {
- FavFolderData userFavoriteData = new FavFolderData
- {
- count = 0,
- list = new List()
- };
- int i = 0;
- while (true)
- {
- i++;
- string url = baseUrl + $"&pn={i}";
-
- var data = GetFavFolder(url);
- if (data == null)
- { break; }
- if (data.count == 0 || data.list == null)
- { break; }
-
- userFavoriteData.list.AddRange(data.list);
- }
- userFavoriteData.count = userFavoriteData.list.Count;
- return userFavoriteData;
- }
-
- private static FavFolderData GetFavFolder(string url)
- {
- string referer = "https://www.bilibili.com";
- string response = Utils.RequestWeb(url, referer);
-
- try
- {
- FavFolder favFolder = JsonConvert.DeserializeObject(response);
- if (favFolder == null || favFolder.data == null) { return null; }
-
- return favFolder.data;
- }
- catch (Exception e)
- {
- Console.WriteLine("GetFavFolder()发生异常: {0}", e);
- return null;
- }
- }
-
- ///
- /// 获得某个收藏夹的内容
- ///
- ///
- ///
- public static List GetAllFavResource(long mediaId)
- {
- string baseUrl = $"https://api.bilibili.com/x/v3/fav/resource/list?media_id={mediaId}&ps=20";
- List medias = new List();
-
- int i = 0;
- while (true)
- {
- i++;
- string url = baseUrl + $"&pn={i}";
-
- var data = GetFavResource(url);
- if (data == null || data.Count == 0)
- { break; }
-
- medias.AddRange(data);
- }
- return medias;
- }
-
- private static List GetFavResource(string url)
- {
- string referer = "https://www.bilibili.com";
- string response = Utils.RequestWeb(url, referer);
-
- try
- {
- FavResource favResource = JsonConvert.DeserializeObject(response);
- if (favResource == null || favResource.data == null) { return null; }
- return favResource.data.medias;
- }
- catch (Exception e)
- {
- Console.WriteLine("GetFavResource()发生异常: {0}", e);
- return null;
- }
- }
-
-
- ///
- /// 获取订阅番剧的数量
- /// 废弃
- ///
- ///
- ///
- //public static int GetBangumiFollowList(long mid)
- //{
- // string url = $"https://space.bilibili.com/ajax/Bangumi/getList?mid={mid}";
- // string referer = "https://www.bilibili.com";
- // string response = Utils.RequestWeb(url, referer);
-
- // try
- // {
- // BangumiList bangumiList = JsonConvert.DeserializeObject(response);
- // if (bangumiList == null || bangumiList.data == null) { return -1; }
-
- // return bangumiList.data.count;
- // }
- // catch (Exception e)
- // {
- // Console.WriteLine("发生异常: {0}", e);
- // return 0;
- // }
- //}
-
- }
-}
diff --git a/src/Core/Utils.cs b/src/Core/Utils.cs
deleted file mode 100644
index f27fc64..0000000
--- a/src/Core/Utils.cs
+++ /dev/null
@@ -1,430 +0,0 @@
-using Brotli;
-using Core.api.login;
-using Core.history;
-using System;
-using System.Collections;
-using System.Collections.Generic;
-using System.Drawing;
-using System.IO;
-using System.IO.Compression;
-using System.Linq;
-using System.Net;
-using System.Runtime.Serialization.Formatters.Binary;
-using System.Text;
-
-namespace Core
-{
- public static class Utils
- {
- ///
- /// 随机的UserAgent
- ///
- /// userAgent
- public static string GetUserAgent()
- {
- string[] userAgents = {
- // Chrome
- "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36",
- "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.125 Safari/537.36",
- "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36",
- "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36",
- "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.182 Safari/537.36",
- "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.36",
- "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.77 Safari/537.36",
-
- // 新版Edge
- "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36 Edg/83.0.478.58",
- "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.36 Edg/90.0.818.66",
-
- // IE 11
- "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 10.0; WOW64; Trident/7.0; .NET4.0C; .NET4.0E; .NET CLR 2.0.50727; .NET CLR 3.0.30729; .NET CLR 3.5.30729)",
-
- // 火狐
- "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:69.0) Gecko/20100101 Firefox/69.0",
-
- // Opera
- "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36 OPR/63.0.3368.43",
-
- // MacOS Chrome
- "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.106 Safari/537.36",
-
- // MacOS Safari
- "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_5) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.1.1 Safari/605.1.15"
- };
-
- var time = DateTime.Now;
-
- Random random = new Random(time.GetHashCode());
- int number = random.Next(0, userAgents.Length - 1);
-
- return userAgents[number];
- }
-
- ///
- /// 发送get或post请求
- ///
- ///
- ///
- ///
- ///
- ///
- public static string RequestWeb(string url, string referer = null, string method = "GET", Dictionary parameters = null, int retry = 3)
- {
- // 重试次数
- if (retry <= 0) { return ""; }
-
- // post请求,发送参数
- if (method == "POST" && parameters != null)
- {
- StringBuilder builder = new StringBuilder();
- int i = 0;
- foreach (var item in parameters)
- {
- if (i > 0) builder.Append("&");
- builder.AppendFormat("{0}={1}", item.Key, item.Value);
- i++;
- }
-
- url += "?" + builder.ToString();
- }
-
- try
- {
- HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
- request.Method = method;
- request.Timeout = 30 * 1000;
- request.UserAgent = GetUserAgent();
- //request.ContentType = "application/json,text/html,application/xhtml+xml,application/xml;charset=UTF-8";
- request.Headers["accept-language"] = "zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7";
- request.Headers["accept-encoding"] = "gzip, deflate, br";
-
- //request.Headers["sec-fetch-dest"] = "empty";
- //request.Headers["sec-fetch-mode"] = "cors";
- //request.Headers["sec-fetch-site"] = "same-site";
-
- // referer
- if (referer != null)
- {
- request.Referer = referer;
- }
-
- // 构造cookie
- if (!url.Contains("getLogin"))
- {
- request.Headers["origin"] = "https://www.bilibili.com";
-
- CookieContainer cookies = LoginHelper.GetInstance().GetLoginInfoCookies();
- if (cookies != null)
- {
- request.CookieContainer = cookies;
- }
- }
-
- //// post请求,发送参数
- //if (method == "POST" && parameters != null)
- //{
- // StringBuilder builder = new StringBuilder();
- // int i = 0;
- // foreach (var item in parameters)
- // {
- // if (i > 0) builder.Append("&");
- // builder.AppendFormat("{0}={1}", item.Key, item.Value);
- // i++;
- // }
- // byte[] data = Encoding.UTF8.GetBytes(builder.ToString());
- // request.ContentLength = data.Length;
-
- // Stream reqStream = request.GetRequestStream();
- // reqStream.Write(data, 0, data.Length);
- // reqStream.Close();
-
- // Console.WriteLine("\n" + builder.ToString() + "\t" + data.Length + "\n");
- //}
-
- //HttpWebResponse response = (HttpWebResponse)request.GetResponse();
- //Stream responseStream = response.GetResponseStream();
- //StreamReader streamReader = new StreamReader(responseStream, Encoding.UTF8);
- //string str = streamReader.ReadToEnd();
- //streamReader.Close();
- //responseStream.Close();
-
- string html = string.Empty;
- using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
- {
- if (response.ContentEncoding.ToLower().Contains("gzip"))
- {
- using (GZipStream stream = new GZipStream(response.GetResponseStream(), CompressionMode.Decompress))
- {
- using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
- {
- html = reader.ReadToEnd();
- }
- }
- }
- else if (response.ContentEncoding.ToLower().Contains("deflate"))
- {
- using (DeflateStream stream = new DeflateStream(response.GetResponseStream(), CompressionMode.Decompress))
- {
- using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
- {
- html = reader.ReadToEnd();
- }
- }
- }
- else if (response.ContentEncoding.ToLower().Contains("br"))
- {
- using (BrotliStream stream = new BrotliStream(response.GetResponseStream(), CompressionMode.Decompress))
- {
- using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
- {
- html = reader.ReadToEnd();
- }
- }
- }
- else
- {
- using (Stream stream = response.GetResponseStream())
- {
- using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
- {
- html = reader.ReadToEnd();
- }
- }
- }
- }
-
- return html;
- }
- catch (WebException e)
- {
- Console.WriteLine("RequestWeb()发生Web异常: {0}", e);
- return RequestWeb(url, referer, method, parameters, retry - 1);
- }
- catch (IOException e)
- {
- Console.WriteLine("RequestWeb()发生IO异常: {0}", e);
- return RequestWeb(url, referer, method, parameters, retry - 1);
- }
- catch (Exception e)
- {
- Console.WriteLine("RequestWeb()发生其他异常: {0}", e);
- return RequestWeb(url, referer, method, parameters, retry - 1);
- }
- }
-
- ///
- /// 解析二维码登录返回的url,用于设置cookie
- ///
- ///
- ///
- public static CookieContainer ParseCookie(string url)
- {
- CookieContainer cookieContainer = new CookieContainer();
-
- if (url == null || url == "") { return cookieContainer; }
-
- string[] strList = url.Split('?');
- if (strList.Count() < 2) { return cookieContainer; }
-
- string[] strList2 = strList[1].Split('&');
- if (strList2.Count() == 0) { return cookieContainer; }
-
- // 获取expires
- string expires = strList2.FirstOrDefault(it => it.Contains("Expires")).Split('=')[1];
- DateTime dateTime = DateTime.Now;
- dateTime = dateTime.AddSeconds(int.Parse(expires));
-
- foreach (var item in strList2)
- {
- string[] strList3 = item.Split('=');
- if (strList3.Count() < 2) { continue; }
-
- string name = strList3[0];
- string value = strList3[1];
-
- // 不需要
- if (name == "Expires" || name == "gourl") { continue; }
-
- // 添加cookie
- cookieContainer.Add(new Cookie(name, value, "/", ".bilibili.com") { Expires = dateTime });
-#if DEBUG
- Console.WriteLine(name + ": " + value + "\t" + cookieContainer.Count);
-#endif
- }
-
- return cookieContainer;
- }
-
- ///
- /// 将CookieContainer中的所有的Cookie读出来
- ///
- ///
- ///
- public static List GetAllCookies(CookieContainer cc)
- {
- List lstCookies = new List();
-
- Hashtable table = (Hashtable)cc.GetType().InvokeMember("m_domainTable",
- System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.GetField |
- System.Reflection.BindingFlags.Instance, null, cc, new object[] { });
-
- foreach (object pathList in table.Values)
- {
- SortedList lstCookieCol = (SortedList)pathList.GetType().InvokeMember("m_list",
- System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.GetField
- | System.Reflection.BindingFlags.Instance, null, pathList, new object[] { });
- foreach (CookieCollection colCookies in lstCookieCol.Values)
- foreach (Cookie c in colCookies) lstCookies.Add(c);
- }
-
- return lstCookies;
- }
-
- ///
- /// 写入cookies到磁盘
- ///
- ///
- ///
- ///
- public static bool WriteCookiesToDisk(string file, CookieContainer cookieJar)
- {
- return WriteObjectToDisk(file, cookieJar);
- }
-
- ///
- /// 从磁盘读取cookie
- ///
- ///
- ///
- public static CookieContainer ReadCookiesFromDisk(string file)
- {
- return (CookieContainer)ReadObjectFromDisk(file);
- }
-
- ///
- /// 写入历史数据到磁盘
- ///
- ///
- ///
- ///
- public static bool WriteHistoryToDisk(string file, HistoryEntity history)
- {
- return WriteObjectToDisk(file, history);
- }
-
- ///
- /// 从磁盘读取历史数据
- ///
- ///
- ///
- public static HistoryEntity ReadHistoryFromDisk(string file)
- {
- return (HistoryEntity)ReadObjectFromDisk(file);
- }
-
- ///
- /// 写入序列化对象到磁盘
- ///
- ///
- ///
- ///
- public static bool WriteObjectToDisk(string file, object obj)
- {
- try
- {
- using (Stream stream = File.Create(file))
- {
-#if DEBUG
- Console.Out.Write("Writing object to disk... ");
-#endif
- BinaryFormatter formatter = new BinaryFormatter();
- formatter.Serialize(stream, obj);
-#if DEBUG
- Console.Out.WriteLine("Done.");
-#endif
- return true;
- }
- }
- catch (IOException e)
- {
- Console.WriteLine("WriteObjectToDisk()发生IO异常: {0}", e);
- return false;
- }
- catch (Exception e)
- {
- //Console.Out.WriteLine("Problem writing object to disk: " + e.GetType());
- Console.WriteLine("WriteObjectToDisk()发生异常: {0}", e);
- return false;
- }
- }
-
- ///
- /// 从磁盘读取序列化对象
- ///
- ///
- ///
- public static object ReadObjectFromDisk(string file)
- {
- try
- {
- using (Stream stream = File.Open(file, FileMode.Open))
- {
-#if DEBUG
- Console.Out.Write("Reading object from disk... ");
-#endif
- BinaryFormatter formatter = new BinaryFormatter();
-#if DEBUG
- Console.Out.WriteLine("Done.");
-#endif
- return formatter.Deserialize(stream);
- }
- }
- catch (IOException e)
- {
- Console.WriteLine("ReadObjectFromDisk()发生IO异常: {0}", e);
- return null;
- }
- catch (Exception e)
- {
- //Console.Out.WriteLine("Problem reading object from disk: " + e.GetType());
- Console.WriteLine("ReadObjectFromDisk()发生异常: {0}", e);
- return null;
- }
- }
-
- ///
- /// 生成二维码
- ///
- /// 信息
- /// 版本 1 ~ 40
- /// 像素点大小
- /// 图标路径
- /// 图标尺寸
- /// 图标边框厚度
- /// 二维码白边
- /// 位图
- public static Bitmap EncodeQRCode(string msg, int version, int pixel, string icon_path, int icon_size, int icon_border, bool white_edge)
- {
- QRCoder.QRCodeGenerator code_generator = new QRCoder.QRCodeGenerator();
-
- QRCoder.QRCodeData code_data = code_generator.CreateQrCode(msg, QRCoder.QRCodeGenerator.ECCLevel.H/* 这里设置容错率的一个级别 */, true, false, QRCoder.QRCodeGenerator.EciMode.Utf8, version);
-
- QRCoder.QRCode code = new QRCoder.QRCode(code_data);
-
- Bitmap icon;
- if (icon_path == null || icon_path == "")
- {
- icon = null;
- }
- else
- {
- icon = new Bitmap(icon_path);
- }
-
- Bitmap bmp = code.GetGraphic(pixel, Color.Black, Color.White, icon, icon_size, icon_border, white_edge);
- return bmp;
- }
-
- }
-
-}
diff --git a/src/Core/api/danmaku/BiliDanmaku.cs b/src/Core/api/danmaku/BiliDanmaku.cs
deleted file mode 100644
index 6218273..0000000
--- a/src/Core/api/danmaku/BiliDanmaku.cs
+++ /dev/null
@@ -1,36 +0,0 @@
-namespace Core.api.danmaku.entity
-{
- public class BiliDanmaku
- {
- public long Id { get; set; } //弹幕dmID
- public int Progress { get; set; } //出现时间
- public int Mode { get; set; } //弹幕类型
- public int Fontsize { get; set; } //文字大小
- public uint Color { get; set; } //弹幕颜色
- public string MidHash { get; set; } //发送者UID的HASH
- public string Content { get; set; } //弹幕内容
- public long Ctime { get; set; } //发送时间
- public int Weight { get; set; } //权重
- //public string Action { get; set; } //动作?
- public int Pool { get; set; } //弹幕池
-
- public override string ToString()
- {
- //return base.ToString();
-
- string separator = "\n";
- return $"id: {Id}{separator}" +
- $"progress: {Progress}{separator}" +
- $"mode: {Mode}{separator}" +
- $"fontsize: {Fontsize}{separator}" +
- $"color: {Color}{separator}" +
- $"midHash: {MidHash}{separator}" +
- $"content: {Content}{separator}" +
- $"ctime: {Ctime}{separator}" +
- $"weight: {Weight}{separator}" +
- //$"action: {Action}{separator}" +
- $"pool: {Pool}";
- }
-
- }
-}
diff --git a/src/Core/api/danmaku/DanmakuProtobuf.cs b/src/Core/api/danmaku/DanmakuProtobuf.cs
deleted file mode 100644
index e2c8180..0000000
--- a/src/Core/api/danmaku/DanmakuProtobuf.cs
+++ /dev/null
@@ -1,115 +0,0 @@
-using Core.api.danmaku.entity;
-using System;
-using System.Collections.Generic;
-using System.IO;
-
-namespace Core.api.danmaku
-{
- ///
- /// protobuf弹幕
- ///
- public class DanmakuProtobuf
- {
- private static DanmakuProtobuf instance;
-
- ///
- /// 获取DanmakuProtobuf实例
- ///
- ///
- public static DanmakuProtobuf GetInstance()
- {
- if (instance == null)
- {
- instance = new DanmakuProtobuf();
- }
- return instance;
- }
-
- ///
- /// 隐藏DanmakuProtobuf()方法,必须使用单例模式
- ///
- private DanmakuProtobuf() { }
-
- ///
- /// 下载6分钟内的弹幕,返回弹幕列表
- ///
- /// 稿件avID
- /// 视频CID
- /// 分包,每6分钟一包
- ///
- public List GetDanmakuProto(long avid, long cid, int segmentIndex)
- {
- string url = $"https://api.bilibili.com/x/v2/dm/web/seg.so?type=1&oid={cid}&pid={avid}&segment_index={segmentIndex}";
- string referer = "https://www.bilibili.com";
-
- FileDownloadUtil fileDownload = new FileDownloadUtil();
- fileDownload.Init(url, referer, Path.GetTempPath() + "downkyi/danmaku", $"{cid}-{segmentIndex}.proto", "DanmakuProtobuf");
- fileDownload.Download();
-
- var danmakuList = new List();
-
- DmSegMobileReply danmakus;
- try
- {
- using (var input = File.OpenRead(Path.GetTempPath() + $"downkyi/danmaku/{cid}-{segmentIndex}.proto"))
- {
- danmakus = DmSegMobileReply.Parser.ParseFrom(input);
- if (danmakus == null || danmakus.Elems == null)
- {
- return danmakuList;
- }
-
- foreach (var dm in danmakus.Elems)
- {
- var danmaku = new BiliDanmaku
- {
- Id = dm.Id,
- Progress = dm.Progress,
- Mode = dm.Mode,
- Fontsize = dm.Fontsize,
- Color = dm.Color,
- MidHash = dm.MidHash,
- Content = dm.Content,
- Ctime = dm.Ctime,
- Weight = dm.Weight,
- //Action = dm.Action,
- Pool = dm.Pool
- };
- danmakuList.Add(danmaku);
- }
- }
- }
- catch (Exception e)
- {
-#if DEBUG
- Console.WriteLine("发生异常: {0}", e);
-#endif
- return null;
- }
-
- return danmakuList;
- }
-
- ///
- /// 下载所有弹幕,返回弹幕列表
- ///
- /// 稿件avID
- /// 视频CID
- ///
- public List GetAllDanmakuProto(long avid, long cid)
- {
- var danmakuList = new List();
-
- int segmentIndex = 0;
- while (true)
- {
- segmentIndex += 1;
- var danmakus = GetDanmakuProto(avid, cid, segmentIndex);
- if (danmakus == null) { break; }
- danmakuList.AddRange(danmakus);
- }
- return danmakuList;
- }
-
- }
-}
diff --git a/src/Core/api/danmaku/proto/Danmaku.cs b/src/Core/api/danmaku/proto/Danmaku.cs
deleted file mode 100644
index 75fb7b6..0000000
--- a/src/Core/api/danmaku/proto/Danmaku.cs
+++ /dev/null
@@ -1,814 +0,0 @@
-//
-// Generated by the protocol buffer compiler. DO NOT EDIT!
-// source: Danmaku.proto
-//
-#pragma warning disable 1591, 0612, 3021
-#region Designer generated code
-
-using pb = global::Google.Protobuf;
-using pbc = global::Google.Protobuf.Collections;
-using pbr = global::Google.Protobuf.Reflection;
-using scg = global::System.Collections.Generic;
-/// Holder for reflection information generated from Danmaku.proto
-public static partial class DanmakuReflection {
-
- #region Descriptor
- /// File descriptor for Danmaku.proto
- public static pbr::FileDescriptor Descriptor {
- get { return descriptor; }
- }
- private static pbr::FileDescriptor descriptor;
-
- static DanmakuReflection() {
- byte[] descriptorData = global::System.Convert.FromBase64String(
- string.Concat(
- "Cg1EYW5tYWt1LnByb3RvIsgBCgtEYW5tYWt1RWxlbRIKCgJpZBgBIAEoAxIQ",
- "Cghwcm9ncmVzcxgCIAEoBRIMCgRtb2RlGAMgASgFEhAKCGZvbnRzaXplGAQg",
- "ASgFEg0KBWNvbG9yGAUgASgNEg8KB21pZEhhc2gYBiABKAkSDwoHY29udGVu",
- "dBgHIAEoCRINCgVjdGltZRgIIAEoAxIOCgZ3ZWlnaHQYCSABKAUSDgoGYWN0",
- "aW9uGAogASgJEgwKBHBvb2wYCyABKAUSDQoFaWRTdHIYDCABKAkiLwoQRG1T",
- "ZWdNb2JpbGVSZXBseRIbCgVlbGVtcxgBIAMoCzIMLkRhbm1ha3VFbGVtYgZw",
- "cm90bzM="));
- descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
- new pbr::FileDescriptor[] { },
- new pbr::GeneratedClrTypeInfo(null, null, new pbr::GeneratedClrTypeInfo[] {
- new pbr::GeneratedClrTypeInfo(typeof(global::DanmakuElem), global::DanmakuElem.Parser, new[]{ "Id", "Progress", "Mode", "Fontsize", "Color", "MidHash", "Content", "Ctime", "Weight", "Action", "Pool", "IdStr" }, null, null, null, null),
- new pbr::GeneratedClrTypeInfo(typeof(global::DmSegMobileReply), global::DmSegMobileReply.Parser, new[]{ "Elems" }, null, null, null, null)
- }));
- }
- #endregion
-
-}
-#region Messages
-public sealed partial class DanmakuElem : pb::IMessage
-#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
- , pb::IBufferMessage
-#endif
-{
- private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new DanmakuElem());
- private pb::UnknownFieldSet _unknownFields;
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public static pb::MessageParser Parser { get { return _parser; } }
-
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public static pbr::MessageDescriptor Descriptor {
- get { return global::DanmakuReflection.Descriptor.MessageTypes[0]; }
- }
-
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- pbr::MessageDescriptor pb::IMessage.Descriptor {
- get { return Descriptor; }
- }
-
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public DanmakuElem() {
- OnConstruction();
- }
-
- partial void OnConstruction();
-
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public DanmakuElem(DanmakuElem other) : this() {
- id_ = other.id_;
- progress_ = other.progress_;
- mode_ = other.mode_;
- fontsize_ = other.fontsize_;
- color_ = other.color_;
- midHash_ = other.midHash_;
- content_ = other.content_;
- ctime_ = other.ctime_;
- weight_ = other.weight_;
- action_ = other.action_;
- pool_ = other.pool_;
- idStr_ = other.idStr_;
- _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
- }
-
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public DanmakuElem Clone() {
- return new DanmakuElem(this);
- }
-
- /// Field number for the "id" field.
- public const int IdFieldNumber = 1;
- private long id_;
- ///
- ///弹幕dmID
- ///
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public long Id {
- get { return id_; }
- set {
- id_ = value;
- }
- }
-
- /// Field number for the "progress" field.
- public const int ProgressFieldNumber = 2;
- private int progress_;
- ///
- ///出现时间
- ///
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public int Progress {
- get { return progress_; }
- set {
- progress_ = value;
- }
- }
-
- /// Field number for the "mode" field.
- public const int ModeFieldNumber = 3;
- private int mode_;
- ///
- ///弹幕类型
- ///
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public int Mode {
- get { return mode_; }
- set {
- mode_ = value;
- }
- }
-
- /// Field number for the "fontsize" field.
- public const int FontsizeFieldNumber = 4;
- private int fontsize_;
- ///
- ///文字大小
- ///
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public int Fontsize {
- get { return fontsize_; }
- set {
- fontsize_ = value;
- }
- }
-
- /// Field number for the "color" field.
- public const int ColorFieldNumber = 5;
- private uint color_;
- ///
- ///弹幕颜色
- ///
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public uint Color {
- get { return color_; }
- set {
- color_ = value;
- }
- }
-
- /// Field number for the "midHash" field.
- public const int MidHashFieldNumber = 6;
- private string midHash_ = "";
- ///
- ///发送者UID的HASH
- ///
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public string MidHash {
- get { return midHash_; }
- set {
- midHash_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
- }
- }
-
- /// Field number for the "content" field.
- public const int ContentFieldNumber = 7;
- private string content_ = "";
- ///
- ///弹幕内容
- ///
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public string Content {
- get { return content_; }
- set {
- content_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
- }
- }
-
- /// Field number for the "ctime" field.
- public const int CtimeFieldNumber = 8;
- private long ctime_;
- ///
- ///发送时间
- ///
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public long Ctime {
- get { return ctime_; }
- set {
- ctime_ = value;
- }
- }
-
- /// Field number for the "weight" field.
- public const int WeightFieldNumber = 9;
- private int weight_;
- ///
- ///权重
- ///
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public int Weight {
- get { return weight_; }
- set {
- weight_ = value;
- }
- }
-
- /// Field number for the "action" field.
- public const int ActionFieldNumber = 10;
- private string action_ = "";
- ///
- ///动作?
- ///
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public string Action {
- get { return action_; }
- set {
- action_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
- }
- }
-
- /// Field number for the "pool" field.
- public const int PoolFieldNumber = 11;
- private int pool_;
- ///
- ///弹幕池
- ///
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public int Pool {
- get { return pool_; }
- set {
- pool_ = value;
- }
- }
-
- /// Field number for the "idStr" field.
- public const int IdStrFieldNumber = 12;
- private string idStr_ = "";
- ///
- ///弹幕dmID(字串形式)
- ///
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public string IdStr {
- get { return idStr_; }
- set {
- idStr_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
- }
- }
-
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public override bool Equals(object other) {
- return Equals(other as DanmakuElem);
- }
-
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public bool Equals(DanmakuElem other) {
- if (ReferenceEquals(other, null)) {
- return false;
- }
- if (ReferenceEquals(other, this)) {
- return true;
- }
- if (Id != other.Id) return false;
- if (Progress != other.Progress) return false;
- if (Mode != other.Mode) return false;
- if (Fontsize != other.Fontsize) return false;
- if (Color != other.Color) return false;
- if (MidHash != other.MidHash) return false;
- if (Content != other.Content) return false;
- if (Ctime != other.Ctime) return false;
- if (Weight != other.Weight) return false;
- if (Action != other.Action) return false;
- if (Pool != other.Pool) return false;
- if (IdStr != other.IdStr) return false;
- return Equals(_unknownFields, other._unknownFields);
- }
-
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public override int GetHashCode() {
- int hash = 1;
- if (Id != 0L) hash ^= Id.GetHashCode();
- if (Progress != 0) hash ^= Progress.GetHashCode();
- if (Mode != 0) hash ^= Mode.GetHashCode();
- if (Fontsize != 0) hash ^= Fontsize.GetHashCode();
- if (Color != 0) hash ^= Color.GetHashCode();
- if (MidHash.Length != 0) hash ^= MidHash.GetHashCode();
- if (Content.Length != 0) hash ^= Content.GetHashCode();
- if (Ctime != 0L) hash ^= Ctime.GetHashCode();
- if (Weight != 0) hash ^= Weight.GetHashCode();
- if (Action.Length != 0) hash ^= Action.GetHashCode();
- if (Pool != 0) hash ^= Pool.GetHashCode();
- if (IdStr.Length != 0) hash ^= IdStr.GetHashCode();
- if (_unknownFields != null) {
- hash ^= _unknownFields.GetHashCode();
- }
- return hash;
- }
-
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public override string ToString() {
- return pb::JsonFormatter.ToDiagnosticString(this);
- }
-
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public void WriteTo(pb::CodedOutputStream output) {
- #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
- output.WriteRawMessage(this);
- #else
- if (Id != 0L) {
- output.WriteRawTag(8);
- output.WriteInt64(Id);
- }
- if (Progress != 0) {
- output.WriteRawTag(16);
- output.WriteInt32(Progress);
- }
- if (Mode != 0) {
- output.WriteRawTag(24);
- output.WriteInt32(Mode);
- }
- if (Fontsize != 0) {
- output.WriteRawTag(32);
- output.WriteInt32(Fontsize);
- }
- if (Color != 0) {
- output.WriteRawTag(40);
- output.WriteUInt32(Color);
- }
- if (MidHash.Length != 0) {
- output.WriteRawTag(50);
- output.WriteString(MidHash);
- }
- if (Content.Length != 0) {
- output.WriteRawTag(58);
- output.WriteString(Content);
- }
- if (Ctime != 0L) {
- output.WriteRawTag(64);
- output.WriteInt64(Ctime);
- }
- if (Weight != 0) {
- output.WriteRawTag(72);
- output.WriteInt32(Weight);
- }
- if (Action.Length != 0) {
- output.WriteRawTag(82);
- output.WriteString(Action);
- }
- if (Pool != 0) {
- output.WriteRawTag(88);
- output.WriteInt32(Pool);
- }
- if (IdStr.Length != 0) {
- output.WriteRawTag(98);
- output.WriteString(IdStr);
- }
- if (_unknownFields != null) {
- _unknownFields.WriteTo(output);
- }
- #endif
- }
-
- #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) {
- if (Id != 0L) {
- output.WriteRawTag(8);
- output.WriteInt64(Id);
- }
- if (Progress != 0) {
- output.WriteRawTag(16);
- output.WriteInt32(Progress);
- }
- if (Mode != 0) {
- output.WriteRawTag(24);
- output.WriteInt32(Mode);
- }
- if (Fontsize != 0) {
- output.WriteRawTag(32);
- output.WriteInt32(Fontsize);
- }
- if (Color != 0) {
- output.WriteRawTag(40);
- output.WriteUInt32(Color);
- }
- if (MidHash.Length != 0) {
- output.WriteRawTag(50);
- output.WriteString(MidHash);
- }
- if (Content.Length != 0) {
- output.WriteRawTag(58);
- output.WriteString(Content);
- }
- if (Ctime != 0L) {
- output.WriteRawTag(64);
- output.WriteInt64(Ctime);
- }
- if (Weight != 0) {
- output.WriteRawTag(72);
- output.WriteInt32(Weight);
- }
- if (Action.Length != 0) {
- output.WriteRawTag(82);
- output.WriteString(Action);
- }
- if (Pool != 0) {
- output.WriteRawTag(88);
- output.WriteInt32(Pool);
- }
- if (IdStr.Length != 0) {
- output.WriteRawTag(98);
- output.WriteString(IdStr);
- }
- if (_unknownFields != null) {
- _unknownFields.WriteTo(ref output);
- }
- }
- #endif
-
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public int CalculateSize() {
- int size = 0;
- if (Id != 0L) {
- size += 1 + pb::CodedOutputStream.ComputeInt64Size(Id);
- }
- if (Progress != 0) {
- size += 1 + pb::CodedOutputStream.ComputeInt32Size(Progress);
- }
- if (Mode != 0) {
- size += 1 + pb::CodedOutputStream.ComputeInt32Size(Mode);
- }
- if (Fontsize != 0) {
- size += 1 + pb::CodedOutputStream.ComputeInt32Size(Fontsize);
- }
- if (Color != 0) {
- size += 1 + pb::CodedOutputStream.ComputeUInt32Size(Color);
- }
- if (MidHash.Length != 0) {
- size += 1 + pb::CodedOutputStream.ComputeStringSize(MidHash);
- }
- if (Content.Length != 0) {
- size += 1 + pb::CodedOutputStream.ComputeStringSize(Content);
- }
- if (Ctime != 0L) {
- size += 1 + pb::CodedOutputStream.ComputeInt64Size(Ctime);
- }
- if (Weight != 0) {
- size += 1 + pb::CodedOutputStream.ComputeInt32Size(Weight);
- }
- if (Action.Length != 0) {
- size += 1 + pb::CodedOutputStream.ComputeStringSize(Action);
- }
- if (Pool != 0) {
- size += 1 + pb::CodedOutputStream.ComputeInt32Size(Pool);
- }
- if (IdStr.Length != 0) {
- size += 1 + pb::CodedOutputStream.ComputeStringSize(IdStr);
- }
- if (_unknownFields != null) {
- size += _unknownFields.CalculateSize();
- }
- return size;
- }
-
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public void MergeFrom(DanmakuElem other) {
- if (other == null) {
- return;
- }
- if (other.Id != 0L) {
- Id = other.Id;
- }
- if (other.Progress != 0) {
- Progress = other.Progress;
- }
- if (other.Mode != 0) {
- Mode = other.Mode;
- }
- if (other.Fontsize != 0) {
- Fontsize = other.Fontsize;
- }
- if (other.Color != 0) {
- Color = other.Color;
- }
- if (other.MidHash.Length != 0) {
- MidHash = other.MidHash;
- }
- if (other.Content.Length != 0) {
- Content = other.Content;
- }
- if (other.Ctime != 0L) {
- Ctime = other.Ctime;
- }
- if (other.Weight != 0) {
- Weight = other.Weight;
- }
- if (other.Action.Length != 0) {
- Action = other.Action;
- }
- if (other.Pool != 0) {
- Pool = other.Pool;
- }
- if (other.IdStr.Length != 0) {
- IdStr = other.IdStr;
- }
- _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
- }
-
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public void MergeFrom(pb::CodedInputStream input) {
- #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
- input.ReadRawMessage(this);
- #else
- uint tag;
- while ((tag = input.ReadTag()) != 0) {
- switch(tag) {
- default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
- break;
- case 8: {
- Id = input.ReadInt64();
- break;
- }
- case 16: {
- Progress = input.ReadInt32();
- break;
- }
- case 24: {
- Mode = input.ReadInt32();
- break;
- }
- case 32: {
- Fontsize = input.ReadInt32();
- break;
- }
- case 40: {
- Color = input.ReadUInt32();
- break;
- }
- case 50: {
- MidHash = input.ReadString();
- break;
- }
- case 58: {
- Content = input.ReadString();
- break;
- }
- case 64: {
- Ctime = input.ReadInt64();
- break;
- }
- case 72: {
- Weight = input.ReadInt32();
- break;
- }
- case 82: {
- Action = input.ReadString();
- break;
- }
- case 88: {
- Pool = input.ReadInt32();
- break;
- }
- case 98: {
- IdStr = input.ReadString();
- break;
- }
- }
- }
- #endif
- }
-
- #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
- uint tag;
- while ((tag = input.ReadTag()) != 0) {
- switch(tag) {
- default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
- break;
- case 8: {
- Id = input.ReadInt64();
- break;
- }
- case 16: {
- Progress = input.ReadInt32();
- break;
- }
- case 24: {
- Mode = input.ReadInt32();
- break;
- }
- case 32: {
- Fontsize = input.ReadInt32();
- break;
- }
- case 40: {
- Color = input.ReadUInt32();
- break;
- }
- case 50: {
- MidHash = input.ReadString();
- break;
- }
- case 58: {
- Content = input.ReadString();
- break;
- }
- case 64: {
- Ctime = input.ReadInt64();
- break;
- }
- case 72: {
- Weight = input.ReadInt32();
- break;
- }
- case 82: {
- Action = input.ReadString();
- break;
- }
- case 88: {
- Pool = input.ReadInt32();
- break;
- }
- case 98: {
- IdStr = input.ReadString();
- break;
- }
- }
- }
- }
- #endif
-
-}
-
-public sealed partial class DmSegMobileReply : pb::IMessage
-#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
- , pb::IBufferMessage
-#endif
-{
- private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new DmSegMobileReply());
- private pb::UnknownFieldSet _unknownFields;
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public static pb::MessageParser Parser { get { return _parser; } }
-
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public static pbr::MessageDescriptor Descriptor {
- get { return global::DanmakuReflection.Descriptor.MessageTypes[1]; }
- }
-
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- pbr::MessageDescriptor pb::IMessage.Descriptor {
- get { return Descriptor; }
- }
-
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public DmSegMobileReply() {
- OnConstruction();
- }
-
- partial void OnConstruction();
-
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public DmSegMobileReply(DmSegMobileReply other) : this() {
- elems_ = other.elems_.Clone();
- _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
- }
-
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public DmSegMobileReply Clone() {
- return new DmSegMobileReply(this);
- }
-
- /// Field number for the "elems" field.
- public const int ElemsFieldNumber = 1;
- private static readonly pb::FieldCodec _repeated_elems_codec
- = pb::FieldCodec.ForMessage(10, global::DanmakuElem.Parser);
- private readonly pbc::RepeatedField elems_ = new pbc::RepeatedField();
- ///
- ///弹幕条目
- ///
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public pbc::RepeatedField Elems {
- get { return elems_; }
- }
-
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public override bool Equals(object other) {
- return Equals(other as DmSegMobileReply);
- }
-
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public bool Equals(DmSegMobileReply other) {
- if (ReferenceEquals(other, null)) {
- return false;
- }
- if (ReferenceEquals(other, this)) {
- return true;
- }
- if(!elems_.Equals(other.elems_)) return false;
- return Equals(_unknownFields, other._unknownFields);
- }
-
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public override int GetHashCode() {
- int hash = 1;
- hash ^= elems_.GetHashCode();
- if (_unknownFields != null) {
- hash ^= _unknownFields.GetHashCode();
- }
- return hash;
- }
-
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public override string ToString() {
- return pb::JsonFormatter.ToDiagnosticString(this);
- }
-
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public void WriteTo(pb::CodedOutputStream output) {
- #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
- output.WriteRawMessage(this);
- #else
- elems_.WriteTo(output, _repeated_elems_codec);
- if (_unknownFields != null) {
- _unknownFields.WriteTo(output);
- }
- #endif
- }
-
- #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) {
- elems_.WriteTo(ref output, _repeated_elems_codec);
- if (_unknownFields != null) {
- _unknownFields.WriteTo(ref output);
- }
- }
- #endif
-
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public int CalculateSize() {
- int size = 0;
- size += elems_.CalculateSize(_repeated_elems_codec);
- if (_unknownFields != null) {
- size += _unknownFields.CalculateSize();
- }
- return size;
- }
-
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public void MergeFrom(DmSegMobileReply other) {
- if (other == null) {
- return;
- }
- elems_.Add(other.elems_);
- _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
- }
-
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public void MergeFrom(pb::CodedInputStream input) {
- #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
- input.ReadRawMessage(this);
- #else
- uint tag;
- while ((tag = input.ReadTag()) != 0) {
- switch(tag) {
- default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
- break;
- case 10: {
- elems_.AddEntriesFrom(input, _repeated_elems_codec);
- break;
- }
- }
- }
- #endif
- }
-
- #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
- uint tag;
- while ((tag = input.ReadTag()) != 0) {
- switch(tag) {
- default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
- break;
- case 10: {
- elems_.AddEntriesFrom(ref input, _repeated_elems_codec);
- break;
- }
- }
- }
- }
- #endif
-
-}
-
-#endregion
-
-
-#endregion Designer generated code
diff --git a/src/Core/api/danmaku/proto/Danmaku.proto b/src/Core/api/danmaku/proto/Danmaku.proto
deleted file mode 100644
index 71f4f54..0000000
--- a/src/Core/api/danmaku/proto/Danmaku.proto
+++ /dev/null
@@ -1,20 +0,0 @@
-syntax = "proto3";
-
-message DanmakuElem {
- int64 id = 1; //弹幕dmID
- int32 progress = 2; //出现时间
- int32 mode = 3; //弹幕类型
- int32 fontsize = 4; //文字大小
- uint32 color = 5; //弹幕颜色
- string midHash = 6; //发送者UID的HASH
- string content = 7; //弹幕内容
- int64 ctime = 8; //发送时间
- int32 weight = 9; //权重
- string action = 10; //动作?
- int32 pool = 11; //弹幕池
- string idStr = 12; //弹幕dmID(字串形式)
-}
-
-message DmSegMobileReply {
- repeated DanmakuElem elems = 1; //弹幕条目
-}
diff --git a/src/Core/api/fileDownload/FileDownloadConfig.cs b/src/Core/api/fileDownload/FileDownloadConfig.cs
deleted file mode 100644
index 7bea76d..0000000
--- a/src/Core/api/fileDownload/FileDownloadConfig.cs
+++ /dev/null
@@ -1,42 +0,0 @@
-using System;
-using System.Collections.Generic;
-
-namespace Core.api.fileDownload
-{
- [Serializable]
- internal class FileDownloadConfig
- {
- public long DownloadSize { get; set; }
- public long TotalSize { get; set; }
- public Queue DownloadQueue { get; set; }
-
- ///
- /// 保存文件下载的配置信息,包括总字节数、已下载字节数、下载队列信息
- ///
- ///
- ///
- ///
- ///
- public static void SaveConfig(string configFile, long downloadSize, long totalSize, Queue downloadQueue)
- {
- var config = new FileDownloadConfig()
- {
- DownloadSize = downloadSize,
- TotalSize = totalSize,
- DownloadQueue = downloadQueue
- };
- Utils.WriteObjectToDisk(configFile, config);
- }
-
- ///
- /// 读取文件下载的配置信息,包括总字节数、已下载字节数、下载队列信息
- ///
- ///
- ///
- public static FileDownloadConfig ReadConfig(string configFile)
- {
- return (FileDownloadConfig)Utils.ReadObjectFromDisk(configFile);
- }
-
- }
-}
diff --git a/src/Core/api/fileDownload/FileDownloadEvent.cs b/src/Core/api/fileDownload/FileDownloadEvent.cs
deleted file mode 100644
index d641257..0000000
--- a/src/Core/api/fileDownload/FileDownloadEvent.cs
+++ /dev/null
@@ -1,24 +0,0 @@
-namespace Core.api.fileDownload
-{
- public class FileDownloadEvent
- {
-
- //private long _downloadSize;
- //private long _totalSize;
- public FileDownloadEvent() { }
-
- // 每秒下载的速度 B/s
- public float Speed { get; set; }
-
- public float Percent
- {
- get { return DownloadSize * 100.0f / TotalSize; }
- }
-
- public long DownloadSize { get; set; }
-
- public long TotalSize { get; set; }
-
-
- }
-}
diff --git a/src/Core/api/fileDownload/FileDownloadHelper.cs b/src/Core/api/fileDownload/FileDownloadHelper.cs
deleted file mode 100644
index de0ad49..0000000
--- a/src/Core/api/fileDownload/FileDownloadHelper.cs
+++ /dev/null
@@ -1,317 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.IO;
-using System.Net;
-using System.Threading;
-using System.Threading.Tasks;
-
-namespace Core.api.fileDownload
-{
- public class FileDownloadHelper
- {
- private const int DOWNLOAD_BUFFER_SIZE = 102400; //每次下载量 100KB
- private const int THREAD_BUFFER_SIZE = 10485760; //每个线程每次最大下载大小 设为10MB 不能太小 否则会创建太多的request对象
- public delegate void ErrorMakedEventHandler(string errorstring);
- public event ErrorMakedEventHandler ErrorMakedEvent;
- public delegate void DownloadEventHandler(FileDownloadEvent e);
- public event DownloadEventHandler DownloadEvent;
- public delegate void StopEventHandler();
- public event StopEventHandler StopEvent;
- private object locker = new object();
- private long downloadSize = 0; //已经下载的字节
- private CancellationTokenSource cancelTokenSource = new CancellationTokenSource();
- private ManualResetEvent mre = new ManualResetEvent(true); //初始化不等待
- private AutoResetEvent eventFinished = new AutoResetEvent(false);
-
- private void ThreadWork(string url, FileStream fs, Queue downQueue)
- {
- mre.WaitOne();
- if (cancelTokenSource.IsCancellationRequested)
- {
- return;
- }
-
- Monitor.Enter(downQueue);
- if (downQueue.Count == 0)
- {
- return;
- }
- ThreadDownloadInfo downInfo = downQueue.Dequeue();
- Monitor.Exit(downQueue);
-
- HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
- request.AddRange(downInfo.StartLength); //设置Range值
- HttpWebResponse response = (HttpWebResponse)request.GetResponse();
- Stream ns = response.GetResponseStream();
- byte[] nbytes = new byte[DOWNLOAD_BUFFER_SIZE];
- int temp = 0;
- int nReadSize = 0;
- byte[] buffer = new byte[downInfo.Length]; //文件写入缓冲
- nReadSize = ns.Read(nbytes, 0, Math.Min(DOWNLOAD_BUFFER_SIZE, downInfo.Length));
- while (temp < downInfo.Length)
- {
- mre.WaitOne();
- Buffer.BlockCopy(nbytes, 0, buffer, temp, nReadSize);
- lock (locker)
- {
- downloadSize += nReadSize;
- }
- temp += nReadSize;
- nReadSize = ns.Read(nbytes, 0, Math.Min(DOWNLOAD_BUFFER_SIZE, downInfo.Length - temp));
- }
-
- lock (locker)
- {
- fs.Seek(downInfo.StartLength, SeekOrigin.Begin);
- fs.Write(buffer, 0, buffer.Length);
- }
-
- ns.Close();
- ThreadWork(url, fs, downQueue);
- }
-
- public async void StartDownload(FileDownloadInfo info)
- {
- if (string.IsNullOrEmpty(info.DownLoadUrl))
- { throw new Exception("下载地址不能为空!"); }
- if (!info.DownLoadUrl.ToLower().StartsWith("http://") || !info.DownLoadUrl.ToLower().StartsWith("https://"))
- { throw new Exception("非法的下载地址!"); }
-
- downloadSize = 0;
- await Task.Run(() =>
- {
- try
- {
- long totalSize = 0;
- long threadInitedLength = 0; //分配线程任务的下载量
-
- #region 获取文件信息
- //打开网络连接
- HttpWebRequest initRequest = (HttpWebRequest)WebRequest.Create(info.DownLoadUrl);
- WebResponse initResponse = initRequest.GetResponse();
- FileInfo fileMsg = FileInfo.GetFileMessage(initResponse);
- totalSize = fileMsg.Length;
- if ((!string.IsNullOrEmpty(fileMsg.FileName)) && info.LocalSaveFolder != null)
- {
- info.SavePath = Path.Combine(info.LocalSaveFolder, fileMsg.FileName);
- }
- //ReaderWriterLock readWriteLock = new ReaderWriterLock();
- #endregion
-
- #region 读取配置文件
- string configPath = info.SavePath.Substring(0, info.SavePath.LastIndexOf(".")) + ".cfg";
- FileDownloadConfig initInfo = null;
- if (File.Exists(configPath) && (info.IsNew == false))
- {
- initInfo = FileDownloadConfig.ReadConfig(configPath);
- downloadSize = (long)initInfo.DownloadSize;
- totalSize = (long)initInfo.TotalSize;
- }
- #endregion
-
- #region 计算速度
- //Stopwatch MyStopWatch = new Stopwatch();
- long lastDownloadSize = 0; //上次下载量
- bool isSendCompleteEvent = false; //是否完成
- Timer timer = new Timer(new TimerCallback((o) =>
- {
- if (!isSendCompleteEvent)
- {
- FileDownloadEvent e = new FileDownloadEvent();
- e.DownloadSize = downloadSize;
- e.TotalSize = totalSize;
- if (totalSize > 0 && downloadSize == totalSize)
- {
- e.Speed = 0;
- isSendCompleteEvent = true;
- eventFinished.Set();
- }
- else
- {
- e.Speed = downloadSize - lastDownloadSize;
- lastDownloadSize = downloadSize; //更新上次下载量
- }
-
- DownloadEvent(e);
- }
-
- }), null, 0, 1000);
- #endregion
-
- string tempPath = info.SavePath.Substring(0, info.SavePath.LastIndexOf(".")) + ".dat";
-
- #region 多线程下载
- //分配下载队列
- Queue downQueue = null;
- if (initInfo == null || info.IsNew)
- {
- downQueue = new Queue(); //下载信息队列
- while (threadInitedLength < totalSize)
- {
- ThreadDownloadInfo downInfo = new ThreadDownloadInfo();
- downInfo.StartLength = threadInitedLength;
- downInfo.Length = (int)Math.Min(Math.Min(THREAD_BUFFER_SIZE, totalSize - threadInitedLength), totalSize / info.ThreadCount); //下载量
- downQueue.Enqueue(downInfo);
- threadInitedLength += downInfo.Length;
- }
- }
- else
- {
- downQueue = initInfo.DownloadQueue;
- }
-
- FileStream fs = new FileStream(tempPath, FileMode.OpenOrCreate);
- fs.SetLength(totalSize);
- int threads = info.ThreadCount;
-
- for (int i = 0; i < info.ThreadCount; i++)
- {
- ThreadPool.QueueUserWorkItem((state) =>
- {
- ThreadWork(info.DownLoadUrl, fs, downQueue);
- if (Interlocked.Decrement(ref threads) == 0)
- {
- (state as AutoResetEvent).Set();
- }
- }, eventFinished);
- }
-
- //等待所有线程完成
- eventFinished.WaitOne();
- if (fs != null)
- {
- fs.Close();
- }
- fs = null;
- if (File.Exists(info.SavePath))
- {
- File.Delete(info.SavePath);
- }
-
- if (downloadSize == totalSize)
- {
- File.Move(tempPath, info.SavePath);
- File.Delete(configPath);
- }
-
- if (cancelTokenSource.IsCancellationRequested && StopEvent != null)
- {
- StopEvent();
- //保存配置文件
- FileDownloadConfig.SaveConfig(configPath, downloadSize, totalSize, downQueue);
- }
- #endregion
-
- }
- catch (Exception ex)
- {
- ErrorMakedEvent?.Invoke(ex.Message);
- }
- });
-
- }
-
- public void Stop()
- {
- cancelTokenSource.Cancel();
- }
-
- public void Suspend()
- {
- mre.Reset();
- }
-
- public void Resume()
- {
- mre.Set();
- }
-
- //#region 获取文件信息
- //public class FileMessage
- //{
- // public long Length { get; set; }
- // public string FileName { get; set; }
- //}
-
- //public FileMessage GetFileMessage(WebResponse response)
- //{
- // FileMessage info = new FileMessage();
-
- // if (response.Headers["Content-Disposition"] != null)
- // {
- // Match match = Regex.Match(response.Headers["Content-Disposition"], "filename=(.*)");
- // if (match.Success)
- // {
- // string fileName = match.Groups[1].Value;
- // Encoding encoding = Encoding.UTF8;
- // string str = (response as HttpWebResponse).CharacterSet;
- // if (!string.IsNullOrEmpty(str))
- // {
- // encoding = Encoding.GetEncoding(str);
- // }
- // info.FileName = System.Web.HttpUtility.UrlDecode(fileName, encoding);
- // }
- // }
-
- // if (response.Headers["Content-Length"] != null)
- // {
- // info.Length = long.Parse(response.Headers.Get("Content-Length"));
- // }
- // else
- // {
- // info.Length = response.ContentLength;
- // }
-
- // return info;
- //}
-
-
- //#endregion
-
- //private void SaveConfig(string configPath, long downloadSize, long totalSize, Queue downQueue)
- //{
- // stringBuilder sb = new stringBuilder();
- // sb.Append(downloadSize + ";" + totalSize + ";");
- // foreach (ThreadDownloadInfo info in downQueue)
- // {
- // sb.Append("(" + info.startLength + ",");
- // sb.Append(info.length + ");");
- // }
-
- // byte[] buffer = Encoding.UTF8.GetBytes(sb.Tostring());
- // string str = Convert.ToBase64string(buffer);
- // File.WriteAllText(configPath, str);
- //}
-
- //private List ReadConfig(string configPath)
- //{
- // List list = new List();
- // string str = File.ReadAllText(configPath);
- // byte[] buffer = Convert.FromBase64string(str);
- // str =Encoding.UTF8.Getstring(buffer);
- // lock (locker)
- // {
- // string[] split = str.Split(';');
- // long downloadSize = Convert.ToInt64(split[0]);
- // long totalSize = Convert.ToInt64(split[1]);
- // Queue downQueue = new Queue(); //下载信息队列
- // foreach (Match match in Regex.Matches(str, "\\((\\d+),(\\d+)\\);"))
- // {
- // ThreadDownloadInfo downInfo = new ThreadDownloadInfo();
- // downInfo.startLength = Convert.ToInt64(match.Groups[1].Value);
- // downInfo.length = Convert.ToInt32(match.Groups[2].Value);
- // downQueue.Enqueue(downInfo);
- // }
-
- // list.Add(downloadSize);
- // list.Add(totalSize);
- // list.Add(downQueue);
- // }
-
- // return list;
- //}
-
-
- }
-
-}
diff --git a/src/Core/api/fileDownload/FileDownloadInfo.cs b/src/Core/api/fileDownload/FileDownloadInfo.cs
deleted file mode 100644
index e40cbc6..0000000
--- a/src/Core/api/fileDownload/FileDownloadInfo.cs
+++ /dev/null
@@ -1,77 +0,0 @@
-using System;
-using System.IO;
-
-namespace Core.api.fileDownload
-{
- public class FileDownloadInfo
- {
-
-
- // 下载地址
- public string DownLoadUrl { get; set; }
-
- private string _localSaveFolder;
- // 本地保存路径
- public string LocalSaveFolder
- {
- get { return _localSaveFolder; }
- set
- { _localSaveFolder = value; }
- }
-
- // 包含文件名的完整保存路径
- private string _savePath;
- public string SavePath
- {
- get
- {
- if (_savePath == null)
- {
- if (_localSaveFolder == null)
- {
- throw new Exception("本地保存路径不能为空");
- }
-
- _savePath = Path.Combine(_localSaveFolder, Path.GetFileName(DownLoadUrl));
-
- if (File.Exists(_savePath))
- {
- if (IsNew)
- {
- if (IsOver)
- {
- File.Delete(_savePath);
- }
- else
- {
- _savePath = _savePath.Substring(0, _savePath.LastIndexOf(".")) + "(2)" + _savePath.Substring(_savePath.LastIndexOf("."));
- }
- }
- }
- }
-
- return _savePath;
- }
- set
- {
- _savePath = value;
- }
- }
-
- private int _threadCount = 1;
- ////// 线程数
- public int ThreadCount
- {
- get { return _threadCount; }
- set { _threadCount = value; }
- }
-
- ////// 是否覆盖已存在的文件
- public bool IsOver { get; set; }
-
- ////// 是否重新下载
- public bool IsNew { get; set; }
-
-
- }
-}
diff --git a/src/Core/api/fileDownload/FileInfo.cs b/src/Core/api/fileDownload/FileInfo.cs
deleted file mode 100644
index 934f84d..0000000
--- a/src/Core/api/fileDownload/FileInfo.cs
+++ /dev/null
@@ -1,43 +0,0 @@
-using System.Net;
-using System.Text.RegularExpressions;
-
-namespace Core.api.fileDownload
-{
- internal class FileInfo
- {
- public long Length { get; set; }
- public string FileName { get; set; }
-
- ///
- /// 获取远程文件的信息
- ///
- ///
- ///
- public static FileInfo GetFileMessage(WebResponse response)
- {
- FileInfo info = new FileInfo();
-
- if (response.Headers["Content-Disposition"] != null)
- {
- Match match = Regex.Match(response.Headers["Content-Disposition"], "filename=(.*)");
- if (match.Success)
- {
- string fileName = match.Groups[1].Value;
- info.FileName = WebUtility.UrlDecode(fileName);
- }
- }
-
- if (response.Headers["Content-Length"] != null)
- {
- info.Length = long.Parse(response.Headers.Get("Content-Length"));
- }
- else
- {
- info.Length = response.ContentLength;
- }
-
- return info;
- }
-
- }
-}
diff --git a/src/Core/api/fileDownload/ThreadDownloadInfo.cs b/src/Core/api/fileDownload/ThreadDownloadInfo.cs
deleted file mode 100644
index f1e4364..0000000
--- a/src/Core/api/fileDownload/ThreadDownloadInfo.cs
+++ /dev/null
@@ -1,11 +0,0 @@
-namespace Core.api.fileDownload
-{
- internal class ThreadDownloadInfo
- {
- // 开始位置
- public long StartLength { get; set; }
-
- // 下载量
- public int Length { get; set; }
- }
-}
diff --git a/src/Core/api/history/History.cs b/src/Core/api/history/History.cs
deleted file mode 100644
index c02e92a..0000000
--- a/src/Core/api/history/History.cs
+++ /dev/null
@@ -1,90 +0,0 @@
-using Core.entity2.history;
-using Newtonsoft.Json;
-using System;
-
-namespace Core.api.history
-{
- ///
- /// 历史记录
- ///
- public class History
- {
- private static History instance;
-
- ///
- /// 获取UserInfo实例
- ///
- ///
- public static History GetInstance()
- {
- if (instance == null)
- {
- instance = new History();
- }
- return instance;
- }
-
- ///
- /// History()方法,必须使用单例模式
- ///
- private History() { }
-
- ///
- /// 获取历史记录列表(视频、直播、专栏)
- /// startId和startTime必须同时使用才有效,分别对应结果中的max和view_at,默认为0
- ///
- /// 历史记录开始目标ID
- /// 历史记录开始时间
- /// 每页项数
- /// 历史记录ID类型
- ///
- public HistoryData GetHistory(long startId, long startTime, int ps = 30, HistoryBusiness business = HistoryBusiness.ARCHIVE)
- {
- string businessStr = string.Empty;
- switch (business)
- {
- case HistoryBusiness.ARCHIVE:
- businessStr = "archive";
- break;
- case HistoryBusiness.PGC:
- businessStr = "pgc";
- break;
- case HistoryBusiness.LIVE:
- businessStr = "live";
- break;
- case HistoryBusiness.ARTICLE_LIST:
- businessStr = "article-list";
- break;
- case HistoryBusiness.ARTICLE:
- businessStr = "article";
- 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 = Utils.RequestWeb(url, referer);
-
- try
- {
- var history = JsonConvert.DeserializeObject(response);
- if (history == null || history.Data == null) { return null; }
- return history.Data;
- }
- catch (Exception e)
- {
- Console.WriteLine("GetHistory()发生异常: {0}", e);
- return null;
- }
- }
-
- }
-
- public enum HistoryBusiness
- {
- ARCHIVE = 1, // 稿件
- PGC, // 番剧(影视)
- LIVE, // 直播
- ARTICLE_LIST, // 文集
- ARTICLE, // 文章
- }
-
-}
diff --git a/src/Core/api/history/ToView.cs b/src/Core/api/history/ToView.cs
deleted file mode 100644
index ceff6ef..0000000
--- a/src/Core/api/history/ToView.cs
+++ /dev/null
@@ -1,58 +0,0 @@
-using Core.entity2.history;
-using Newtonsoft.Json;
-using System;
-using System.Collections.Generic;
-
-namespace Core.api.history
-{
- ///
- /// 获取稍后再看列表
- ///
- public class ToView
- {
- private static ToView instance;
-
- ///
- /// 获取ToView实例
- ///
- ///
- public static ToView GetInstance()
- {
- if (instance == null)
- {
- instance = new ToView();
- }
- return instance;
- }
-
- ///
- /// 隐藏ToView()方法,必须使用单例模式
- ///
- private ToView() { }
-
- ///
- /// 获取稍后再看视频列表
- ///
- ///
- public List GetHistoryToView()
- {
- string url = "https://api.bilibili.com/x/v2/history/toview/web";
- string referer = "https://www.bilibili.com";
- string response = Utils.RequestWeb(url, referer);
-
- try
- {
- var toView = JsonConvert.DeserializeObject(response);
- if (toView == null || toView.Data == null) { return null; }
- return toView.Data.List;
- }
- catch (Exception e)
- {
- Console.WriteLine("GetHistoryToView()发生异常: {0}", e);
- return null;
- }
- }
-
- }
-
-}
diff --git a/src/Core/api/login/LoginHelper.cs b/src/Core/api/login/LoginHelper.cs
deleted file mode 100644
index 7d23378..0000000
--- a/src/Core/api/login/LoginHelper.cs
+++ /dev/null
@@ -1,231 +0,0 @@
-using Core.settings;
-using System;
-using System.Drawing;
-using System.IO;
-using System.Net;
-using System.Windows.Media.Imaging;
-
-namespace Core.api.login
-{
- public class LoginHelper
- {
- private static LoginHelper instance;
-
- ///
- /// 获取LoginHelper实例
- ///
- ///
- public static LoginHelper GetInstance()
- {
- if (instance == null)
- {
- instance = new LoginHelper();
- }
- return instance;
- }
-
- ///
- /// 隐藏LoginHelper()方法,必须使用单例模式
- ///
- private LoginHelper() { }
-
- private static readonly string LOCAL_LOGIN_INFO = Common.ConfigPath + "Login";
- private static readonly string SecretKey = "Ps*rB$TGaM#&JvOe"; // 16位密码,ps:密码位数没有限制,可任意设置
-
- ///
- /// 获得登录二维码
- ///
- ///
- public BitmapImage GetLoginQRCode()
- {
- try
- {
- string loginUrl = Login.GetInstance().GetLoginUrl().Data.Url;
- return GetLoginQRCode(loginUrl);
- }
- catch (Exception e)
- {
- Console.WriteLine("GetLoginQRCode()发生异常: {0}", e);
- return null;
- }
- }
-
- ///
- /// 根据输入url生成二维码
- ///
- ///
- ///
- public BitmapImage GetLoginQRCode(string url)
- {
- // 设置的参数影响app能否成功扫码
- Bitmap qrCode = Utils.EncodeQRCode(url, 10, 10, null, 0, 0, false);
-
- MemoryStream ms = new MemoryStream();
- qrCode.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
- byte[] bytes = ms.GetBuffer();
- ms.Close();
-
- BitmapImage image = new BitmapImage();
- image.BeginInit();
- image.StreamSource = new MemoryStream(bytes);
- image.EndInit();
- return image;
- }
-
- ///
- /// 保存登录的cookies到文件
- ///
- ///
- ///
- public bool SaveLoginInfoCookies(string url)
- {
- if (!Directory.Exists(Common.ConfigPath))
- {
- Directory.CreateDirectory(Common.ConfigPath);
- }
-
- string tempFile = LOCAL_LOGIN_INFO + "-" + Guid.NewGuid().ToString("N");
- CookieContainer cookieContainer = Utils.ParseCookie(url);
-
- bool isSucceed = Utils.WriteCookiesToDisk(tempFile, cookieContainer);
- if (isSucceed)
- {
- // 加密密钥,增加机器码
- string password = SecretKey + MachineCode.GetMachineCodeString();
-
- try
- {
- Encryptor.EncryptFile(tempFile, LOCAL_LOGIN_INFO, password);
- }
- catch (Exception e)
- {
- Console.WriteLine("SaveLoginInfoCookies()发生异常: {0}", e);
- return false;
- }
- }
-
- if (File.Exists(tempFile))
- {
- File.Delete(tempFile);
- }
- return isSucceed;
- }
-
- ///
- /// 获得登录的cookies
- ///
- ///
- public CookieContainer GetLoginInfoCookies()
- {
- string tempFile = LOCAL_LOGIN_INFO + "-" + Guid.NewGuid().ToString("N");
-
- if (File.Exists(LOCAL_LOGIN_INFO))
- {
- try
- {
- // 加密密钥,增加机器码
- string password = SecretKey + MachineCode.GetMachineCodeString();
- Encryptor.DecryptFile(LOCAL_LOGIN_INFO, tempFile, password);
- }
- catch (CryptoHelpException e)
- {
- Console.WriteLine("GetLoginInfoCookies()发生异常: {0}", e);
- if (File.Exists(tempFile))
- {
- File.Delete(tempFile);
- }
- return null;
- }
- catch (FileNotFoundException e)
- {
- Console.WriteLine("GetLoginInfoCookies()发生异常: {0}", e);
- if (File.Exists(tempFile))
- {
- File.Delete(tempFile);
- }
- return null;
- }
- catch (DirectoryNotFoundException e)
- {
- Console.WriteLine("GetLoginInfoCookies()发生异常: {0}", e);
- if (File.Exists(tempFile))
- {
- File.Delete(tempFile);
- }
- return null;
- }
- catch (Exception e)
- {
- Console.WriteLine("GetLoginInfoCookies()发生异常: {0}", e);
- if (File.Exists(tempFile))
- {
- File.Delete(tempFile);
- }
- return null;
- }
- }
- else { return null; }
-
- CookieContainer cookies = Utils.ReadCookiesFromDisk(tempFile);
-
- if (File.Exists(tempFile))
- {
- File.Delete(tempFile);
- }
- return cookies;
- }
-
- ///
- /// 返回登录信息的cookies的字符串
- ///
- ///
- public string GetLoginInfoCookiesString()
- {
- var cookieContainer = GetLoginInfoCookies();
- if (cookieContainer == null)
- {
- return "";
- }
-
- var cookies = Utils.GetAllCookies(cookieContainer);
-
- string cookie = string.Empty;
- foreach (var item in cookies)
- {
- cookie += item.ToString() + ";";
- }
- return cookie.TrimEnd(';');
- }
-
- ///
- /// 注销登录
- ///
- ///
- public bool Logout()
- {
- if (File.Exists(LOCAL_LOGIN_INFO))
- {
- try
- {
- File.Delete(LOCAL_LOGIN_INFO);
-
- Settings.GetInstance().SetUserInfo(new UserInfoForSetting
- {
- Mid = -1,
- Name = "",
- IsLogin = false,
- IsVip = false
- });
- return true;
- }
- catch (IOException e)
- {
- Console.WriteLine("Logout()发生异常: {0}", e);
- return false;
- }
- }
- return false;
- }
-
- }
-}
diff --git a/src/Core/api/users/UserInfo.cs b/src/Core/api/users/UserInfo.cs
deleted file mode 100644
index 5c0d421..0000000
--- a/src/Core/api/users/UserInfo.cs
+++ /dev/null
@@ -1,81 +0,0 @@
-using Core.entity2.users;
-using Newtonsoft.Json;
-using System;
-
-namespace Core.api.users
-{
- ///
- /// 用户基本信息
- ///
- public class UserInfo
- {
- private static UserInfo instance;
-
- ///
- /// 获取UserInfo实例
- ///
- ///
- public static UserInfo GetInstance()
- {
- if (instance == null)
- {
- instance = new UserInfo();
- }
- return instance;
- }
-
- ///
- /// 隐藏UserInfo()方法,必须使用单例模式
- ///
- private UserInfo() { }
-
- ///
- /// 用户详细信息1 (用于空间)
- ///
- /// 目标用户UID
- ///
- public SpaceInfo GetInfoForSpace(long mid)
- {
- string url = $"https://api.bilibili.com/x/space/acc/info?mid={mid}";
- string referer = "https://www.bilibili.com";
- string response = Utils.RequestWeb(url, referer);
-
- try
- {
- var spaceInfo = JsonConvert.DeserializeObject(response);
- if (spaceInfo == null || spaceInfo.Data == null) { return null; }
- return spaceInfo.Data;
- }
- catch (Exception e)
- {
- Console.WriteLine("GetInfoForSpace()发生异常: {0}", e);
- return null;
- }
- }
-
- ///
- /// 本用户详细信息
- ///
- ///
- public MyInfo GetMyInfo()
- {
- string url = "https://api.bilibili.com/x/space/myinfo";
- string referer = "https://www.bilibili.com";
- string response = Utils.RequestWeb(url, referer);
-
- try
- {
- var myInfo = JsonConvert.DeserializeObject(response);
- if (myInfo == null || myInfo.Data == null) { return null; }
- return myInfo.Data;
- }
- catch (Exception e)
- {
- Console.WriteLine("GetMyInfo()发生异常: {0}", e);
- return null;
- }
- }
-
- }
-
-}
diff --git a/src/Core/api/users/UserRelation.cs b/src/Core/api/users/UserRelation.cs
deleted file mode 100644
index b7e432e..0000000
--- a/src/Core/api/users/UserRelation.cs
+++ /dev/null
@@ -1,290 +0,0 @@
-using Core.entity2.users;
-using Newtonsoft.Json;
-using System;
-using System.Collections.Generic;
-
-namespace Core.api.users
-{
- ///
- /// 用户关系相关
- ///
- public class UserRelation
- {
- private static UserRelation instance;
-
- ///
- /// 获取UserRelation实例
- ///
- ///
- public static UserRelation GetInstance()
- {
- if (instance == null)
- {
- instance = new UserRelation();
- }
- return instance;
- }
-
- ///
- /// 隐藏UserRelation()方法,必须使用单例模式
- ///
- private UserRelation() { }
-
- ///
- /// 查询用户粉丝明细
- ///
- /// 目标用户UID
- /// 页码
- /// 每页项数
- ///
- public 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 = Utils.RequestWeb(url, referer);
-
- try
- {
- var relationFollower = JsonConvert.DeserializeObject(response);
- if (relationFollower == null || relationFollower.Data == null) { return null; }
- return relationFollower.Data;
- }
- catch (Exception e)
- {
- Console.WriteLine("GetFollowers()发生异常: {0}", e);
- return null;
- }
- }
-
- ///
- /// 查询用户所有的粉丝明细
- ///
- /// 目标用户UID
- ///
- public List GetAllFollowers(long mid)
- {
- List result = new List();
-
- int i = 0;
- while (true)
- {
- i++;
- int ps = 50;
-
- var data = GetFollowers(mid, i, ps);
- //if (data == null) { continue; }
-
- if (data == null || data.List == null || data.List.Count == 0)
- { break; }
-
- result.AddRange(data.List);
- }
-
- return result;
- }
-
- ///
- /// 查询用户关注明细
- ///
- /// 目标用户UID
- /// 页码
- /// 每页项数
- /// 排序方式
- ///
- public RelationFollow GetFollowings(long mid, int pn, int ps, FollowingOrder order = FollowingOrder.DEFAULT)
- {
- string 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 = Utils.RequestWeb(url, referer);
-
- try
- {
- var relationFollower = JsonConvert.DeserializeObject(response);
- if (relationFollower == null || relationFollower.Data == null) { return null; }
- return relationFollower.Data;
- }
- catch (Exception e)
- {
- Console.WriteLine("GetFollowings()发生异常: {0}", e);
- return null;
- }
- }
-
- ///
- /// 查询用户所有的关注明细
- ///
- /// 目标用户UID
- /// 排序方式
- ///
- public List GetAllFollowings(long mid, FollowingOrder order = FollowingOrder.DEFAULT)
- {
- List result = new List();
-
- int i = 0;
- while (true)
- {
- i++;
- int ps = 50;
-
- var data = GetFollowings(mid, i, ps, order);
- //if (data == null) { continue; }
-
- if (data == null || data.List == null || data.List.Count == 0)
- { break; }
-
- result.AddRange(data.List);
- }
-
- return result;
- }
-
- ///
- /// 查询悄悄关注明细
- ///
- /// 页码
- /// 每页项数
- ///
- public 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 = Utils.RequestWeb(url, referer);
-
- try
- {
- var relationWhisper = JsonConvert.DeserializeObject(response);
- if (relationWhisper == null || relationWhisper.Data == null) { return null; }
- return relationWhisper.Data;
- }
- catch (Exception e)
- {
- Console.WriteLine("GetWhispers()发生异常: {0}", e);
- return null;
- }
- }
-
- ///
- /// 查询黑名单明细
- ///
- /// 页码
- /// 每页项数
- ///
- public 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 = Utils.RequestWeb(url, referer);
-
- try
- {
- var relationBlack = JsonConvert.DeserializeObject(response);
- if (relationBlack == null || relationBlack.Data == null) { return null; }
- return relationBlack.Data;
- }
- catch (Exception e)
- {
- Console.WriteLine("GetBlacks()发生异常: {0}", e);
- return null;
- }
- }
-
- // 关注分组相关,只能查询当前登录账户的信息
-
- ///
- /// 查询关注分组列表
- ///
- ///
- public List GetFollowingGroup()
- {
- string url = $"https://api.bilibili.com/x/relation/tags";
- string referer = "https://www.bilibili.com";
- string response = Utils.RequestWeb(url, referer);
-
- try
- {
- var followingGroup = JsonConvert.DeserializeObject(response);
- if (followingGroup == null || followingGroup.Data == null) { return null; }
- return followingGroup.Data;
- }
- catch (Exception e)
- {
- Console.WriteLine("GetFollowingGroup()发生异常: {0}", e);
- return null;
- }
- }
-
- ///
- /// 查询关注分组明细
- ///
- /// 分组ID
- /// 页数
- /// 每页项数
- /// 排序方式
- ///
- public List GetFollowingGroupContent(int tagId, int pn, int ps, FollowingOrder order = FollowingOrder.DEFAULT)
- {
- string orderType = "";
- if (order == FollowingOrder.ATTENTION)
- {
- orderType = "attention";
- }
-
- string 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 = Utils.RequestWeb(url, referer);
-
- try
- {
- var content = JsonConvert.DeserializeObject(response);
- if (content == null || content.Data == null) { return null; }
- return content.Data;
- }
- catch (Exception e)
- {
- Console.WriteLine("GetFollowingGroupContent()发生异常: {0}", e);
- return null;
- }
- }
-
- ///
- /// 查询所有的关注分组明细
- ///
- /// 分组ID
- /// 排序方式
- ///
- public List GetAllFollowingGroupContent(int tagId, FollowingOrder order = FollowingOrder.DEFAULT)
- {
- List result = new List();
-
- int i = 0;
- while (true)
- {
- i++;
- int ps = 50;
-
- var data = GetFollowingGroupContent(tagId, i, ps, order);
-
- if (data == null || data.Count == 0)
- { break; }
-
- result.AddRange(data);
- }
-
- return result;
- }
-
- }
-
- public enum FollowingOrder
- {
- DEFAULT = 1, // 按照关注顺序排列,默认
- ATTENTION // 按照最常访问排列
- }
-
-}
diff --git a/src/Core/api/users/UserSpace.cs b/src/Core/api/users/UserSpace.cs
deleted file mode 100644
index 4661fda..0000000
--- a/src/Core/api/users/UserSpace.cs
+++ /dev/null
@@ -1,520 +0,0 @@
-using Core.entity2.users;
-using Newtonsoft.Json;
-using Newtonsoft.Json.Linq;
-using System;
-using System.Collections.Generic;
-using System.Threading.Tasks;
-
-namespace Core.api.users
-{
- ///
- /// 用户空间信息
- ///
- public class UserSpace
- {
- private static UserSpace instance;
-
- ///
- /// 获取UserSpace实例
- ///
- ///
- public static UserSpace GetInstance()
- {
- if (instance == null)
- {
- instance = new UserSpace();
- }
- return instance;
- }
-
- ///
- /// 隐藏UserSpace()方法,必须使用单例模式
- ///
- private UserSpace() { }
-
- ///
- /// 查询空间设置
- ///
- ///
- ///
- public SpaceSettings GetSpaceSettings(long mid)
- {
- string url = $"https://space.bilibili.com/ajax/settings/getSettings?mid={mid}";
- string referer = "https://www.bilibili.com";
- string response = Utils.RequestWeb(url, referer);
-
- try
- {
- var settings = JsonConvert.DeserializeObject(response);
- if (settings == null || settings.Data == null || !settings.Status) { return null; }
-
- return settings.Data;
- }
- catch (Exception e)
- {
- Console.WriteLine("GetSpaceSettings()发生异常: {0}", e);
- return null;
- }
- }
-
- ///
- /// 获取用户投稿视频的所有分区
- ///
- /// 用户id
- ///
- public List GetPublicationType(long mid)
- {
- int pn = 1;
- int ps = 1;
- var publication = GetPublication(mid, pn, ps);
- return GetPublicationType(publication);
- }
-
- ///
- /// 获取用户投稿视频的所有分区
- ///
- /// 用户id
- ///
- public List GetPublicationType(SpacePublicationList publication)
- {
- if (publication == null || publication.Tlist == null)
- {
- return null;
- }
-
- List result = new List();
- JObject typeList = JObject.Parse(publication.Tlist.ToString("N"));
- foreach (var item in typeList)
- {
- var value = JsonConvert.DeserializeObject(item.Value.ToString());
- result.Add(value);
- }
- return result;
- }
-
- ///
- /// 查询用户所有的投稿视频明细
- ///
- /// 用户id
- /// 排序
- /// 视频分区
- /// 搜索关键词
- ///
- public async Task> GetAllPublication(long mid, int tid = 0, PublicationOrder order = PublicationOrder.PUBDATE, string keyword = "")
- {
- List result = new List();
-
- await Task.Run(() =>
- {
- int i = 0;
- while (true)
- {
- i++;
- int ps = 100;
-
- var data = GetPublication(mid, i, ps, tid, order, keyword);
- //if (data == null) { continue; }
-
- if (data == null || data.Vlist == null || data.Vlist.Count == 0)
- { break; }
-
- result.AddRange(data.Vlist);
- }
- });
-
- return result;
- }
-
- ///
- /// 查询用户投稿视频明细
- ///
- /// 用户id
- /// 页码
- /// 每页的视频数
- /// 排序
- /// 视频分区
- /// 搜索关键词
- ///
- public SpacePublicationList GetPublication(long mid, int pn, int ps, int tid = 0, PublicationOrder order = PublicationOrder.PUBDATE, string keyword = "")
- {
- string url = $"https://api.bilibili.com/x/space/arc/search?mid={mid}&pn={pn}&ps={ps}&order={order.ToString("G").ToLower()}&tid={tid}&keyword={keyword}";
- string referer = "https://www.bilibili.com";
- string response = Utils.RequestWeb(url, referer);
-
- try
- {
- // 忽略play的值为“--”时的类型错误
- var settings = new JsonSerializerSettings
- {
- Error = (sender, args) =>
- {
- if (Equals(args.ErrorContext.Member, "play") &&
- args.ErrorContext.OriginalObject.GetType() == typeof(SpacePublicationListVideo))
- {
- args.ErrorContext.Handled = true;
- }
- }
- };
-
- var spacePublication = JsonConvert.DeserializeObject(response, settings);
- if (spacePublication == null || spacePublication.Data == null) { return null; }
- return spacePublication.Data.List;
- }
- catch (Exception e)
- {
- Console.WriteLine("GetPublication()发生异常: {0}", e);
- return null;
- }
- }
-
- ///
- /// 查询用户频道列表
- ///
- /// 用户id
- ///
- public List GetChannelList(long mid)
- {
- string url = $"https://api.bilibili.com/x/space/channel/list?mid={mid}";
- string referer = "https://www.bilibili.com";
- string response = Utils.RequestWeb(url, referer);
-
- try
- {
- var spaceChannel = JsonConvert.DeserializeObject(response);
- if (spaceChannel == null || spaceChannel.Data == null) { return null; }
- return spaceChannel.Data.List;
- }
- catch (Exception e)
- {
- Console.WriteLine("GetChannelList()发生异常: {0}", e);
- return null;
- }
- }
-
- ///
- /// 查询用户频道中的所有视频
- ///
- ///
- ///
- ///
- public List GetAllChannelVideoList(long mid, long cid)
- {
- List result = new List();
-
- int i = 0;
- while (true)
- {
- i++;
- int ps = 100;
-
- var data = GetChannelVideoList(mid, cid, i, ps);
- if (data == null || data.Count == 0)
- { break; }
-
- result.AddRange(data);
- }
- return result;
- }
-
- ///
- /// 查询用户频道中的视频
- ///
- ///
- ///
- ///
- ///
- ///
- public List GetChannelVideoList(long mid, long cid, int pn, int ps)
- {
- string url = $"https://api.bilibili.com/x/space/channel/video?mid={mid}&cid={cid}&pn={pn}&ps={ps}";
- string referer = "https://www.bilibili.com";
- string response = Utils.RequestWeb(url, referer);
-
- try
- {
- var spaceChannelVideo = JsonConvert.DeserializeObject(response);
- if (spaceChannelVideo == null || spaceChannelVideo.Data == null || spaceChannelVideo.Data.List == null)
- { return null; }
- return spaceChannelVideo.Data.List.Archives;
- }
- catch (Exception e)
- {
- Console.WriteLine("GetChannelVideoList()发生异常: {0}", e);
- return null;
- }
- }
-
- ///
- /// 查询用户创建的视频收藏夹
- ///
- /// 目标用户UID
- /// 页码
- /// 每页项数
- ///
- public List GetCreatedFavoriteFolder(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 = Utils.RequestWeb(url, referer);
-
- try
- {
- var favoriteFolder = JsonConvert.DeserializeObject(response);
- if (favoriteFolder == null || favoriteFolder.Data == null || favoriteFolder.Data.List == null)
- { return null; }
- return favoriteFolder.Data.List;
- }
- catch (Exception e)
- {
- Console.WriteLine("GetCreatedFavoriteFolder()发生异常: {0}", e);
- return null;
- }
- }
-
- ///
- /// 查询所有的用户创建的视频收藏夹
- ///
- /// 目标用户UID
- ///
- public List GetAllCreatedFavoriteFolder(long mid)
- {
- List result = new List();
-
- int i = 0;
- while (true)
- {
- i++;
- int ps = 50;
-
- var data = GetCreatedFavoriteFolder(mid, i, ps);
- if (data == null || data.Count == 0)
- { break; }
-
- result.AddRange(data);
- }
- return result;
- }
-
- ///
- /// 查询用户收藏的视频收藏夹
- ///
- /// 目标用户UID
- /// 页码
- /// 每页项数
- ///
- public List GetCollectedFavoriteFolder(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 = Utils.RequestWeb(url, referer);
-
- try
- {
- var favoriteFolder = JsonConvert.DeserializeObject(response);
- if (favoriteFolder == null || favoriteFolder.Data == null || favoriteFolder.Data.List == null)
- { return null; }
- return favoriteFolder.Data.List;
- }
- catch (Exception e)
- {
- Console.WriteLine("GetCollectedFavoriteFolder()发生异常: {0}", e);
- return null;
- }
- }
-
- ///
- /// 查询所有的用户收藏的视频收藏夹
- ///
- /// 目标用户UID
- ///
- public List GetAllCollectedFavoriteFolder(long mid)
- {
- List result = new List();
-
- int i = 0;
- while (true)
- {
- i++;
- int ps = 50;
-
- var data = GetCollectedFavoriteFolder(mid, i, ps);
- if (data == null || data.Count == 0)
- { break; }
-
- result.AddRange(data);
- }
- return result;
- }
-
- ///
- /// 查询视频收藏夹的内容
- ///
- /// 收藏夹ID
- /// 页码
- /// 每页项数
- ///
- public List GetFavoriteFolderResource(long mediaId, int pn, int ps)
- {
- string url = $"https://api.bilibili.com/x/v3/fav/resource/list?media_id={mediaId}&pn={pn}&ps={ps}";
- string referer = "https://www.bilibili.com";
- string response = Utils.RequestWeb(url, referer);
-
- try
- {
- var resource = JsonConvert.DeserializeObject(response);
- if (resource == null || resource.Data == null || resource.Data.Medias == null)
- { return null; }
- return resource.Data.Medias;
- }
- catch (Exception e)
- {
- Console.WriteLine("GetFavoriteFolderResource()发生异常: {0}", e);
- return null;
- }
- }
-
- ///
- /// 查询视频收藏夹的所有内容
- ///
- /// 收藏夹ID
- ///
- public List GetAllFavoriteFolderResource(long mediaId)
- {
- List result = new List();
-
- int i = 0;
- while (true)
- {
- i++;
- int ps = 20;
-
- var data = GetFavoriteFolderResource(mediaId, i, ps);
- if (data == null || data.Count == 0)
- { break; }
-
- result.AddRange(data);
- }
- return result;
- }
-
- ///
- /// 查询用户发布的课程列表
- ///
- /// 目标用户UID
- /// 页码
- /// 每页项数
- ///
- public List GetCheese(long mid, int pn, int ps)
- {
- string url = $"https://api.bilibili.com/pugv/app/web/season/page?mid={mid}&pn={pn}&ps={ps}";
- string referer = "https://www.bilibili.com";
- string response = Utils.RequestWeb(url, referer);
-
- try
- {
- var cheese = JsonConvert.DeserializeObject(response);
- if (cheese == null || cheese.Data == null || cheese.Data.Items == null)
- { return null; }
- return cheese.Data.Items;
- }
- catch (Exception e)
- {
- Console.WriteLine("GetCheese()发生异常: {0}", e);
- return null;
- }
- }
-
- ///
- /// 查询用户发布的所有课程列表
- ///
- /// 目标用户UID
- ///
- public List GetAllCheese(long mid)
- {
- List result = new List();
-
- int i = 0;
- while (true)
- {
- i++;
- int ps = 50;
-
- var data = GetCheese(mid, i, ps);
- if (data == null || data.Count == 0)
- { break; }
-
- result.AddRange(data);
- }
- return result;
- }
-
- ///
- /// 查询用户追番(追剧)明细
- ///
- /// 目标用户UID
- /// 查询类型
- /// 页码
- /// 每页项数
- ///
- public BangumiFollowData GetBangumiFollow(long mid, BangumiType type, int pn, int ps)
- {
- string url = $"https://api.bilibili.com/x/space/bangumi/follow/list?vmid={mid}&type={type:D}&pn={pn}&ps={ps}";
- string referer = "https://www.bilibili.com";
- string response = Utils.RequestWeb(url, referer);
-
- try
- {
- var bangumiFollow = JsonConvert.DeserializeObject(response);
- if (bangumiFollow == null || bangumiFollow.Data == null)
- { return null; }
- return bangumiFollow.Data;
- }
- catch (Exception e)
- {
- Console.WriteLine("GetBangumiFollow()发生异常: {0}", e);
- return null;
- }
- }
-
- ///
- /// 查询用户所有的追番(追剧)明细
- ///
- /// 目标用户UID
- /// 查询类型
- ///
- public List GetAllBangumiFollow(long mid, BangumiType type)
- {
- List result = new List();
-
- int i = 0;
- while (true)
- {
- i++;
- int ps = 30;
-
- var data = GetBangumiFollow(mid, type, i, ps);
- if (data == null || data.List == null || data.List.Count == 0)
- { break; }
-
- result.AddRange(data.List);
- }
- return result;
- }
-
- }
-
-
- public enum PublicationOrder
- {
- PUBDATE = 1, // 最新发布,默认
- CLICK, // 最多播放
- STOW // 最多收藏
- }
-
- public enum BangumiType
- {
- ANIME = 1, // 番剧
- EPISODE = 2 // 剧集、电影
- }
-
-}
diff --git a/src/Core/api/users/UserStatus.cs b/src/Core/api/users/UserStatus.cs
deleted file mode 100644
index 3dcbb6a..0000000
--- a/src/Core/api/users/UserStatus.cs
+++ /dev/null
@@ -1,83 +0,0 @@
-using Core.entity2.users;
-using Newtonsoft.Json;
-using System;
-
-namespace Core.api.users
-{
- ///
- /// 用户状态数
- ///
- public class UserStatus
- {
- private static UserStatus instance;
-
- ///
- /// 获取UserStatus实例
- ///
- ///
- public static UserStatus GetInstance()
- {
- if (instance == null)
- {
- instance = new UserStatus();
- }
- return instance;
- }
-
- ///
- /// 隐藏UserStatus()方法,必须使用单例模式
- ///
- private UserStatus() { }
-
- ///
- /// 关系状态数
- ///
- ///
- ///
- public UserRelationStat GetUserRelationStat(long mid)
- {
- string url = $"https://api.bilibili.com/x/relation/stat?vmid={mid}";
- string referer = "https://www.bilibili.com";
- string response = Utils.RequestWeb(url, referer);
-
- try
- {
- var userRelationStat = JsonConvert.DeserializeObject(response);
- if (userRelationStat == null || userRelationStat.Data == null) { return null; }
- return userRelationStat.Data;
- }
- catch (Exception e)
- {
- Console.WriteLine("GetUserRelationStat()发生异常: {0}", e);
- return null;
- }
- }
-
- ///
- /// UP主状态数
- ///
- /// 注:该接口需要任意用户登录,否则不会返回任何数据
- ///
- ///
- ///
- public UpStat GetUpStat(long mid)
- {
- string url = $"https://api.bilibili.com/x/space/upstat?mid={mid}";
- string referer = "https://www.bilibili.com";
- string response = Utils.RequestWeb(url, referer);
-
- try
- {
- var upStat = JsonConvert.DeserializeObject(response);
- if (upStat == null || upStat.Data == null) { return null; }
- return upStat.Data;
- }
- catch (Exception e)
- {
- Console.WriteLine("GetUpStat()发生异常: {0}", e);
- return null;
- }
- }
-
- }
-}
diff --git a/src/Core/aria2cNet/Aria2c.cs b/src/Core/aria2cNet/Aria2c.cs
deleted file mode 100644
index 6067942..0000000
--- a/src/Core/aria2cNet/Aria2c.cs
+++ /dev/null
@@ -1,433 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.IO;
-using System.Net.WebSockets;
-using System.Text;
-using System.Threading;
-using System.Threading.Tasks;
-
-// 代码来源
-// https://blog.csdn.net/haibin258/article/details/87905628
-
-// Aria2详细信息请看
-// https://aria2.github.io/manual/en/html/aria2c.html#rpc-interface
-
-// 废弃
-namespace Core.aria2cNet
-{
- //定义一个类用于转码成JSON字符串发送给Aria2 json-rpc接口
- public class JsonClass
- {
- public string Jsonrpc { get; set; }
- public string Id { get; set; }
- public string Method { get; set; }
- public List Params { get; set; }
- }
-
- public class Aria2
- {
- public static ClientWebSocket webSocket; // 用于连接到Aria2Rpc的客户端
- public static CancellationToken cancellationToken; // 传播有关应取消操作的通知
-
- ///
- /// 连接Aria2Rpc服务器
- ///
- ///
- ///
- public static async Task ConnectServer(string uri)
- {
- webSocket = new ClientWebSocket(); // 用于连接到Aria2Rpc的客户端
- cancellationToken = new CancellationToken(); // 传播有关应取消操作的通知
- bool status = false; //储存连接状态
- try
- {
- //连接服务器
- await webSocket.ConnectAsync(new Uri(uri), cancellationToken);
- }
- catch
- {
- status = false;
- }
- //检查连接是否成功
- if (webSocket.State == WebSocketState.Open)
- {
- status = true;
- }
- return status;
- }
-
-
- ///
- /// JsonClass类转为json格式
- ///
- ///
- ///
- private static string ToJson(JsonClass json)
- {
- string str = "{" + "\"jsonrpc\":\"" + json.Jsonrpc + "\",\"id\":\"" + json.Id + "\",\"method\":\"" + json.Method + "\",\"params\":[";
- for (int i = 0; i < json.Params.Count; i++)
- {
- if (json.Method == "aria2.addUri")
- {
- str += "[\"" + json.Params[i] + "\"]";
- }
- else if (json.Method == "aria2.tellStatus")
- {
- if (i == 0)
- {
- str += "\"" + json.Params[i] + "\"";
- }
- else
- {
- str += "[\"" + json.Params[i] + "\"]";
- }
- }
- else
- {
- str += "\"" + json.Params[i] + "\"";
- }
- if (json.Params.Count - 1 > i)
- {
- str += ",";
- }
- }
- str += "]}";
- //最后得到类似
- //{"jsonrpc":"2.0","id":"qwer","method":"aria2.addUri","params:"[["http://www.baidu.com"]]}
- return str;
- }
-
-
- ///
- /// 发送json并返回json消息
- ///
- ///
- ///
- private static async Task SendAndReceive(JsonClass json)
- {
- string str = ToJson(json);
- try
- {
- //发送json数据
- await webSocket.SendAsync(new ArraySegment(Encoding.UTF8.GetBytes(str)), WebSocketMessageType.Text, true, cancellationToken);
- var result = new byte[1024];
- //接收数据
- await webSocket.ReceiveAsync(new ArraySegment(result), new CancellationToken());
- str += "\r\n" + Encoding.UTF8.GetString(result, 0, result.Length) + "\r\n";
- }
- catch
- {
- str = "连接错误";
- }
- return str;
- }
-
-
- ///
- /// 添加新的下载
- ///
- ///
- ///
- public static async Task AddUri(string uri)
- {
- var json = new JsonClass
- {
- Jsonrpc = "2.0",
- Id = "qwer",
- Method = "aria2.addUri"
- };
- List paramslist = new List();
- //添加下载地址
- paramslist.Add(uri);
- json.Params = paramslist;
- string str = await SendAndReceive(json);
- return str;
- }
-
-
- ///
- /// 上传“.torrent”文件添加BitTorrent下载
- ///
- ///
- ///
- public static async Task AddTorrent(string path)
- {
- string str = "";
- string fsbase64 = "";
- byte[] fs = File.ReadAllBytes(path);
- fsbase64 = Convert.ToBase64String(fs); //转为Base64编码
-
- var json = new JsonClass();
- json.Jsonrpc = "2.0";
- json.Id = "qwer";
- json.Method = "aria2.addTorrent";
- List paramslist = new List();
- //添加“.torrent”文件本地地址
- paramslist.Add(fsbase64);
- json.Params = paramslist;
- str = await SendAndReceive(json);
- return str;
- }
-
-
- ///
- /// 删除已经停止的任务,强制删除请使用ForceRemove方法
- ///
- ///
- ///
- public static async Task Remove(string gid)
- {
- string str = "";
- var json = new JsonClass
- {
- Jsonrpc = "2.0",
- Id = "qwer",
- Method = "aria2.remove"
- };
- List paramslist = new List();
- //添加下载地址
- paramslist.Add(gid);
- json.Params = paramslist;
- str = await SendAndReceive(json);
- return str;
- }
-
-
- ///
- /// 强制删除
- ///
- ///
- ///
- public static async Task ForceRemove(string gid)
- {
- string str = "";
- var json = new JsonClass
- {
- Jsonrpc = "2.0",
- Id = "qwer",
- Method = "aria2.forceRemove"
- };
- List paramslist = new List();
- //添加下载地址
- paramslist.Add(gid);
- json.Params = paramslist;
- str = await SendAndReceive(json);
- return str;
- }
-
-
- ///
- /// 暂停下载,强制暂停请使用ForcePause方法
- ///
- ///
- ///
- public static async Task Pause(string gid)
- {
- string str = "";
- var json = new JsonClass
- {
- Jsonrpc = "2.0",
- Id = "qwer",
- Method = "aria2.pause"
- };
- List paramslist = new List();
- //添加下载地址
- paramslist.Add(gid);
- json.Params = paramslist;
- str = await SendAndReceive(json);
- return str;
- }
-
-
- ///
- /// 暂停全部任务
- ///
- ///
- ///
- public static async Task PauseAll()
- {
- string str = "";
- var json = new JsonClass();
- json.Jsonrpc = "2.0";
- json.Id = "qwer";
- json.Method = "aria2.pauseAll";
- List paramslist = new List();
- //添加下载地址
- paramslist.Add("");
- json.Params = paramslist;
- str = await Aria2.SendAndReceive(json);
- return str;
- }
-
-
- ///
- /// 强制暂停下载
- ///
- ///
- ///
- public static async Task ForcePause(string gid)
- {
- string str = "";
- var json = new JsonClass();
- json.Jsonrpc = "2.0";
- json.Id = "qwer";
- json.Method = "aria2.forcePause";
- List paramslist = new List();
- //添加下载地址
- paramslist.Add(gid);
- json.Params = paramslist;
- str = await Aria2.SendAndReceive(json);
- return str;
- }
-
-
- ///
- /// 强制暂停全部下载
- ///
- ///
- ///
- public static async Task ForcePauseAll()
- {
- string str = "";
- var json = new JsonClass();
- json.Jsonrpc = "2.0";
- json.Id = "qwer";
- json.Method = "aria2.forcePauseAll";
- List paramslist = new List();
- //添加下载地址
- paramslist.Add("");
- json.Params = paramslist;
- str = await Aria2.SendAndReceive(json);
- return str;
- }
-
-
- ///
- /// 把正在下载的任务状态改为等待下载
- ///
- ///
- ///
- public static async Task PauseToWaiting(string gid)
- {
- string str = "";
- var json = new JsonClass();
- json.Jsonrpc = "2.0";
- json.Id = "qwer";
- json.Method = "aria2.unpause";
- List paramslist = new List();
- //添加下载地址
- paramslist.Add(gid);
- json.Params = paramslist;
- str = await Aria2.SendAndReceive(json);
- return str;
- }
-
-
- ///
- /// 把全部在下载的任务状态改为等待下载
- ///
- ///
- ///
- public static async Task PauseToWaitingAll()
- {
- string str = "";
- var json = new JsonClass();
- json.Jsonrpc = "2.0";
- json.Id = "qwer";
- json.Method = "aria2.unpauseAll";
- List paramslist = new List();
- //添加下载地址
- paramslist.Add("");
- json.Params = paramslist;
- str = await Aria2.SendAndReceive(json);
- return str;
- }
-
-
- ///
- /// 返回下载进度
- ///
- ///
- ///
- public static async Task TellStatus(string gid)
- {
- string str = "";
- var json = new JsonClass();
- json.Jsonrpc = "2.0";
- json.Id = "qwer";
- json.Method = "aria2.tellStatus";
- List paramslist = new List();
- //添加下载地址
- paramslist.Add(gid);
- paramslist.Add("completedLength\", \"totalLength\",\"downloadSpeed");
-
- json.Params = paramslist;
- str = await Aria2.SendAndReceive(json);
- return str;
- }
-
-
- ///
- /// 返回全局统计信息,例如整体下载和上载速度
- ///
- ///
- ///
- public static async Task GetGlobalStat(string gid)
- {
- string str = "";
- var json = new JsonClass();
- json.Jsonrpc = "2.0";
- json.Id = "qwer";
- json.Method = "aria2.getGlobalStat";
- List paramslist = new List();
- //添加下载地址
- paramslist.Add(gid);
- json.Params = paramslist;
- str = await Aria2.SendAndReceive(json);
- return str;
- }
-
-
- ///
- /// 返回由gid(字符串)表示的下载中使用的URI 。响应是一个结构数组
- ///
- ///
- ///
- public static async Task GetUris(string gid)
- {
- string str = "";
- var json = new JsonClass();
- json.Jsonrpc = "2.0";
- json.Id = "qwer";
- json.Method = "aria2.getUris";
- List paramslist = new List();
- //添加下载地址
- paramslist.Add(gid);
- json.Params = paramslist;
- str = await Aria2.SendAndReceive(json);
- return str;
- }
-
-
- ///
- /// 返回由gid(字符串)表示的下载文件列表
- ///
- ///
- ///
- public static async Task GetFiles(string gid)
- {
- string str = "";
- var json = new JsonClass();
- json.Jsonrpc = "2.0";
- json.Id = "qwer";
- json.Method = "aria2.getFiles";
- List paramslist = new List();
- //添加下载地址
- paramslist.Add(gid);
- json.Params = paramslist;
- str = await Aria2.SendAndReceive(json);
- return str;
- }
-
- }
-}
diff --git a/src/Core/aria2cNet/client/AriaClientWebSocket.cs b/src/Core/aria2cNet/client/AriaClientWebSocket.cs
deleted file mode 100644
index 71e88e8..0000000
--- a/src/Core/aria2cNet/client/AriaClientWebSocket.cs
+++ /dev/null
@@ -1,111 +0,0 @@
-using Core.aria2cNet.client.entity;
-using Newtonsoft.Json;
-using System;
-using System.Collections.Generic;
-using System.Net.WebSockets;
-using System.Text;
-using System.Threading;
-using System.Threading.Tasks;
-
-namespace Core.aria2cNet.client
-{
- public class AriaClientWebSocket
- {
- private static readonly string JSONRPC = "2.0";
- private static readonly string TOKEN = "downkyi";
-
- public static ClientWebSocket webSocket; // 用于连接到Aria2Rpc的客户端
- public static CancellationToken cancellationToken; // 传播有关应取消操作的通知
- public static bool Status; // 储存连接状态
-
- ///
- /// 连接Aria2Rpc服务器
- ///
- ///
- ///
- public static async Task ConnectServerAsync(string uri)
- {
- webSocket = new ClientWebSocket(); // 用于连接到Aria2Rpc的客户端
- cancellationToken = new CancellationToken(); // 传播有关应取消操作的通知
- Status = false; // 储存连接状态
-
- try
- {
- //连接服务器
- await webSocket.ConnectAsync(new Uri(uri), cancellationToken);
- }
- catch
- {
- Status = false;
- }
- //检查连接是否成功
- if (webSocket.State == WebSocketState.Open)
- {
- Status = true;
- }
- return Status;
- }
-
- ///
- /// add
- ///
- ///
- ///
- public static async Task AddUriAsync(List uris)
- {
- AriaSendOption option = new AriaSendOption
- {
- Out = "index测试.html",
- Dir = "home/"
- };
-
- List