ModNet.vb 93 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983
  1. Imports System.Net.Http.Headers
  2. Imports System.Net.Sockets
  3. Imports System.Runtime.CompilerServices
  4. Imports System.Threading.Tasks
  5. Public Module ModNet
  6. #Region "网络请求"
  7. ''' <summary>
  8. ''' 发送一次网络请求并获取返回内容。
  9. ''' </summary>
  10. Public Function NetRequestByClient(Url As String, Optional Method As HttpMethod = Nothing,
  11. Optional Content As Object = Nothing, Optional ContentType As String = Nothing, Optional Accept As String = "*/*",
  12. Optional Timeout As Integer = 25000, Optional Headers As String(,) = Nothing, Optional RequireJson As Boolean = False,
  13. Optional Encoding As Encoding = Nothing, Optional SimulateBrowserHeaders As Boolean = False, Optional MakeLog As Boolean = True) As String
  14. If Method Is Nothing Then Method = HttpMethod.Get
  15. If MakeLog Then Log("[Net] 发起网络请求(" & Method.Method & "," & Url & "),最大超时 " & Timeout)
  16. Try
  17. Dim HeaderDictionary = If(Headers, {}).ToDictionary
  18. If ContentType IsNot Nothing Then HeaderDictionary("Content-Type") = ContentType
  19. If Accept IsNot Nothing Then HeaderDictionary("Accept") = Accept
  20. Dim Result = If(Encoding, Encoding.UTF8).GetString(SendRequest(Url, Method, Content, HeaderDictionary, Timeout:=Timeout, Encoding:=Encoding, SimulateBrowserHeaders:=SimulateBrowserHeaders))
  21. '检查结果是否为完整 JSON(在 #6683 中可能返回空,在被 GFW 截断时可能不完整)
  22. '在此处检查并报错,可以让 NetRequestByClientRetry 等方法进行重试
  23. If RequireJson Then
  24. Result = Result.Trim((vbCrLf & " ").ToCharArray) 'Authlib-Injector 的结果会在末尾附带一个空行
  25. If Not (Result.StartsWithF("{") AndAlso Result.EndsWithF("}")) AndAlso
  26. Not (Result.StartsWithF("[") AndAlso Result.EndsWithF("]")) Then
  27. Throw New FormatException("返回结果并非 JSON 格式:" &
  28. If(Result.Length > 2000, Result.Substring(0, 1000) & "..." & Result.Substring(Result.Length - 1000), Result))
  29. End If
  30. End If
  31. Return Result
  32. Catch ex As FormatException
  33. Throw
  34. Catch ex As ThreadInterruptedException
  35. Throw
  36. Catch ex As Exception
  37. If MakeLog Then Log(ex, "网络请求失败", LogLevel.Developer)
  38. Throw
  39. End Try
  40. End Function
  41. ''' <summary>
  42. ''' 发送网络请求并获取返回内容。
  43. ''' 会进行至多 45 秒 3 次的尝试,允许最长 30s 的超时。
  44. ''' </summary>
  45. ''' <param name="BackupUrl">如果第一次尝试失败,换用的备用 URL。</param>
  46. Public Function NetRequestByClientRetry(Url As String, Optional Method As HttpMethod = Nothing, Optional BackupUrl As String = Nothing,
  47. Optional Content As Object = Nothing, Optional ContentType As String = Nothing, Optional Accept As String = "*/*",
  48. Optional Headers As String(,) = Nothing, Optional RequireJson As Boolean = False,
  49. Optional Encoding As Encoding = Nothing, Optional SimulateBrowserHeaders As Boolean = False) As String
  50. Dim RetryCount As Integer = 0
  51. Dim RetryException As Exception = Nothing
  52. Dim StartTime As Long = GetTimeTick()
  53. Try
  54. Retry:
  55. Select Case RetryCount
  56. Case 0 '正常尝试
  57. Return NetRequestByClient(Url, Method, Content, ContentType, Accept, 10000, Headers, RequireJson, Encoding, SimulateBrowserHeaders)
  58. Case 1 '慢速重试
  59. Thread.Sleep(500)
  60. Return NetRequestByClient(Url, Method, Content, ContentType, Accept, 30000, Headers, RequireJson, Encoding, SimulateBrowserHeaders)
  61. Case Else '快速重试
  62. If GetTimeTick() - StartTime > 5500 Then
  63. '若前两次加载耗费 5 秒以上,才进行重试
  64. Thread.Sleep(500)
  65. Return NetRequestByClient(Url, Method, Content, ContentType, Accept, 4000, Headers, RequireJson, Encoding, SimulateBrowserHeaders)
  66. Else
  67. Throw RetryException
  68. End If
  69. End Select
  70. Catch ex As ThreadInterruptedException
  71. Throw
  72. Catch ex As Exception
  73. If TypeOf ex Is ResponsedWebException Then
  74. If CType(ex, ResponsedWebException).StatusCode = HttpStatusCode.Forbidden Then Throw
  75. If CType(ex, ResponsedWebException).StatusCode = 429 Then Thread.Sleep(10000) 'Too Many Requests
  76. End If
  77. '重试
  78. Select Case RetryCount
  79. Case 0
  80. RetryException = ex
  81. RetryCount += 1
  82. GoTo Retry
  83. Case 1
  84. RetryCount += 1
  85. GoTo Retry
  86. Case Else
  87. Throw
  88. End Select
  89. End Try
  90. End Function
  91. ''' <summary>
  92. ''' 生成数个线程,同时发送网络请求并获取返回内容。
  93. ''' 每个线程开始之前会略有延迟。
  94. ''' </summary>
  95. Public Function NetRequestByClientMultiple(Url As String, Optional Method As HttpMethod = Nothing, Optional ThreadCount As Integer = 3,
  96. Optional Content As Object = Nothing, Optional ContentType As String = Nothing, Optional Accept As String = "*/*",
  97. Optional Headers As String(,) = Nothing, Optional RequireJson As Boolean = False, Optional Timeout As Integer = 25000,
  98. Optional Encoding As Encoding = Nothing, Optional SimulateBrowserHeaders As Boolean = False) As String
  99. Dim Threads As New List(Of Thread)
  100. Dim RequestResult = Nothing
  101. Dim RequestEx As Exception = Nothing
  102. Dim FailCount As Integer = 0
  103. For i = 1 To ThreadCount
  104. Dim th As New Thread(
  105. Sub()
  106. Try
  107. RequestResult = NetRequestByClient(Url, Method, Content, ContentType, Accept, Timeout, Headers, RequireJson, Encoding, SimulateBrowserHeaders)
  108. Catch ex As Exception
  109. FailCount += 1
  110. RequestEx = ex
  111. End Try
  112. End Sub)
  113. th.Start()
  114. Threads.Add(th)
  115. Thread.Sleep(i * 250)
  116. If RequestResult IsNot Nothing Then GoTo RequestFinished
  117. Next
  118. Do While True
  119. If RequestResult IsNot Nothing Then
  120. RequestFinished:
  121. Try
  122. For Each th In Threads
  123. If th.IsAlive Then th.Interrupt()
  124. Next
  125. Catch
  126. End Try
  127. Return RequestResult
  128. ElseIf FailCount = ThreadCount Then
  129. Try
  130. For Each th In Threads
  131. If th.IsAlive Then th.Interrupt()
  132. Next
  133. Catch
  134. End Try
  135. Throw RequestEx
  136. End If
  137. Thread.Sleep(20)
  138. Loop
  139. Return Nothing
  140. End Function
  141. ''' <summary>
  142. ''' 以多线程下载网页文件的方式获取内容。
  143. ''' 不支持缓存协商;若需缓存协商,需要换用 NetRequestByClient。
  144. ''' </summary>
  145. Public Function NetRequestByLoader(Url As String, Optional Timeout As Integer = 45000, Optional IsJson As Boolean = False, Optional SimulateBrowserHeaders As Boolean = False) As String
  146. Return NetRequestByLoader({Url}, Timeout, IsJson, SimulateBrowserHeaders)
  147. End Function
  148. ''' <summary>
  149. ''' 以多线程下载网页文件的方式获取内容。
  150. ''' 不支持缓存协商;若需缓存协商,需要换用 NetRequestByClient。
  151. ''' </summary>
  152. Public Function NetRequestByLoader(Urls As IEnumerable(Of String), Optional Timeout As Integer = 45000, Optional IsJson As Boolean = False, Optional SimulateBrowserHeaders As Boolean = False) As String
  153. Dim Temp As String = RequestTaskTempFolder() & "download.txt"
  154. Dim NewTask As New LoaderDownload("源码获取 " & GetUuid() & "#", New List(Of NetFile) From {New NetFile(Urls, Temp, New FileChecker With {.IsJson = IsJson}, SimulateBrowserHeaders)})
  155. Try
  156. NewTask.WaitForExitTime(Timeout, TimeoutMessage:="连接服务器超时(第一下载源:" & Urls.First & ")")
  157. NetRequestByLoader = ReadFile(Temp)
  158. File.Delete(Temp)
  159. Finally
  160. NewTask.Abort()
  161. End Try
  162. End Function
  163. #End Region
  164. #Region "文件下载"
  165. ''' <summary>
  166. ''' 通过网络请求直接下载小文件,若文件已存在将被覆盖。
  167. ''' 不建议用于下载大文件。
  168. ''' </summary>
  169. Public Sub NetDownloadByClient(Url As String, LocalPath As String, Optional SimulateBrowserHeaders As Boolean = False)
  170. Log($"[Net] 通过网络请求直接下载小文件:{Url} → {LocalPath}")
  171. '初始化文件路径
  172. Try
  173. Directory.CreateDirectory(GetPathFromFullPath(LocalPath))
  174. File.Delete(LocalPath)
  175. Catch ex As Exception
  176. Throw New Exception($"预处理下载文件路径失败({LocalPath})", ex)
  177. End Try
  178. '下载
  179. Try
  180. File.WriteAllBytes(LocalPath, SendRequest(Url, HttpMethod.Get, SimulateBrowserHeaders:=SimulateBrowserHeaders))
  181. Catch ex As Exception
  182. File.Delete(LocalPath)
  183. Throw New WebException($"通过网络请求直接下载小文件失败({LocalPath})", ex)
  184. End Try
  185. End Sub
  186. ''' <summary>
  187. ''' 通过多线程下载引擎下载文件。
  188. ''' </summary>
  189. Public Sub NetDownloadByLoader(Url As String, LocalPath As String, Optional LoaderToSyncProgress As LoaderBase = Nothing, Optional Check As FileChecker = Nothing, Optional SimulateBrowserHeaders As Boolean = False)
  190. NetDownloadByLoader({Url}, LocalPath, LoaderToSyncProgress, Check, SimulateBrowserHeaders)
  191. End Sub
  192. ''' <summary>
  193. ''' 通过多线程下载引擎下载文件。
  194. ''' </summary>
  195. ''' <param name="Urls">文件的 Url 列表。</param>
  196. ''' <param name="LocalPath">下载的本地地址。</param>
  197. Public Sub NetDownloadByLoader(Urls As IEnumerable(Of String), LocalPath As String, Optional LoaderToSyncProgress As LoaderBase = Nothing, Optional Check As FileChecker = Nothing, Optional SimulateBrowserHeaders As Boolean = False)
  198. Dim NewTask As New LoaderDownload($"文件下载 {GetUuid()}#", New List(Of NetFile) From {New NetFile(Urls, LocalPath, Check, SimulateBrowserHeaders)})
  199. Try
  200. NewTask.WaitForExit(LoaderToSyncProgress:=LoaderToSyncProgress)
  201. Catch ex As Exception
  202. Throw New WebException($"多线程直接下载文件失败(第一下载源:" & Urls.First() & ")", ex)
  203. Finally
  204. NewTask.Abort()
  205. End Try
  206. End Sub
  207. #End Region
  208. #Region "基础请求引擎"
  209. '基础请求函数
  210. Private Function SendRequest(Url As String, Method As HttpMethod,
  211. Optional Content As Object = Nothing, Optional Headers As Dictionary(Of String, String) = Nothing,
  212. Optional SimulateBrowserHeaders As Boolean = False, Optional Timeout As Integer = 25000, Optional Encoding As Encoding = Nothing) As Byte()
  213. If RunInUi() AndAlso Not Url.Contains("//127.") Then Throw New Exception("在 UI 线程执行了网络请求")
  214. Dim Request As HttpRequestMessage = Nothing, CancelToken As CancellationTokenSource = Nothing,
  215. Response As HttpResponseMessage = Nothing, HostIp As String = Nothing
  216. Try
  217. Url = SecretCdnSign(Url)
  218. Request = New HttpRequestMessage(Method, Url)
  219. '写入 Content
  220. If Content IsNot Nothing AndAlso Request.Method <> HttpMethod.Get AndAlso Request.Method <> HttpMethod.Head Then
  221. If TypeOf Content Is HttpContent Then
  222. Request.Content = DirectCast(Content, HttpContent)
  223. ElseIf TypeOf Content Is Byte() Then
  224. Request.Content = New ByteArrayContent(DirectCast(Content, Byte()))
  225. ElseIf Content IsNot Nothing Then
  226. Request.Content = New ByteArrayContent(If(Encoding, Encoding.UTF8).GetBytes(Content.ToString()))
  227. End If
  228. End If
  229. '写入 Headers
  230. For Each Header In If(Headers, New Dictionary(Of String, String))
  231. If Header.Key.ToLower = "content-type" Then
  232. Request.Content?.Headers.TryAddWithoutValidation(Header.Key, Header.Value)
  233. Else
  234. Request.Headers.Add(Header.Key, Header.Value)
  235. End If
  236. Next
  237. SecretHeadersSign(Url, Request, SimulateBrowserHeaders)
  238. 'DNS 解析
  239. CancelToken = New CancellationTokenSource(Timeout)
  240. HostIp = DNSLookup(Request, CancelToken)
  241. If HostIp IsNot Nothing AndAlso Not IPReliability.ContainsKey(HostIp) Then
  242. IPReliability(HostIp) = -0.01 '预先降低一点,这样快速的重复请求会使用不同的 IP 以提高成功率
  243. End If
  244. '发送请求
  245. SyncLock RequestClientLock
  246. '延迟初始化,以避免在程序启动前加载 CacheCow 导致 DLL 加载失败
  247. If RequestClient Is Nothing Then
  248. RequestClient = CacheCow.Client.ClientExtensions.CreateClient(New CacheCow.Client.FileCacheStore.FileStore(PathTemp & "Cache/Http/"), New HttpClientHandler With {
  249. .AutomaticDecompression = DecompressionMethods.Deflate Or DecompressionMethods.GZip Or DecompressionMethods.None,
  250. .UseCookies = False '不设为 False 就不能从 Header 手动传入 Cookies
  251. })
  252. End If
  253. End SyncLock
  254. Response = RequestClient.SendAsync(Request, HttpCompletionOption.ResponseHeadersRead, CancelToken.Token).GetAwaiter().GetResult()
  255. Dim ResponseStream = Response.Content.ReadAsStreamAsync().GetAwaiter().GetResult()
  256. Dim ResponseBytes As Byte()
  257. Using Stream As New MemoryStream
  258. ResponseStream.CopyToAsync(Stream, 81920, CancelToken.Token).GetAwaiter().GetResult()
  259. ResponseBytes = Stream.ToArray()
  260. End Using
  261. '输出
  262. If Response.IsSuccessStatusCode Then
  263. RecordIPReliability(HostIp, 0.5)
  264. Return ResponseBytes
  265. Else
  266. RecordIPReliability(HostIp, -0.7)
  267. Dim ResponseMessage = If(Encoding, Encoding.UTF8).GetString(ResponseBytes)
  268. Throw New ResponsedWebException(
  269. $"错误码 {Response.StatusCode} ({CInt(Response.StatusCode)}),{Method},{Url},{HostIp}" &
  270. If(String.IsNullOrEmpty(ResponseMessage), "", vbCrLf & ResponseMessage), Response.StatusCode, ResponseMessage)
  271. End If
  272. Catch ex As ThreadInterruptedException
  273. Throw
  274. Catch ex As ResponsedWebException
  275. Throw
  276. Catch ex As Exception
  277. RecordIPReliability(HostIp, -1)
  278. If TypeOf ex Is OperationCanceledException Then 'CancellationToken 超时
  279. Throw New WebException($"连接服务器超时,请稍后再试,或使用 VPN 改善网络环境({Method}, {Url},IP:{HostIp})", WebExceptionStatus.Timeout)
  280. ElseIf ex.IsNetworkRelated Then
  281. Throw New WebException($"网络请求失败,请稍后再试,或使用 VPN 改善网络环境({Method}, {Url},IP:{HostIp})", WebExceptionStatus.Timeout)
  282. Else
  283. Throw New Exception($"网络请求出现意外异常({Method}, {Url},{HostIp})", ex)
  284. End If
  285. Finally
  286. Request?.Dispose()
  287. CancelToken?.Dispose()
  288. Response?.Dispose()
  289. End Try
  290. End Function
  291. Private RequestClient As HttpClient = Nothing
  292. Private RequestClientLock As New Object
  293. ''' <summary>
  294. ''' 进行 DNS 解析。它仅在选择的 IP 与系统默认的不一致时才对 URL 中的 Host 进行替换。
  295. ''' 返回请求时应使用的 IP;若为 IPv6,则加上了方括号。
  296. ''' 若解析失败,则返回 Nothing。
  297. ''' </summary>
  298. Private Function DNSLookup(Request As HttpRequestMessage, CancelToken As CancellationTokenSource) As String
  299. Dim GetIPReliability = Function(Key) IPReliability.GetOrDefault(Key.ToString, 0)
  300. '初步 DNS 解析
  301. Dim Host = Request.RequestUri.Host
  302. Dim DnsTask As Task(Of IPAddress()) = Nothing
  303. Try
  304. DnsTask = Dns.GetHostAddressesAsync(Host)
  305. DnsTask.Wait(CancelToken.Token)
  306. Catch ex As Exception
  307. Log(ex, $"DNS 解析失败({Host})")
  308. Return Nothing
  309. End Try
  310. Dim Candidates As IPAddress() = DnsTask.Result.ToArray
  311. If Not Candidates.Any Then
  312. Log($"[Net] DNS 解析无结果({Host})")
  313. Return Nothing
  314. End If
  315. '若同时存在 IPv4 和 IPv6 地址,仅选择其中一类(因为 GFW 可能只屏蔽了 IPv4 或 IPv6)
  316. Dim IPv4Targets = Candidates.Where(Function(i) i.AddressFamily = AddressFamily.InterNetwork).ToArray
  317. Dim IPv6Targets = Candidates.Where(Function(i) i.AddressFamily = AddressFamily.InterNetworkV6).ToArray
  318. If IPv4Targets.Any AndAlso IPv6Targets.Any Then
  319. Dim IPv4Reliability = IPv4Targets.Average(Function(i) GetIPReliability(i))
  320. Dim IPv6Reliability = IPv6Targets.Average(Function(i) GetIPReliability(i))
  321. If Host = "api.modrinth.com" Then IPv6Reliability -= 0.1 '让 Modrinth 优先使用 IPv4 地址(#6887)
  322. Candidates = If(IPv4Reliability >= IPv6Reliability, IPv4Targets, IPv6Targets)
  323. End If
  324. '选择可靠度最高的 IP
  325. Dim MaxReliability As Double = Candidates.Max(Function(i) GetIPReliability(i))
  326. Dim Target As IPAddress = Candidates.First(Function(i) GetIPReliability(i) = MaxReliability)
  327. Dim TargetIp As String = If(Target.AddressFamily = AddressFamily.InterNetworkV6, $"[{Target}]", Target.ToString)
  328. If Target IsNot Candidates.First Then
  329. '优选结果与系统默认 IP 不一致,替换域名并设置 Host 头
  330. If ModeDebug Then Log($"[Net] DNS 解析结果:{Host} → {Target},所有可能的 IP 与可靠度:{DnsTask.Result.Select(Function(i) $"{i} → {GetIPReliability(i):0.000}").Join(";")}")
  331. Request.Headers.Host = Host
  332. Dim Builder As New UriBuilder(Request.RequestUri)
  333. Builder.Host = TargetIp
  334. Request.RequestUri = Builder.Uri
  335. End If
  336. Return TargetIp
  337. End Function
  338. ''' <summary>
  339. ''' 记录每个 IP 地址的请求可靠度。
  340. ''' 通常取值 -1 ~ +0.5,越高越好。未尝试过的 IP 应视为 0。
  341. ''' </summary>
  342. Private IPReliability As New SafeDictionary(Of String, Double)
  343. ''' <summary>
  344. ''' 根据请求结果,记录 IP 地址的可靠度。
  345. ''' </summary>
  346. Private Sub RecordIPReliability(IP As String, Result As Double)
  347. If IP Is Nothing Then Return
  348. If Not IPReliability.ContainsKey(IP) Then IPReliability(IP) = 0
  349. IPReliability(IP) = (IPReliability(IP) + Result) / 2
  350. End Sub
  351. ''' <summary>
  352. ''' 当 HTTP 状态码不指示成功时引发的异常。
  353. ''' 附带额外属性,可用于获取远程服务器给予的回复以及 HTTP 状态码。
  354. ''' </summary>
  355. Public Class ResponsedWebException
  356. Inherits WebException
  357. ''' <summary>
  358. ''' HTTP 状态码。
  359. ''' </summary>
  360. Public StatusCode As HttpStatusCode
  361. ''' <summary>
  362. ''' 远程服务器给予的回复。
  363. ''' </summary>
  364. Public Overloads Property Response As String
  365. Public Sub New(Message As String, StatusCode As HttpStatusCode, Response As String)
  366. MyBase.New(Message)
  367. Me.StatusCode = StatusCode
  368. Me.Response = Response
  369. End Sub
  370. End Class
  371. #End Region
  372. #Region "多线程下载引擎"
  373. Private ThreadClient As New HttpClient(New HttpClientHandler With {
  374. .AutomaticDecompression = DecompressionMethods.Deflate Or DecompressionMethods.GZip Or DecompressionMethods.None
  375. })
  376. ''' <summary>
  377. ''' 最大线程数。
  378. ''' </summary>
  379. Public NetTaskThreadLimit As Integer
  380. ''' <summary>
  381. ''' 速度下限。
  382. ''' </summary>
  383. Public NetTaskSpeedLimitLow As Long = 256 * 1024L '256K/s
  384. ''' <summary>
  385. ''' 速度上限。若无限制则为 -1。
  386. ''' </summary>
  387. Public NetTaskSpeedLimitHigh As Long = -1
  388. ''' <summary>
  389. ''' 基于限速,当前可以下载的剩余量。
  390. ''' </summary>
  391. Public NetTaskSpeedLimitLeft As Long = -1
  392. Private ReadOnly NetTaskSpeedLimitLeftLock As New Object
  393. Private NetTaskSpeedLimitLeftLast As Long
  394. ''' <summary>
  395. ''' 正在运行中的线程数。
  396. ''' </summary>
  397. Public NetTaskThreadCount As Integer = 0
  398. Private ReadOnly NetTaskThreadCountLock As New Object
  399. ''' <summary>
  400. ''' 下载源。
  401. ''' </summary>
  402. Public Class NetSource
  403. Public Id As Integer
  404. Public Url As String
  405. Public FailCount As Integer
  406. Public Ex As Exception
  407. ''' <summary>
  408. ''' 若该下载源正在进行强制单线程下载,标记这个唯一的线程。
  409. ''' </summary>
  410. Public SingleThread As NetThread
  411. Public IsFailed As Boolean
  412. Public Overrides Function ToString() As String
  413. Return Url
  414. End Function
  415. End Class
  416. ''' <summary>
  417. ''' 下载进度标示。
  418. ''' </summary>
  419. Public Enum NetState
  420. ''' <summary>
  421. ''' 尚未进行已存在检查。
  422. ''' </summary>
  423. WaitForCheck = -1
  424. ''' <summary>
  425. ''' 尚未开始。
  426. ''' </summary>
  427. WaitForDownload = 0
  428. ''' <summary>
  429. ''' 正在连接,尚未获取文件大小。
  430. ''' </summary>
  431. Connect = 1
  432. ''' <summary>
  433. ''' 已获取文件大小,尚未有有效下载。
  434. ''' </summary>
  435. [Get] = 2
  436. ''' <summary>
  437. ''' 正在下载。
  438. ''' </summary>
  439. Download = 3
  440. ''' <summary>
  441. ''' 正在合并文件。
  442. ''' </summary>
  443. Merge = 4
  444. ''' <summary>
  445. ''' 不进行下载,因为已发现现存的文件。
  446. ''' </summary>
  447. WaitForCopy = 5
  448. ''' <summary>
  449. ''' 已完成。
  450. ''' </summary>
  451. Finish = 6
  452. ''' <summary>
  453. ''' 已失败或中断。
  454. ''' </summary>
  455. [Error] = 7
  456. End Enum
  457. ''' <summary>
  458. ''' 预下载检查行为。
  459. ''' </summary>
  460. Public Enum NetPreDownloadBehaviour
  461. ''' <summary>
  462. ''' 当文件已存在时,显示提示以提醒用户是否继续下载。
  463. ''' </summary>
  464. HintWhileExists
  465. ''' <summary>
  466. ''' 当文件已存在或正在下载时,直接退出下载函数执行,不对用户进行提示。
  467. ''' </summary>
  468. ExitWhileExistsOrDownloading
  469. ''' <summary>
  470. ''' 不进行已存在检查。
  471. ''' </summary>
  472. IgnoreCheck
  473. End Enum
  474. ''' <summary>
  475. ''' 下载线程。
  476. ''' </summary>
  477. Public Class NetThread
  478. Implements IEnumerable(Of NetThread), IEquatable(Of NetThread)
  479. ''' <summary>
  480. ''' 对应的下载任务。
  481. ''' </summary>
  482. Public Task As NetFile
  483. ''' <summary>
  484. ''' 对应的线程。
  485. ''' </summary>
  486. Public Thread As Thread
  487. ''' <summary>
  488. ''' 链表中的下一个线程。
  489. ''' </summary>
  490. Public NextThread As NetThread
  491. Private ReadOnly Iterator Property [Next]() As IEnumerable(Of NetThread)
  492. Get
  493. Dim CurrentChain As NetThread = Me
  494. While CurrentChain IsNot Nothing
  495. Yield CurrentChain
  496. CurrentChain = CurrentChain.NextThread
  497. End While
  498. End Get
  499. End Property
  500. Public Function GetEnumerator() As IEnumerator(Of NetThread) Implements IEnumerable(Of NetThread).GetEnumerator
  501. Return [Next].GetEnumerator()
  502. End Function
  503. Private Function IEnumerable_GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator
  504. Return [Next].GetEnumerator()
  505. End Function
  506. ''' <summary>
  507. ''' 分配给任务中每个线程(无论其是否失败)的编号。
  508. ''' </summary>
  509. Public Uuid As Integer
  510. ''' <summary>
  511. ''' 是否为第一个线程。
  512. ''' </summary>
  513. Public ReadOnly Property IsFirstThread As Boolean
  514. Get
  515. Return DownloadStart = 0 AndAlso Task.FileSize = -2
  516. End Get
  517. End Property
  518. ''' <summary>
  519. ''' 该线程的缓存文件。
  520. ''' </summary>
  521. Public Temp As String
  522. ''' <summary>
  523. ''' 线程下载起始位置。
  524. ''' </summary>
  525. Public DownloadStart As Long
  526. ''' <summary>
  527. ''' 线程下载结束位置。
  528. ''' </summary>
  529. Public ReadOnly Property DownloadEnd As Long
  530. Get
  531. SyncLock Task.LockChain
  532. If NextThread Is Nothing Then
  533. If Task.IsUnknownSize Then
  534. Return 1000 * 1000 * 1000 * 1000L '约 1T
  535. Else
  536. Return Task.FileSize - 1
  537. End If
  538. Else
  539. Return NextThread.DownloadStart - 1
  540. End If
  541. End SyncLock
  542. End Get
  543. End Property
  544. ''' <summary>
  545. ''' 线程未下载的文件大小。
  546. ''' </summary>
  547. Public ReadOnly Property DownloadUndone As Long
  548. Get
  549. Return DownloadEnd - (DownloadStart + DownloadDone) + 1
  550. End Get
  551. End Property
  552. ''' <summary>
  553. ''' 线程已下载的文件大小。
  554. ''' </summary>
  555. Public DownloadDone As Long = 0
  556. ''' <summary>
  557. ''' 上次记速时的时间。
  558. ''' </summary>
  559. Private SpeedLastTime As Long = GetTimeTick()
  560. ''' <summary>
  561. ''' 上次记速时的已下载大小。
  562. ''' </summary>
  563. Private SpeedLastDone As Long = 0
  564. ''' <summary>
  565. ''' 当前的下载速度,单位为 Byte / 秒。
  566. ''' </summary>
  567. Public ReadOnly Property Speed As Long
  568. Get
  569. If GetTimeTick() - SpeedLastTime > 200 Then
  570. Dim DeltaTime As Long = GetTimeTick() - SpeedLastTime
  571. _Speed = (DownloadDone - SpeedLastDone) / (DeltaTime / 1000)
  572. SpeedLastDone = DownloadDone
  573. SpeedLastTime += DeltaTime
  574. End If
  575. Return _Speed
  576. End Get
  577. End Property
  578. Private _Speed As Long = 0
  579. ''' <summary>
  580. ''' 线程初始化时的时间。
  581. ''' </summary>
  582. Public InitTime As Long = GetTimeTick()
  583. ''' <summary>
  584. ''' 上次接受到有效数据的时间,-1 表示尚未有有效数据。
  585. ''' </summary>
  586. Public LastReceiveTime As Long = -1
  587. ''' <summary>
  588. ''' 当前线程的状态。
  589. ''' </summary>
  590. Public State As NetState = NetState.WaitForDownload
  591. ''' <summary>
  592. ''' 是否已经结束。
  593. ''' </summary>
  594. Public ReadOnly Property IsEnded As Boolean
  595. Get
  596. Return State = NetState.Finish OrElse State = NetState.Error
  597. End Get
  598. End Property
  599. ''' <summary>
  600. ''' 当前选取的是哪一个 Url。
  601. ''' </summary>
  602. Public Source As NetSource
  603. '允许进行 UUID 比较
  604. Public Overloads Function Equals(other As NetThread) As Boolean Implements IEquatable(Of NetThread).Equals
  605. Return other IsNot Nothing AndAlso Uuid = other.Uuid
  606. End Function
  607. Public Overrides Function Equals(obj As Object) As Boolean
  608. Return Equals(TryCast(obj, NetThread))
  609. End Function
  610. Public Shared Operator =(left As NetThread, right As NetThread) As Boolean
  611. Return EqualityComparer(Of NetThread).Default.Equals(left, right)
  612. End Operator
  613. Public Shared Operator <>(left As NetThread, right As NetThread) As Boolean
  614. Return Not left = right
  615. End Operator
  616. End Class
  617. ''' <summary>
  618. ''' 下载单个文件。
  619. ''' </summary>
  620. Public Class NetFile
  621. #Region "属性"
  622. ''' <summary>
  623. ''' 所属的文件列表任务。
  624. ''' </summary>
  625. Public Tasks As New SafeList(Of LoaderDownload)
  626. ''' <summary>
  627. ''' 所有下载源。
  628. ''' </summary>
  629. Public Sources As SafeList(Of NetSource)
  630. ''' <summary>
  631. ''' 用于在第一个线程出错时切换下载源。
  632. ''' </summary>
  633. Private FirstThreadSource As Integer = 0
  634. ''' <summary>
  635. ''' 所有已经被标记为失败的,但未完整尝试过的,不允许断点续传的下载源。
  636. ''' </summary>
  637. Public SourcesOnce As New SafeList(Of NetSource)
  638. ''' <summary>
  639. ''' 仅当合并失败或首次下载失败时,会将所有下载源重新标记为不允许断点续传的下载源,逐个重新尝试下载。
  640. ''' 这一策略可以兼容多个下载源中的一部分返回错误的文件的情况,以及部分在多线程下载时会抽风的源。
  641. ''' </summary>
  642. Private Retried As Boolean = False
  643. ''' <summary>
  644. ''' 获取从某个源开始,第一个可用的源。
  645. ''' </summary>
  646. Private Function GetSource(Optional Id As Integer = 0) As NetSource
  647. If Id >= Sources.Count OrElse Id < 0 Then Id = 0
  648. SyncLock LockSource
  649. If HasAvailableSource(False) Then
  650. '存在多线程可用源
  651. Dim CurrentSource As NetSource = Sources(Id)
  652. While CurrentSource.IsFailed
  653. Id += 1
  654. If Id >= Sources.Count Then Id = 0
  655. CurrentSource = Sources(Id)
  656. End While
  657. Return CurrentSource
  658. ElseIf SourcesOnce.Any Then
  659. '仅存在单线程可用源
  660. Return SourcesOnce.First
  661. Else
  662. '没有可用源
  663. Return Nothing
  664. End If
  665. End SyncLock
  666. End Function
  667. ''' <summary>
  668. ''' 是否存在可用源。
  669. ''' </summary>
  670. Public Function HasAvailableSource(Optional AllowOnceSource As Boolean = True) As Boolean
  671. SyncLock LockSource
  672. If Sources.Any(Function(s) Not s.IsFailed) Then Return True '存在多线程可用源
  673. If AllowOnceSource AndAlso SourcesOnce.Any Then Return True '存在单线程可用源
  674. End SyncLock
  675. Return False
  676. End Function
  677. ''' <summary>
  678. ''' 存储在本地的带文件名的地址。
  679. ''' </summary>
  680. Public LocalPath As String = Nothing
  681. ''' <summary>
  682. ''' 存储在本地的文件名。
  683. ''' </summary>
  684. Public LocalName As String = Nothing
  685. ''' <summary>
  686. ''' 当前的下载状态。
  687. ''' </summary>
  688. Public State As NetState = NetState.WaitForCheck
  689. ''' <summary>
  690. ''' 导致下载失败的原因。
  691. ''' </summary>
  692. Public Ex As New List(Of Exception)
  693. ''' <summary>
  694. ''' 作为文件组成部分的线程链表。
  695. ''' 如果没有线程,可以为 Nothing。
  696. ''' </summary>
  697. Public Threads As NetThread
  698. ''' <summary>
  699. ''' 文件的总大小。若为 -2 则为未获取,若为 -1 则为无法获取准确大小。
  700. ''' </summary>
  701. Public FileSize As Long = -2
  702. ''' <summary>
  703. ''' 该文件是否无法获取准确大小。
  704. ''' </summary>
  705. Public IsUnknownSize As Boolean = False
  706. ''' <summary>
  707. ''' 该文件是否不需要分割。
  708. ''' </summary>
  709. Public ReadOnly Property IsNoSplit As Boolean
  710. Get
  711. Return IsUnknownSize OrElse FileSize < FilePieceLimit
  712. End Get
  713. End Property
  714. ''' <summary>
  715. ''' 为不需要分割的小文件在内存中提供临时存储。
  716. ''' </summary>
  717. Private Cache As MemoryStream
  718. ''' <summary>
  719. ''' 文件的已下载大小。
  720. ''' </summary>
  721. Public DownloadDone As Long = 0
  722. Private ReadOnly LockDone As New Object
  723. ''' <summary>
  724. ''' 文件的校验规则。
  725. ''' </summary>
  726. Public Check As FileChecker
  727. ''' <summary>
  728. ''' 是否模拟浏览器的 UserAgent 和 Referer。
  729. ''' </summary>
  730. Public SimulateBrowserHeaders As Boolean
  731. ''' <summary>
  732. ''' 上次记速时的时间。
  733. ''' </summary>
  734. Private SpeedLastTime As Long = GetTimeTick()
  735. ''' <summary>
  736. ''' 上次记速时的已下载大小。
  737. ''' </summary>
  738. Private SpeedLastDone As Long = 0
  739. ''' <summary>
  740. ''' 当前的下载速度,单位为 Byte / 秒。
  741. ''' </summary>
  742. Public ReadOnly Property Speed As Long
  743. Get
  744. If GetTimeTick() - SpeedLastTime > 200 Then
  745. Dim DeltaTime As Long = GetTimeTick() - SpeedLastTime
  746. _Speed = (DownloadDone - SpeedLastDone) / (DeltaTime / 1000)
  747. SpeedLastDone = DownloadDone
  748. SpeedLastTime += DeltaTime
  749. End If
  750. Return _Speed
  751. End Get
  752. End Property
  753. Private _Speed As Long = 0
  754. ''' <summary>
  755. ''' 该文件是否由本地文件直接拷贝完成。
  756. ''' </summary>
  757. Public IsCopy As Boolean = False
  758. ''' <summary>
  759. ''' 本文件的显示进度。
  760. ''' </summary>
  761. Public ReadOnly Property Progress As Double
  762. Get
  763. Select Case State
  764. Case NetState.WaitForCheck
  765. Return 0
  766. Case NetState.WaitForCopy
  767. Return 0.2
  768. Case NetState.WaitForDownload
  769. Return 0.01
  770. Case NetState.Connect
  771. Return 0.02
  772. Case NetState.Get
  773. Return 0.04
  774. Case NetState.Download
  775. '正在下载中,对应 5% ~ 98%
  776. Dim OriginalProgress As Double = If(IsUnknownSize, 0.5, DownloadDone / Math.Max(FileSize, 1))
  777. OriginalProgress = 1 - (1 - OriginalProgress) ^ 0.9
  778. Return OriginalProgress * 0.93 + 0.05
  779. Case NetState.Merge
  780. Return 0.99
  781. Case NetState.Finish, NetState.Error
  782. Return 1
  783. Case Else
  784. Throw New ArgumentOutOfRangeException("文件状态未知:" & State)
  785. End Select
  786. End Get
  787. End Property
  788. ''' <summary>
  789. ''' 各个线程建立连接成功的总次数。
  790. ''' </summary>
  791. Private ConnectCount As Integer = 0
  792. ''' <summary>
  793. ''' 各个线程建立连接成功的总时间。
  794. ''' </summary>
  795. Private ConnectTime As Long = 0
  796. ''' <summary>
  797. ''' 各个线程建立连接成功的平均时间,单位为毫秒,-1 代表尚未有成功连接。
  798. ''' </summary>
  799. Private ReadOnly Property ConnectAverage As Integer
  800. Get
  801. SyncLock LockCount
  802. Return If(ConnectCount = 0, -1, ConnectTime / ConnectCount)
  803. End SyncLock
  804. End Get
  805. End Property
  806. Private Const FilePieceLimit As Long = 256 * 1024
  807. Public ReadOnly LockCount As New Object
  808. Public ReadOnly LockState As New Object
  809. Public ReadOnly LockChain As New Object
  810. Public ReadOnly LockSource As New Object
  811. Public ReadOnly Uuid As Integer = GetUuid()
  812. Public Overrides Function Equals(obj As Object) As Boolean
  813. Dim file = TryCast(obj, NetFile)
  814. Return file IsNot Nothing AndAlso Uuid = file.Uuid
  815. End Function
  816. #End Region
  817. ''' <summary>
  818. ''' 新建一个需要下载的文件。
  819. ''' </summary>
  820. ''' <param name="LocalPath">包含文件名的本地地址。</param>
  821. Public Sub New(Urls As IEnumerable(Of String), LocalPath As String, Optional Check As FileChecker = Nothing, Optional SimulateBrowserHeaders As Boolean = False)
  822. Dim Sources As New List(Of NetSource)
  823. Dim Count As Integer = 0
  824. Urls = Urls.Distinct.ToArray
  825. For Each Source As String In Urls
  826. Sources.Add(New NetSource With {.FailCount = 0, .Url = SecretCdnSign(Source.Replace(vbCr, "").Replace(vbLf, "").Trim), .Id = Count, .IsFailed = False, .Ex = Nothing})
  827. Count += 1
  828. Next
  829. Me.Sources = Sources
  830. Me.LocalPath = LocalPath
  831. Me.Check = Check
  832. Me.SimulateBrowserHeaders = SimulateBrowserHeaders
  833. Me.LocalName = GetFileNameFromPath(LocalPath)
  834. End Sub
  835. ''' <summary>
  836. ''' 尝试开始一个新的下载线程。
  837. ''' 如果失败,返回 Nothing。
  838. ''' </summary>
  839. Public Function TryBeginThread() As NetThread
  840. Try
  841. Dim StartPosition As Long, StartSource As NetSource = Nothing
  842. Dim Th As Thread, ThreadInfo As NetThread
  843. '条件检测
  844. SyncLock LockSource
  845. If NetTaskThreadCount >= NetTaskThreadLimit OrElse Not HasAvailableSource() OrElse
  846. (IsNoSplit AndAlso Threads IsNot Nothing AndAlso Threads.State <> NetState.Error) Then Return Nothing
  847. If State >= NetState.Merge OrElse State = NetState.WaitForCheck Then Return Nothing
  848. SyncLock LockState
  849. If State < NetState.Connect Then State = NetState.Connect
  850. End SyncLock
  851. '初始化参数
  852. '获取线程起点与下载源
  853. '不分割
  854. If IsNoSplit Then GoTo StartSingleThreadDownload
  855. '只剩下单线程可用点
  856. If Not HasAvailableSource(False) Then
  857. If SourcesOnce.First.SingleThread IsNot Nothing AndAlso SourcesOnce.First.SingleThread.State <> NetState.Error Then Return Nothing
  858. StartSingleThreadDownload:
  859. Reset()
  860. State = NetState.Get
  861. End If
  862. End SyncLock
  863. SyncLock LockChain
  864. '首个开始点
  865. If Threads Is Nothing Then
  866. StartPosition = 0
  867. StartSource = GetSource(FirstThreadSource)
  868. FirstThreadSource = StartSource.Id + 1
  869. GoTo StartThread
  870. End If
  871. '寻找失败点
  872. For Each Thread As NetThread In Threads
  873. If Thread.State = NetState.Error AndAlso Thread.DownloadUndone > 0 Then
  874. StartPosition = Thread.DownloadStart + Thread.DownloadDone
  875. StartSource = GetSource(Thread.Source.Id + 1)
  876. GoTo StartThread
  877. End If
  878. Next
  879. '是否禁用多线程,以及规定碎片大小
  880. Dim Source As NetSource = GetSource()
  881. If Source Is Nothing Then Return Nothing
  882. Dim TargetUrl As String = Source.Url
  883. If TargetUrl.Contains("pcl2-server") OrElse TargetUrl.Contains("bmclapi") OrElse TargetUrl.Contains("github.com") OrElse
  884. TargetUrl.Contains("optifine.net") OrElse TargetUrl.Contains("modrinth") OrElse TargetUrl.Contains("momot.rs") Then Return Nothing
  885. '寻找最大碎片
  886. 'FUTURE: 下载引擎重做,计算下载源平均链接时间和线程下载速度,按最高时间节省来开启多线程
  887. Dim FilePieceMax As NetThread = Threads
  888. For Each Thread As NetThread In Threads
  889. If Thread.DownloadUndone > FilePieceMax.DownloadUndone Then FilePieceMax = Thread
  890. Next
  891. If FilePieceMax Is Nothing OrElse FilePieceMax.DownloadUndone < FilePieceLimit Then Return Nothing
  892. StartPosition = FilePieceMax.DownloadEnd - FilePieceMax.DownloadUndone * 0.4
  893. StartSource = GetSource()
  894. '开始线程
  895. StartThread:
  896. If (StartPosition > FileSize AndAlso FileSize >= 0 AndAlso Not IsUnknownSize) OrElse StartPosition < 0 OrElse IsNothing(StartSource) Then Return Nothing
  897. '构建线程
  898. Dim ThreadUuid As Integer = GetUuid()
  899. If Not Tasks.Any() Then Return Nothing '由于中断,已没有可用任务
  900. Th = New Thread(AddressOf Thread) With {.Name = $"下载 {Tasks(0).Uuid}/{Uuid}/{ThreadUuid}#", .Priority = ThreadPriority.BelowNormal}
  901. ThreadInfo = New NetThread With {.Uuid = ThreadUuid, .DownloadStart = StartPosition, .Thread = Th, .Source = StartSource, .Task = Me, .State = NetState.WaitForDownload}
  902. '链表处理
  903. If ThreadInfo.IsFirstThread OrElse Threads Is Nothing Then
  904. Threads = ThreadInfo
  905. Else
  906. Dim CurrentChain As NetThread = Threads
  907. While CurrentChain.DownloadEnd <= StartPosition
  908. CurrentChain = CurrentChain.NextThread
  909. End While
  910. ThreadInfo.NextThread = CurrentChain.NextThread
  911. CurrentChain.NextThread = ThreadInfo
  912. End If
  913. End SyncLock
  914. '开始线程
  915. SyncLock NetTaskThreadCountLock
  916. NetTaskThreadCount += 1
  917. End SyncLock
  918. SyncLock LockSource
  919. If Not HasAvailableSource(False) Then SourcesOnce.First.SingleThread = ThreadInfo
  920. End SyncLock
  921. Th.Start(ThreadInfo)
  922. Return ThreadInfo
  923. Catch ex As Exception
  924. Fail(New Exception($"尝试开始下载线程失败({LocalName})", ex))
  925. Return Nothing
  926. End Try
  927. End Function
  928. ''' <summary>
  929. ''' 每个下载线程执行的代码。
  930. ''' </summary>
  931. Private Sub Thread(Th As NetThread)
  932. If ModeDebug OrElse Th.DownloadStart = 0 Then Log($"[Download] {LocalName}:开始,起始点 {Th.DownloadStart},{Th.Source.Url}")
  933. Dim ResultStream As Stream = Nothing, HttpRequest As HttpRequestMessage = Nothing,
  934. Response As HttpResponseMessage = Nothing, ResponseStream As Stream = Nothing,
  935. CancelToken As CancellationTokenSource = Nothing, HostIp As String = Nothing
  936. '部分下载源真的特别慢,并且只需要一个请求,例如 Ping 为 20s,如果增长太慢,就会造成类似 2.5s 5s 7.5s 10s 12.5s... 的极大延迟
  937. '延迟过长会导致某些特别慢的链接迟迟不被掐死
  938. Dim Timeout As Integer = Math.Min(Math.Max(ConnectAverage, 6000) * (1 + Th.Source.FailCount), 30000)
  939. Th.State = NetState.Connect
  940. Try
  941. Dim HttpDataCount As Integer = 0
  942. If SourcesOnce.Contains(Th.Source) AndAlso Th <> Th.Source.SingleThread Then GoTo SourceBreak
  943. HttpRequest = New HttpRequestMessage(HttpMethod.Get, Th.Source.Url)
  944. SecretHeadersSign(Th.Source.Url, HttpRequest, SimulateBrowserHeaders)
  945. CancelToken = New CancellationTokenSource(Timeout)
  946. HostIp = DNSLookup(HttpRequest, CancelToken) 'DNS 预解析
  947. If Not Th.IsFirstThread Then HttpRequest.Headers.Range = New RangeHeaderValue(Th.DownloadStart, Nothing)
  948. Dim ContentLength As Long = 0
  949. Response = ThreadClient.SendAsync(HttpRequest, HttpCompletionOption.ResponseHeadersRead, CancelToken.Token).GetAwaiter().GetResult()
  950. If Not Response.IsSuccessStatusCode Then Throw New Exception($"错误码 {Response.StatusCode} ({CInt(Response.StatusCode)}),{Th.Source.Url}") '状态码检查
  951. If State = NetState.Error Then GoTo SourceBreak '快速中断
  952. If ModeDebug AndAlso Response.RequestMessage.RequestUri.ToString <> Th.Source.Url Then Log($"[Download] {LocalName}:重定向至 {Response.RequestMessage.RequestUri}")
  953. '文件大小校验
  954. ContentLength = Response.Content.Headers.ContentLength.GetValueOrDefault(-1)
  955. If ContentLength = -1 Then
  956. If FileSize > 1 Then
  957. If Th.DownloadStart = 0 Then
  958. Log($"[Download] {LocalName}:文件大小未知,但已从其他下载源获取,不作处理")
  959. Else
  960. Log($"[Download] {LocalName}:ContentLength 返回了 -1,无法确定是否支持分段下载,视作不支持")
  961. GoTo NotSupportRange
  962. End If
  963. Else
  964. FileSize = -1 : IsUnknownSize = True
  965. Log($"[Download] {LocalName}:文件大小未知")
  966. End If
  967. ElseIf ContentLength < 0 Then
  968. Throw New Exception("获取片大小失败,结果为 " & ContentLength & "。")
  969. ElseIf Th.IsFirstThread Then
  970. If Check IsNot Nothing Then
  971. If ContentLength < Check.MinSize AndAlso Check.MinSize > 0 Then
  972. Throw New Exception($"文件大小不足,获取结果为 {ContentLength},要求至少为 {Check.MinSize}。")
  973. End If
  974. If ContentLength <> Check.ActualSize AndAlso Check.ActualSize > 0 Then
  975. Throw New Exception($"文件大小不一致,获取结果为 {ContentLength},要求必须为 {Check.ActualSize}。")
  976. End If
  977. End If
  978. FileSize = ContentLength : IsUnknownSize = False
  979. Log($"[Download] {LocalName}:文件大小 {ContentLength}({GetString(ContentLength)})")
  980. '若文件大小大于 50 M,进行剩余磁盘空间校验
  981. If ContentLength > 50 * 1024 * 1024 Then
  982. For Each Drive As DriveInfo In DriveInfo.GetDrives
  983. Dim DriveName As String = Drive.Name.First.ToString
  984. Dim RequiredSpace = If(PathTemp.StartsWithF(DriveName), ContentLength * 1.1, 0) +
  985. If(LocalPath.StartsWithF(DriveName), ContentLength + 5 * 1024 * 1024, 0)
  986. If Drive.TotalFreeSpace < RequiredSpace Then
  987. Throw New Exception(DriveName & " 盘空间不足,无法进行下载。" & vbCrLf & "需要至少 " & GetString(RequiredSpace) & " 空间,但当前仅剩余 " & GetString(Drive.TotalFreeSpace) & "。" &
  988. If(PathTemp.StartsWithF(DriveName), vbCrLf & vbCrLf & "下载时需要与文件同等大小的空间存放缓存,你可以在设置中调整缓存文件夹的位置。", ""))
  989. End If
  990. Next
  991. End If
  992. ElseIf FileSize < 0 Then
  993. Throw New Exception("非首线程运行时,尚未获取文件大小")
  994. ElseIf Th.DownloadStart > 0 AndAlso ContentLength = FileSize Then
  995. NotSupportRange:
  996. SyncLock LockSource
  997. If SourcesOnce.Contains(Th.Source) Then
  998. GoTo SourceBreak
  999. Else
  1000. SourcesOnce.Add(Th.Source)
  1001. End If
  1002. End SyncLock
  1003. Throw New WebException($"该下载源不支持分段下载:Range 起始于 {Th.DownloadStart},预期 ContentLength 为 {FileSize - Th.DownloadStart},返回 ContentLength 为 {ContentLength},总文件大小 {FileSize}")
  1004. ElseIf Not FileSize - Th.DownloadStart = ContentLength Then
  1005. Throw New WebException($"获取到的分段大小不一致:Range 起始于 {Th.DownloadStart},预期 ContentLength 为 {FileSize - Th.DownloadStart},返回 ContentLength 为 {ContentLength},总文件大小 {FileSize}")
  1006. End If
  1007. 'Log($"[Download] {LocalName} {Info.Uuid}#:通过大小检查,文件大小 {FileSize},起始点 {Info.DownloadStart},ContentLength {ContentLength}")
  1008. Th.State = NetState.Get
  1009. SyncLock LockState
  1010. If State < NetState.Get Then State = NetState.Get
  1011. End SyncLock
  1012. '创建缓存文件
  1013. If IsNoSplit Then
  1014. Th.Temp = Nothing
  1015. Cache = New MemoryStream
  1016. ResultStream = Cache
  1017. Else
  1018. Th.Temp = $"{PathTemp}Download\{Uuid}_{Th.Uuid}_{RandomInteger(0, 999999)}.tmp"
  1019. ResultStream = New FileStream(Th.Temp, FileMode.Create, FileAccess.Write, FileShare.Read)
  1020. End If
  1021. '开始下载
  1022. ResponseStream = Response.Content.ReadAsStreamAsync().GetAwaiter().GetResult()
  1023. If Setup.Get("SystemDebugDelay") Then Threading.Thread.Sleep(RandomInteger(50, 3000))
  1024. Dim ResponseBytes As Byte() = New Byte(16384) {}
  1025. HttpDataCount = ResponseStream.ReadAsync(ResponseBytes, 0, 16384, CancelToken.Token).GetAwaiter().GetResult()
  1026. While (IsUnknownSize OrElse Th.DownloadUndone > 0) AndAlso '判断是否下载完成
  1027. HttpDataCount > 0 AndAlso Not IsProgramEnded AndAlso State < NetState.Merge AndAlso (Not Th.Source.IsFailed OrElse Th.Source.SingleThread = Th)
  1028. '限速
  1029. While NetTaskSpeedLimitHigh > 0 AndAlso NetTaskSpeedLimitLeft <= 0
  1030. Threading.Thread.Sleep(16)
  1031. End While
  1032. Dim RealDataCount As Integer = If(IsUnknownSize, HttpDataCount, Math.Min(HttpDataCount, Th.DownloadUndone))
  1033. SyncLock NetTaskSpeedLimitLeftLock
  1034. If NetTaskSpeedLimitHigh > 0 Then NetTaskSpeedLimitLeft -= RealDataCount
  1035. End SyncLock
  1036. Dim DeltaTime = GetTimeTick() - Th.LastReceiveTime
  1037. If DeltaTime > 1000000 Then DeltaTime = 1 '避免时间刻反转导致出现极大值
  1038. If RealDataCount > 0 Then
  1039. '有数据
  1040. If Th.DownloadDone = 0 Then
  1041. '第一次接受到数据
  1042. Th.State = NetState.Download
  1043. SyncLock LockState
  1044. If State < NetState.Download Then State = NetState.Download
  1045. End SyncLock
  1046. SyncLock LockCount
  1047. ConnectCount += 1
  1048. ConnectTime += GetTimeTick() - Th.InitTime
  1049. End SyncLock
  1050. End If
  1051. SyncLock LockCount
  1052. Th.Source.FailCount = 0
  1053. For Each Task In Tasks
  1054. Task.FailCount = 0
  1055. Next
  1056. End SyncLock
  1057. NetManager.DownloadDone += RealDataCount
  1058. SyncLock LockDone
  1059. DownloadDone += RealDataCount
  1060. End SyncLock
  1061. Th.DownloadDone += RealDataCount
  1062. ResultStream.Write(ResponseBytes, 0, RealDataCount)
  1063. '已完成
  1064. If Th.DownloadUndone = 0 AndAlso Not IsUnknownSize Then Exit While
  1065. '检查速度是否过慢
  1066. If DeltaTime > 5000 AndAlso DeltaTime > RealDataCount AndAlso '数据包间隔大于 5s,且速度小于 1K/s
  1067. Th.Source.SingleThread Is Nothing Then '且并非单线程下载
  1068. Throw New TimeoutException("由于速度过慢断开链接,下载 " & RealDataCount & " B,消耗 " & DeltaTime & " ms。")
  1069. End If
  1070. Th.LastReceiveTime = GetTimeTick()
  1071. ElseIf Th.LastReceiveTime > 0 AndAlso DeltaTime > Timeout Then
  1072. '无数据,且已超时
  1073. Throw New TimeoutException("操作超时,无数据。")
  1074. End If
  1075. HttpDataCount = ResponseStream.Read(ResponseBytes, 0, 16384)
  1076. End While
  1077. SourceBreak:
  1078. If State = NetState.Error OrElse (Th.Source.IsFailed AndAlso Th.Source.SingleThread <> Th) OrElse (Th.DownloadUndone > 0 AndAlso Not IsUnknownSize) Then
  1079. '被外部中断
  1080. Th.State = NetState.Error
  1081. Log($"[Download] {LocalName}:中断")
  1082. ElseIf HttpDataCount = 0 AndAlso Th.DownloadUndone > 0 AndAlso Not IsUnknownSize Then
  1083. '服务器无返回数据
  1084. Throw New Exception($"返回的 ContentLength 过多:ContentLength 为 {ContentLength},但获取到的总数据量仅为 {Th.DownloadDone}(全文件总数据量 {DownloadDone})")
  1085. Else
  1086. '本线程完成
  1087. Th.State = NetState.Finish
  1088. If ModeDebug Then Log($"[Download] {LocalName}:完成,已下载 {Th.DownloadDone}({Th.DownloadStart}~{Th.DownloadEnd})")
  1089. RecordIPReliability(HostIp, 0.5)
  1090. End If
  1091. Catch ex As Exception
  1092. Log($"[Download] {LocalName}:出错,{If(TypeOf ex Is OperationCanceledException, $"已超时({Timeout}ms)", ex.GetDetail())},IP:{HostIp}")
  1093. RecordIPReliability(HostIp, -0.7)
  1094. SourceFail(Th, ex, False)
  1095. Finally
  1096. '释放资源
  1097. HttpRequest?.Dispose()
  1098. Response?.Dispose()
  1099. ResponseStream?.Dispose()
  1100. CancelToken?.Dispose()
  1101. If Not IsNoSplit Then ResultStream?.Dispose()
  1102. '改变计数
  1103. SyncLock NetTaskThreadCountLock
  1104. NetTaskThreadCount -= 1
  1105. End SyncLock
  1106. '合并
  1107. If ((FileSize >= 0 AndAlso DownloadDone >= FileSize) OrElse (FileSize = -1 AndAlso DownloadDone > 0)) AndAlso
  1108. State < NetState.Merge AndAlso Th.State <> NetState.Error Then Merge(Th)
  1109. End Try
  1110. End Sub
  1111. Private Sub SourceFail(Th As NetThread, ex As Exception, IsMergeFailure As Boolean)
  1112. '状态变更
  1113. SyncLock LockCount
  1114. Th.Source.FailCount += 1
  1115. For Each Task In Tasks
  1116. Task.FailCount += 1
  1117. Next
  1118. End SyncLock
  1119. Th.State = NetState.Error
  1120. Th.Source.Ex = ex
  1121. '根据情况判断,是否在多线程下禁用下载源(连续错误过多,或不支持断点续传)
  1122. If IsMergeFailure OrElse
  1123. ex.Message.Contains("该下载源不支持") OrElse ex.Message.Contains("未能解析") OrElse ex.Message.Contains("(404)") OrElse
  1124. ex.Message.Contains("(502)") OrElse ex.Message.Contains("无返回数据") OrElse ex.Message.Contains("空间不足") OrElse ex.Message.Contains("获取到的分段大小不一致") OrElse
  1125. ((ex.Message.Contains("(403)") OrElse ex.Message.Contains("(429)")) AndAlso Not Th.Source.Url.ContainsF("bmclapi")) OrElse 'BMCLAPI 的部分源在高频率请求下会返回 403/429,所以不应因此禁用下载源
  1126. (Th.Source.FailCount >= MathClamp(NetTaskThreadLimit, 5, 30) AndAlso DownloadDone < 1) OrElse Th.Source.FailCount > NetTaskThreadLimit + 2 Then
  1127. '当一个下载源有多个线程在下载时,只选择其中一个线程进行后续处理
  1128. Dim IsThisFail As Boolean = False
  1129. SyncLock LockSource
  1130. If Not Th.Source.IsFailed OrElse Th.Source.SingleThread = Th Then
  1131. IsThisFail = True
  1132. Th.Source.IsFailed = True
  1133. End If
  1134. End SyncLock
  1135. '……后续处理
  1136. If IsThisFail Then
  1137. Log($"[Download] {LocalName}:下载源被禁用({Th.Source.Id}):{Th.Source.Url}")
  1138. Log(ex, $"{If(SourcesOnce.FirstOrDefault?.SingleThread Is Nothing, "", "单线程")}下载源 {Th.Source.Id} 已被禁用",
  1139. If(ex.Message.Contains("不支持分段下载") OrElse ex.Message.Contains("(404)") OrElse ex.Message.Contains("(416)"), LogLevel.Developer, LogLevel.Debug))
  1140. SyncLock LockSource
  1141. SourcesOnce.Remove(Th.Source)
  1142. End SyncLock
  1143. If ex.Message.Contains("空间不足") Then
  1144. '硬盘空间不足:强制失败
  1145. Fail(ex)
  1146. ElseIf HasAvailableSource() AndAlso Not IsMergeFailure Then
  1147. '当前源失败,但还有下载源:正常地继续执行
  1148. ElseIf Not Retried AndAlso Sources.Count > 1 Then
  1149. '合并失败或首次下载失败,未重试:将所有下载源重新标记为不允许断点续传的下载源,逐个重新尝试下载
  1150. Hint($"{LocalName}:文件下载失败,正在自动重试……", If(ModeDebug, HintType.Critical, HintType.Info)) '在调试模式下给出红色提示
  1151. Retried = True
  1152. SyncLock LockSource
  1153. SourcesOnce.Clear()
  1154. For Each Source In Sources
  1155. SourcesOnce.Add(Source)
  1156. Source.IsFailed = True
  1157. Next
  1158. End SyncLock
  1159. Reset()
  1160. SyncLock LockState
  1161. State = NetState.WaitForDownload
  1162. End SyncLock
  1163. ElseIf HasAvailableSource() AndAlso IsMergeFailure Then
  1164. '合并失败且单个源失败:继续下一个源
  1165. Reset()
  1166. SyncLock LockState
  1167. State = NetState.WaitForDownload
  1168. End SyncLock
  1169. Else
  1170. '失败
  1171. Log($"[Download] {LocalName}:已无可用下载源,下载失败")
  1172. Dim ExampleEx As Exception = Nothing
  1173. SyncLock LockSource
  1174. For Each Source As NetSource In Sources
  1175. Log("[Download] 已禁用的下载源:" & Source.Url)
  1176. If Source.Ex IsNot Nothing Then
  1177. ExampleEx = Source.Ex
  1178. Log(Source.Ex, "下载源禁用原因", LogLevel.Developer)
  1179. End If
  1180. Next
  1181. End SyncLock
  1182. Fail(ExampleEx)
  1183. End If
  1184. End If
  1185. End If
  1186. '清理当前已下载的内容
  1187. If FileSize = -2 Then Reset()
  1188. End Sub
  1189. Private Sub Reset()
  1190. FileSize = -2
  1191. Cache?.Dispose() : Cache = Nothing
  1192. SyncLock LockChain
  1193. Threads = Nothing
  1194. End SyncLock
  1195. NetManager.DownloadDone -= DownloadDone
  1196. SyncLock LockDone
  1197. DownloadDone = 0
  1198. End SyncLock
  1199. SpeedLastDone = 0
  1200. End Sub
  1201. '最终收束事件
  1202. ''' <summary>
  1203. ''' 下载完成。合并文件。
  1204. ''' </summary>
  1205. Private Sub Merge(Th As NetThread)
  1206. '状态判断
  1207. SyncLock LockState
  1208. If State < NetState.Merge Then
  1209. State = NetState.Merge
  1210. Else
  1211. Return
  1212. End If
  1213. End SyncLock
  1214. Dim RetryCount As Integer = 0
  1215. Try
  1216. Retry:
  1217. '创建文件夹
  1218. If File.Exists(LocalPath) Then File.Delete(LocalPath)
  1219. Directory.CreateDirectory(GetPathFromFullPath(LocalPath))
  1220. SyncLock LockChain
  1221. '合并文件
  1222. If IsNoSplit Then
  1223. '仅有一个线程,从缓存中输出
  1224. If ModeDebug Then Log($"[Download] {LocalName}:下载结束,从内存输出文件")
  1225. Cache.Position = 0
  1226. WriteFile(LocalPath, Cache)
  1227. ElseIf Threads.DownloadDone = DownloadDone AndAlso Threads.Temp IsNot Nothing Then
  1228. '仅有一个文件,直接复制
  1229. If ModeDebug Then Log($"[Download] {LocalName}:下载结束,仅有一个文件,无需合并")
  1230. CopyFile(Threads.Temp, LocalPath)
  1231. Else
  1232. '有多个线程,合并
  1233. If ModeDebug Then Log($"[Download] {LocalName}:下载结束,开始合并文件")
  1234. Using MergeFile As New FileStream(LocalPath, FileMode.Create)
  1235. Using AddWriter As New BinaryWriter(MergeFile)
  1236. For Each Thread As NetThread In Threads
  1237. If Thread.DownloadDone = 0 OrElse Thread.Temp Is Nothing Then Continue For
  1238. Using fs As New FileStream(Thread.Temp, FileMode.Open, FileAccess.Read, FileShare.Read)
  1239. Using TempReader As New BinaryReader(fs)
  1240. AddWriter.Write(TempReader.ReadBytes(Thread.DownloadDone))
  1241. End Using
  1242. End Using
  1243. Next
  1244. End Using
  1245. End Using
  1246. End If
  1247. '检查文件
  1248. Dim CheckResult As String = Check?.Check(LocalPath)
  1249. If CheckResult Is Nothing AndAlso Not IsUnknownSize AndAlso Check IsNot Nothing Then
  1250. If Check.ActualSize = -1 Then
  1251. CheckResult = (New FileChecker With {.ActualSize = FileSize}).Check(LocalPath) '不修改原始的 Checker,以免污染原始实例
  1252. ElseIf Check.ActualSize <> FileSize Then
  1253. CheckResult = $"文件大小不一致:任务校验要求为 {Check.ActualSize},请求结果为 {FileSize}"
  1254. End If
  1255. End If
  1256. If CheckResult IsNot Nothing Then
  1257. Log($"[Download] {LocalName} 文件校验失败,下载线程细节:")
  1258. For Each T As NetThread In Threads
  1259. Log($"[Download] - {T.Uuid}#,状态 {GetStringFromEnum(T.State)},范围 {T.DownloadStart}~{T.DownloadEnd},已下载 {T.DownloadDone},未下载 {T.DownloadUndone}")
  1260. Next
  1261. Throw New Exception(CheckResult)
  1262. End If
  1263. '后处理
  1264. If Not IsNoSplit Then
  1265. For Each Thread As NetThread In Threads
  1266. If Thread.Temp IsNot Nothing Then File.Delete(Thread.Temp)
  1267. Next
  1268. End If
  1269. Finish()
  1270. End SyncLock
  1271. Catch ex As Exception
  1272. RetryCount += 1
  1273. Log(ex, $"合并文件出错,第 {RetryCount} 次尝试({LocalName})")
  1274. '重新尝试合并
  1275. If RetryCount < 3 Then
  1276. Threading.Thread.Sleep(500 * RetryCount)
  1277. GoTo Retry
  1278. End If
  1279. '失败,禁用当前下载源并重启下载
  1280. If File.Exists(LocalPath) Then File.Delete(LocalPath)
  1281. SourceFail(Th, ex, True)
  1282. Finally
  1283. Cache?.Dispose()
  1284. End Try
  1285. End Sub
  1286. ''' <summary>
  1287. ''' 下载失败。
  1288. ''' </summary>
  1289. Private Sub Fail(Optional RaiseEx As Exception = Nothing)
  1290. SyncLock LockState
  1291. If State >= NetState.Finish Then Return
  1292. If RaiseEx IsNot Nothing Then Ex.Add(RaiseEx)
  1293. '凉凉
  1294. State = NetState.Error
  1295. End SyncLock
  1296. AbortInternal()
  1297. For Each Task In Tasks
  1298. Task.OnFileFail(Me)
  1299. Next
  1300. End Sub
  1301. ''' <summary>
  1302. ''' 下载中断。
  1303. ''' </summary>
  1304. Public Sub Abort(AbortedTask As LoaderDownload)
  1305. '从特定任务中移除,如果它还属于其他任务,则继续下载
  1306. Tasks.Remove(AbortedTask)
  1307. If Tasks.Any Then Return
  1308. '确认中断
  1309. SyncLock LockState
  1310. If State >= NetState.Finish Then Return
  1311. State = NetState.Error
  1312. End SyncLock
  1313. AbortInternal()
  1314. End Sub
  1315. Private Sub AbortInternal()
  1316. On Error Resume Next
  1317. Reset()
  1318. SyncLock NetManager.LockRemain
  1319. NetManager.FileRemain -= 1
  1320. End SyncLock
  1321. Log($"[Download] {LocalName}:已终止,当前状态 {State}")
  1322. End Sub
  1323. '状态改变接口
  1324. ''' <summary>
  1325. ''' 将该文件设置为已下载完成。
  1326. ''' </summary>
  1327. Public Sub Finish(Optional PrintLog As Boolean = True)
  1328. SyncLock LockState
  1329. If State >= NetState.Finish Then Return
  1330. State = NetState.Finish
  1331. End SyncLock
  1332. SyncLock NetManager.LockRemain
  1333. NetManager.FileRemain -= 1
  1334. End SyncLock
  1335. If PrintLog Then Log($"[Download] {LocalName}:已完成")
  1336. For Each Task In Tasks
  1337. Task.OnFileFinish(Me)
  1338. Next
  1339. End Sub
  1340. End Class
  1341. ''' <summary>
  1342. ''' 下载一系列文件的加载器。
  1343. ''' </summary>
  1344. Public Class LoaderDownload
  1345. Inherits LoaderBase
  1346. #Region "属性"
  1347. ''' <summary>
  1348. ''' 需要下载的文件。
  1349. ''' </summary>
  1350. Public Files As SafeList(Of NetFile)
  1351. ''' <summary>
  1352. ''' 剩余未完成的文件数。(用于减轻 FilesLock 的占用)
  1353. ''' </summary>
  1354. Private FileRemain As Integer
  1355. Private ReadOnly FileRemainLock As New Object
  1356. ''' <summary>
  1357. ''' 用于显示的百分比进度。
  1358. ''' </summary>
  1359. Public Overrides Property Progress As Double
  1360. Get
  1361. If State >= LoadState.Finished Then Return 1
  1362. If Not Files.Any() Then Return 0 '必须返回 0,否则在获取列表的时候会错觉已经下载完了
  1363. Return _Progress
  1364. End Get
  1365. Set(value As Double)
  1366. Throw New Exception("文件下载不允许指定进度")
  1367. End Set
  1368. End Property
  1369. Private _Progress As Double = 0
  1370. ''' <summary>
  1371. ''' 任务中的文件的连续失败计数。
  1372. ''' </summary>
  1373. Public Property FailCount As Integer
  1374. Get
  1375. Return _FailCount
  1376. End Get
  1377. Set(value As Integer)
  1378. _FailCount = value
  1379. If State = LoadState.Loading AndAlso value >= Math.Min(10000, Math.Max(FileRemain * 5.5, NetTaskThreadLimit * 5.5 + 3)) Then
  1380. Log("[Download] 由于同加载器中失败次数过多引发强制失败:连续失败了 " & value & " 次", LogLevel.Debug)
  1381. On Error Resume Next
  1382. Dim ExList As New List(Of Exception)
  1383. For Each File In Files
  1384. For Each Source In File.Sources
  1385. If Source.Ex IsNot Nothing Then
  1386. ExList.Add(Source.Ex)
  1387. If ExList.Count > 10 Then GoTo FinishExCatch
  1388. End If
  1389. Next
  1390. Next
  1391. FinishExCatch:
  1392. OnFail(ExList)
  1393. End If
  1394. End Set
  1395. End Property
  1396. Private _FailCount As Integer = 0
  1397. #End Region
  1398. ''' <summary>
  1399. ''' 刷新公开属性。由 NetManager 每 0.1 秒调用一次。
  1400. ''' </summary>
  1401. Public Sub RefreshStat()
  1402. '计算进度
  1403. Dim NewProgress As Double = 0
  1404. Dim TotalProgress As Double = 0
  1405. For Each File In Files
  1406. If File.IsCopy Then
  1407. NewProgress += File.Progress * 0.2
  1408. TotalProgress += 0.2
  1409. Else
  1410. NewProgress += File.Progress
  1411. TotalProgress += 1
  1412. End If
  1413. Next
  1414. If TotalProgress > 0 AndAlso Not Double.IsNaN(TotalProgress) Then NewProgress /= TotalProgress
  1415. '刷新进度
  1416. _Progress = NewProgress
  1417. End Sub
  1418. Public Sub New(Name As String, FileTasks As List(Of NetFile))
  1419. Me.Name = Name
  1420. Files = New SafeList(Of NetFile)(FileTasks)
  1421. End Sub
  1422. Public Overrides Sub Start(Optional Input As Object = Nothing, Optional IsForceRestart As Boolean = False)
  1423. If Input IsNot Nothing Then Files = New SafeList(Of NetFile)(Input)
  1424. '去重
  1425. Dim ResultArray As New SafeList(Of NetFile)
  1426. For i = 0 To Files.Count - 1
  1427. For ii = i + 1 To Files.Count - 1
  1428. If Files(i).LocalPath = Files(ii).LocalPath Then GoTo NextElement
  1429. Next
  1430. ResultArray.Add(Files(i))
  1431. NextElement:
  1432. Next
  1433. Files = ResultArray
  1434. '设置剩余文件数
  1435. SyncLock FileRemainLock
  1436. For Each File In Files
  1437. If File.State <> NetState.Finish Then FileRemain += 1
  1438. Next
  1439. End SyncLock
  1440. State = LoadState.Loading
  1441. '开始执行
  1442. RunInNewThread(
  1443. Sub()
  1444. Try
  1445. '输入检测
  1446. If Not Files.Any() Then
  1447. OnFinish()
  1448. Return
  1449. End If
  1450. For Each File As NetFile In Files
  1451. If File Is Nothing Then Throw New ArgumentException("存在空文件请求!")
  1452. For Each Source As NetSource In File.Sources
  1453. If Not (Source.Url.StartsWithF("https://", True) OrElse Source.Url.StartsWithF("http://", True)) Then
  1454. Source.Ex = New ArgumentException("输入的下载链接不正确:" & Source.Url)
  1455. Source.IsFailed = True
  1456. End If
  1457. Next
  1458. If Not File.HasAvailableSource() Then Throw New ArgumentException("输入的下载链接不正确!")
  1459. If Not File.LocalPath.ToLower.Contains(":\") Then Throw New ArgumentException("输入的本地文件地址不正确:" & File.LocalPath)
  1460. If File.LocalPath.EndsWithF("\") Then Throw New ArgumentException("请输入含文件名的完整文件路径:" & File.LocalPath)
  1461. '文件夹检测
  1462. Dim DirPath As String = New FileInfo(File.LocalPath).Directory.FullName
  1463. If Not Directory.Exists(DirPath) Then Directory.CreateDirectory(DirPath)
  1464. Next
  1465. '接入下载管理器
  1466. NetManager.Start(Me)
  1467. '将文件分配给多个线程以进行已存在查找
  1468. Dim Folders As New List(Of String) '可能会用于已存在查找的文件夹列表
  1469. Dim FoldersFinal As New List(Of String) '最终用于查找的列表
  1470. If Not Setup.Get("SystemDebugSkipCopy") Then '在设置中禁用复制
  1471. Folders.Add(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) & "\.minecraft\") '总是添加官启文件夹,因为 HMCL 会把所有文件存在这里
  1472. For Each Folder In McFolderList
  1473. Folders.Add(Folder.Path)
  1474. Next
  1475. Folders = Folders.Distinct.ToList
  1476. For Each Folder In Folders
  1477. If Folder <> PathMcFolder AndAlso Directory.Exists(Folder) Then FoldersFinal.Add(Folder)
  1478. Next
  1479. End If
  1480. '最多 5 个线程,最少每个线程分配 10 个文件
  1481. Dim FilesPerThread As Integer = Math.Max(5, Files.Count / 10 + 1)
  1482. Dim FilesInThread As New List(Of NetFile)
  1483. For Each File In Files
  1484. FilesInThread.Add(File)
  1485. If FilesInThread.Count = FilesPerThread Then
  1486. Dim FilesToRun As New List(Of NetFile)
  1487. FilesToRun.AddRange(FilesInThread)
  1488. RunInNewThread(Sub() StartCopy(FilesToRun, FoldersFinal), "下载 文件复制 " & Uuid)
  1489. FilesInThread.Clear()
  1490. End If
  1491. Next
  1492. If FilesInThread.Any Then
  1493. Dim FilesToRun As New List(Of NetFile)
  1494. FilesToRun.AddRange(FilesInThread)
  1495. RunInNewThread(Sub() StartCopy(FilesToRun, FoldersFinal), "下载 文件复制 " & Uuid)
  1496. FilesInThread.Clear()
  1497. End If
  1498. Catch ex As Exception
  1499. OnFail(New List(Of Exception) From {ex})
  1500. End Try
  1501. End Sub, "L/下载 " & Uuid)
  1502. End Sub
  1503. Private Sub StartCopy(Files As List(Of NetFile), FolderList As List(Of String))
  1504. Try
  1505. If ModeDebug Then Log($"[Download] 检查线程分配文件数:{Files.Count},线程名:{Thread.CurrentThread.Name}")
  1506. '试图从已存在的 Minecraft 文件夹中寻找目标文件
  1507. Dim ExistFiles As New List(Of KeyValuePair(Of NetFile, String)) '{NetFile, Target As String}
  1508. For Each File As NetFile In Files
  1509. Dim ExistFilePath As String = Nothing
  1510. '判断是否有已存在的文件
  1511. If File.Check IsNot Nothing AndAlso McFolderList IsNot Nothing AndAlso PathMcFolder IsNot Nothing AndAlso
  1512. File.Check.CanUseExistsFile AndAlso File.LocalPath.StartsWithF(PathMcFolder) Then
  1513. Dim Relative = File.LocalPath.Replace(PathMcFolder, "")
  1514. For Each Folder In FolderList
  1515. Dim Target = Folder & Relative
  1516. If File.Check.Check(Target) Is Nothing Then
  1517. ExistFilePath = Target
  1518. Exit For
  1519. End If
  1520. Next
  1521. End If
  1522. '若存在,则改变状态
  1523. SyncLock LockState
  1524. If ExistFilePath IsNot Nothing Then
  1525. File.State = NetState.WaitForCopy
  1526. File.IsCopy = True
  1527. ExistFiles.Add(New KeyValuePair(Of NetFile, String)(File, ExistFilePath))
  1528. Else
  1529. File.State = NetState.WaitForDownload
  1530. File.IsCopy = False
  1531. End If
  1532. End SyncLock
  1533. Next
  1534. '复制已存在的文件
  1535. For Each FileToken In ExistFiles
  1536. Dim File As NetFile = FileToken.Key
  1537. SyncLock LockState
  1538. If File.State > NetState.WaitForCopy Then Return
  1539. End SyncLock
  1540. Dim LocalPath As String = FileToken.Value
  1541. Dim RetryCount As Integer = 0
  1542. Retry:
  1543. Try
  1544. Log("[Download] 复制已存在的文件(" & LocalPath & ")")
  1545. CopyFile(LocalPath, File.LocalPath)
  1546. File.Finish(False)
  1547. Catch ex As Exception
  1548. RetryCount += 1
  1549. Log(ex, $"复制已存在的文件失败,重试第 {RetryCount} 次({LocalPath} -> {File.LocalPath})")
  1550. If RetryCount < 3 Then
  1551. Thread.Sleep(200)
  1552. GoTo Retry
  1553. End If
  1554. File.State = NetState.WaitForDownload
  1555. File.IsCopy = False
  1556. End Try
  1557. Next
  1558. Catch ex As Exception
  1559. Log(ex, "下载已存在文件查找失败", LogLevel.Feedback)
  1560. End Try
  1561. End Sub
  1562. Public Sub OnFileFinish(File As NetFile)
  1563. '要求全部文件完成
  1564. SyncLock FileRemainLock
  1565. FileRemain -= 1
  1566. If FileRemain > 0 Then Return
  1567. End SyncLock
  1568. OnFinish()
  1569. End Sub
  1570. Public Sub OnFinish()
  1571. RaisePreviewFinish()
  1572. SyncLock LockState
  1573. If State > LoadState.Loading Then Return
  1574. State = LoadState.Finished
  1575. End SyncLock
  1576. End Sub
  1577. Public Sub OnFileFail(File As NetFile)
  1578. '将下载源的错误加入主错误列表
  1579. For Each Source In File.Sources
  1580. If Not IsNothing(Source.Ex) Then File.Ex.Add(Source.Ex)
  1581. Next
  1582. OnFail(File.Ex)
  1583. End Sub
  1584. Public Sub OnFail(ExList As List(Of Exception))
  1585. SyncLock LockState
  1586. If State > LoadState.Loading Then Return
  1587. If ExList Is Nothing OrElse Not ExList.Any() Then ExList = New List(Of Exception) From {New Exception("未知错误!")}
  1588. '寻找有效的错误信息
  1589. Dim UsefulExs = ExList.Where(Function(e) TypeOf e IsNot OperationCanceledException AndAlso TypeOf e IsNot ThreadInterruptedException).ToList
  1590. [Error] = If(UsefulExs.FirstOrDefault, ExList.FirstOrDefault)
  1591. '获取实际失败的文件
  1592. For Each File In Files
  1593. If File.State <> NetState.Error Then Continue For
  1594. Dim Detail As String = Join(File.Sources.Select(Function(s) $"{If(s.Ex Is Nothing, "无错误信息。", s.Ex.GetBrief())}({s.Url})"), vbCrLf)
  1595. [Error] = New Exception("文件下载失败:" & File.LocalPath & vbCrLf &
  1596. "各下载源的错误如下:" & vbCrLf & Detail,
  1597. [Error])
  1598. '上报
  1599. Telemetry("文件下载失败",
  1600. "FileName", File.LocalName,
  1601. "Exception", Detail)
  1602. Exit For
  1603. Next
  1604. '在设置 Error 对象后再更改为失败,避免 WaitForExit 无法捕获错误
  1605. State = LoadState.Failed
  1606. End SyncLock
  1607. '中断所有文件
  1608. For Each TaskFile In Files
  1609. TaskFile.Abort(Me)
  1610. Next
  1611. '在退出同步锁后再进行日志输出
  1612. Dim ErrOutput As New List(Of String)
  1613. For Each Ex As Exception In ExList
  1614. ErrOutput.Add(Ex.GetDetail())
  1615. Next
  1616. Log("[Download] " & Join(ErrOutput.Distinct.ToArray, vbCrLf))
  1617. End Sub
  1618. Public Overrides Sub Abort()
  1619. SyncLock LockState
  1620. If State >= LoadState.Finished Then Return
  1621. State = LoadState.Aborted
  1622. End SyncLock
  1623. Log("[Download] " & Name & " 已取消!")
  1624. '中断所有文件
  1625. For Each TaskFile In Files
  1626. TaskFile.Abort(Me)
  1627. Next
  1628. End Sub
  1629. End Class
  1630. Public NetManager As New NetManagerClass
  1631. ''' <summary>
  1632. ''' 下载文件管理。
  1633. ''' </summary>
  1634. Public Class NetManagerClass
  1635. #Region "属性"
  1636. ''' <summary>
  1637. ''' 需要下载的文件。为“本地地址 - 文件对象”键值对。
  1638. ''' </summary>
  1639. Public Files As New Dictionary(Of String, NetFile)
  1640. Public ReadOnly LockFiles As New Object
  1641. ''' <summary>
  1642. ''' 当前的所有下载任务。
  1643. ''' </summary>
  1644. Public Tasks As New SafeList(Of LoaderDownload)
  1645. ''' <summary>
  1646. ''' 已下载完成的大小。
  1647. ''' </summary>
  1648. Public Property DownloadDone As Long
  1649. Get
  1650. Return _DownloadDone
  1651. End Get
  1652. Set(value As Long)
  1653. SyncLock LockDone
  1654. _DownloadDone = value
  1655. End SyncLock
  1656. End Set
  1657. End Property
  1658. Private _DownloadDone As Long = 0
  1659. Private ReadOnly LockDone As New Object
  1660. ''' <summary>
  1661. ''' 尚未完成下载的文件数。
  1662. ''' </summary>
  1663. Public FileRemain As Integer = 0
  1664. Public ReadOnly LockRemain As New Object
  1665. ''' <summary>
  1666. ''' 上次记速时的已下载大小。
  1667. ''' </summary>
  1668. Private SpeedLastDone As Long = 0
  1669. ''' <summary>
  1670. ''' 至多最近 30 次下载速度的记录,较新的在前面。
  1671. ''' </summary>
  1672. Private SpeedLast As New List(Of Long)
  1673. '这些属性由 RefreshStat 刷新
  1674. ''' <summary>
  1675. ''' 当前的全局下载速度,单位为 Byte / 秒。
  1676. ''' </summary>
  1677. Public Speed As Long = 0
  1678. Public ReadOnly Uuid As Integer = GetUuid()
  1679. #End Region
  1680. ''' <summary>
  1681. ''' 进度与下载速度由下载管理线程每隔约 0.1 秒刷新一次。
  1682. ''' </summary>
  1683. Private Sub RefreshStat()
  1684. Try
  1685. Dim DeltaTime As Long = GetTimeTick() - RefreshStatLast
  1686. If DeltaTime = 0 Then Return
  1687. RefreshStatLast += DeltaTime
  1688. #Region "刷新整体速度"
  1689. '计算瞬时速度
  1690. Dim ActualSpeed As Double = Math.Max(0, (DownloadDone - SpeedLastDone) / (DeltaTime / 1000))
  1691. SpeedLast.Insert(0, ActualSpeed)
  1692. If SpeedLast.Count >= 31 Then SpeedLast.RemoveAt(30)
  1693. SpeedLastDone = DownloadDone
  1694. '计算用于显示的速度
  1695. Dim SpeedSum As Long = 0, SpeedDiv As Long = 0, Weight = SpeedLast.Count
  1696. For Each SpeedRecord In SpeedLast
  1697. SpeedSum += SpeedRecord * Weight
  1698. SpeedDiv += Weight
  1699. Weight -= 1
  1700. Next
  1701. Speed = If(SpeedDiv > 0, SpeedSum / SpeedDiv, 0)
  1702. '计算新的速度下限
  1703. Dim Limit As Long = 0
  1704. If SpeedLast.Count >= 10 Then Limit = SpeedLast.Take(10).Average * 0.85 '取近 1 秒的平均速度的 85%
  1705. If Limit > NetTaskSpeedLimitLow Then
  1706. NetTaskSpeedLimitLow = Limit
  1707. Log("[Download] " & "速度下限已提升到 " & GetString(Limit))
  1708. End If
  1709. #End Region
  1710. #Region "刷新下载任务属性"
  1711. For Each Task In Tasks
  1712. Task.RefreshStat()
  1713. Next
  1714. #End Region
  1715. Catch ex As Exception
  1716. Log(ex, "刷新下载公开属性失败")
  1717. End Try
  1718. End Sub
  1719. Private RefreshStatLast As Long
  1720. ''' <summary>
  1721. ''' 启动监控线程,用于新增下载线程。
  1722. ''' </summary>
  1723. Private Sub StartManager()
  1724. If IsManagerStarted Then Return
  1725. IsManagerStarted = True
  1726. Dim ThreadStarter =
  1727. Sub(Id As Integer) '0 或 1
  1728. Try
  1729. While True
  1730. Thread.Sleep(20)
  1731. '获取文件列表
  1732. Dim AllFiles As List(Of NetFile)
  1733. SyncLock LockFiles
  1734. If Id = 0 AndAlso FileRemain = 0 AndAlso Files.Any() Then Files.Clear() '若已完成,则清空
  1735. AllFiles = Files.Values.ToList()
  1736. End SyncLock
  1737. Dim WaitingFiles As New List(Of NetFile)
  1738. Dim OngoingFiles As New List(Of NetFile)
  1739. For Each File As NetFile In AllFiles
  1740. If File.Uuid Mod 2 = Id Then Continue For
  1741. If File.State = NetState.WaitForDownload Then
  1742. WaitingFiles.Add(File)
  1743. ElseIf File.State < NetState.Merge Then
  1744. OngoingFiles.Add(File)
  1745. End If
  1746. Next
  1747. '为等待中的文件开始线程
  1748. For Each File As NetFile In WaitingFiles
  1749. If NetTaskThreadCount >= NetTaskThreadLimit Then Continue While '最大线程数检查
  1750. Dim NewThread = File.TryBeginThread()
  1751. If NewThread IsNot Nothing AndAlso NewThread.Source.Url.Contains("bmclapi") Then Thread.Sleep(40) '减少 BMCLAPI 请求频率(目前每分钟限制 4000 次)
  1752. Next
  1753. '为进行中的文件追加线程
  1754. If Speed >= NetTaskSpeedLimitLow Then Continue While '下载速度足够,无需新增
  1755. For Each File As NetFile In OngoingFiles
  1756. If NetTaskThreadCount >= NetTaskThreadLimit Then Continue While '最大线程数检查
  1757. '线程种类计数
  1758. Dim PreparingCount = 0, DownloadingCount = 0
  1759. If File.Threads IsNot Nothing Then
  1760. For Each Thread As NetThread In File.Threads.ToList
  1761. If Thread.State < NetState.Download Then
  1762. PreparingCount += 1
  1763. ElseIf Thread.State = NetState.Download Then
  1764. DownloadingCount += 1
  1765. End If
  1766. Next
  1767. End If
  1768. '新增线程
  1769. If PreparingCount > DownloadingCount Then Continue For '准备中的线程已多于下载中的线程,不再新增
  1770. Dim NewThread = File.TryBeginThread()
  1771. If NewThread IsNot Nothing AndAlso NewThread.Source.Url.Contains("bmclapi") Then Thread.Sleep(40) '减少 BMCLAPI 请求频率(目前每分钟限制 4000 次)
  1772. Next
  1773. End While
  1774. Catch ex As Exception
  1775. Log(ex, $"下载管理启动线程 {Id} 出错", LogLevel.Critical)
  1776. End Try
  1777. End Sub
  1778. RunInNewThread(Sub() ThreadStarter(0), "NetManager ThreadStarter 0")
  1779. RunInNewThread(Sub() ThreadStarter(1), "NetManager ThreadStarter 1")
  1780. RunInNewThread(
  1781. Sub()
  1782. Try
  1783. Dim LastLoopTime As Long
  1784. NetTaskSpeedLimitLeftLast = GetTimeTick()
  1785. While True
  1786. Dim TimeNow = GetTimeTick()
  1787. LastLoopTime = TimeNow
  1788. '增加限速余量
  1789. If NetTaskSpeedLimitHigh > 0 Then NetTaskSpeedLimitLeft = NetTaskSpeedLimitHigh / 1000 * (TimeNow - NetTaskSpeedLimitLeftLast)
  1790. NetTaskSpeedLimitLeftLast = TimeNow
  1791. '刷新公开属性
  1792. RefreshStat()
  1793. '等待直至 80 ms
  1794. Do While GetTimeTick() - LastLoopTime < 80
  1795. Thread.Sleep(10)
  1796. Loop
  1797. End While
  1798. Catch ex As Exception
  1799. Log(ex, "下载管理刷新线程出错", LogLevel.Critical)
  1800. End Try
  1801. End Sub, "NetManager StatRefresher")
  1802. End Sub
  1803. Private IsManagerStarted As Boolean = False
  1804. Private DownloadCacheLock As New Object
  1805. Private IsDownloadCacheCleared As Boolean = False
  1806. ''' <summary>
  1807. ''' 开始一个下载任务。
  1808. ''' </summary>
  1809. Public Sub Start(Task As LoaderDownload)
  1810. StartManager()
  1811. '清理缓存
  1812. SyncLock DownloadCacheLock '防止同时开启多个下载任务时重复清理
  1813. If Not IsDownloadCacheCleared Then
  1814. Try
  1815. Log("[Net] 开始清理下载缓存")
  1816. DeleteDirectory(PathTemp & "Download")
  1817. Log("[Net] 下载缓存已清理")
  1818. Catch ex As Exception
  1819. Log(ex, "清理下载缓存失败")
  1820. End Try
  1821. Directory.CreateDirectory(PathTemp & "Download")
  1822. End If
  1823. IsDownloadCacheCleared = True
  1824. End SyncLock
  1825. '文件处理
  1826. SyncLock LockFiles
  1827. '添加每个文件
  1828. For i = 0 To Task.Files.Count - 1
  1829. Dim File = Task.Files(i)
  1830. If Files.ContainsKey(File.LocalPath) Then
  1831. '已有该文件
  1832. If Files(File.LocalPath).State >= NetState.Finish Then
  1833. '该文件已经下载过一次,且下载完成
  1834. '将已下载的文件替换成当前文件,重新下载
  1835. File.Tasks.Add(Task)
  1836. Files(File.LocalPath) = File
  1837. SyncLock LockRemain
  1838. FileRemain += 1
  1839. End SyncLock
  1840. If ModeDebug Then Log($"[Download] {File.LocalName}:重新加入下载列表")
  1841. Else
  1842. '该文件正在下载中
  1843. '将当前文件替换成下载中的文件,即两个任务指向同一个文件
  1844. File = Files(File.LocalPath)
  1845. File.Tasks.Add(Task)
  1846. End If
  1847. Else
  1848. '没有该文件
  1849. File.Tasks.Add(Task)
  1850. Files.Add(File.LocalPath, File)
  1851. SyncLock LockRemain
  1852. FileRemain += 1
  1853. End SyncLock
  1854. If ModeDebug Then Log($"[Download] {File.LocalName}:已加入下载列表")
  1855. End If
  1856. Task.Files(i) = File '回设
  1857. Next
  1858. End SyncLock
  1859. Tasks.Add(Task)
  1860. End Sub
  1861. End Class
  1862. ''' <summary>
  1863. ''' 是否有正在进行中、需要在下载管理页面显示的下载任务?
  1864. ''' </summary>
  1865. Public Function HasDownloadingTask(Optional IgnoreCustomDownload As Boolean = False) As Boolean
  1866. For Each Task In LoaderTaskbar.ToList()
  1867. If (Task.Show AndAlso Task.State = LoadState.Loading) AndAlso
  1868. (Not IgnoreCustomDownload OrElse Not Task.Name.ToString.Contains("自定义下载")) Then
  1869. Return True
  1870. End If
  1871. Next
  1872. Return False
  1873. End Function
  1874. #End Region
  1875. ''' <summary>
  1876. ''' 测试 Ping。失败则返回 -1。
  1877. ''' </summary>
  1878. Public Function Ping(Ip As String, Optional Timeout As Integer = 10000, Optional MakeLog As Boolean = True) As Integer
  1879. Dim PingResult As NetworkInformation.PingReply
  1880. Try
  1881. PingResult = (New NetworkInformation.Ping).Send(Ip)
  1882. Catch ex As Exception
  1883. If MakeLog Then Log("[Net] Ping " & Ip & " 失败:" & ex.Message)
  1884. Return -1
  1885. End Try
  1886. If PingResult.Status = NetworkInformation.IPStatus.Success Then
  1887. If MakeLog Then Log("[Net] Ping " & Ip & " 结束:" & PingResult.RoundtripTime & "ms")
  1888. Return PingResult.RoundtripTime
  1889. Else
  1890. If MakeLog Then Log("[Net] Ping " & Ip & " 失败")
  1891. Return -1
  1892. End If
  1893. End Function
  1894. ''' <summary>
  1895. ''' 判断某个 Exception 是否为网络问题所导致。
  1896. ''' </summary>
  1897. <Extension> Public Function IsNetworkRelated(Ex As Exception) As Boolean
  1898. Dim Detail = Ex.GetDetail()
  1899. If Detail.Contains("(403)") Then Return False
  1900. Return {
  1901. "(408)", "超时", "timeout", "网络请求失败", "连接尝试失败", "远程主机强迫关闭了", "远程方已关闭传输流", "未能解析此远程名称",
  1902. "由于目标计算机积极拒绝", "基础连接已经关闭"
  1903. }.Any(Function(k) Detail.ContainsF(k, True))
  1904. End Function
  1905. End Module