ModNet.vb 98 KB

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