2
0

ModNet.vb 94 KB

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