ModNet.vb 92 KB

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