ModNet.vb 98 KB

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