ModNet.vb 102 KB

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