ModNet.vb 102 KB

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