ModNet.vb 97 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. SecretHeadersSign(Url, Request)
  192. Using res As HttpWebResponse = Request.GetResponse()
  193. Using HttpStream As Stream = res.GetResponseStream()
  194. HttpStream.ReadTimeout = Timeout
  195. Dim HttpData As Byte() = New Byte(16384) {}
  196. Using Reader As New StreamReader(HttpStream, If(Encode, Encoding.UTF8))
  197. Dim ResultString As String = Reader.ReadToEnd
  198. Return If(IsJson, GetJson(ResultString), ResultString)
  199. End Using
  200. End Using
  201. End Using
  202. Catch ex As ThreadInterruptedException
  203. Throw
  204. Catch ex As Exception
  205. If ex.GetType.Equals(GetType(WebException)) AndAlso CType(ex, WebException).Status = WebExceptionStatus.Timeout Then
  206. Throw New TimeoutException("连接服务器超时,已接收 " & Result.Count & " B(" & Url & ")")
  207. Else
  208. Throw New WebException("获取结果失败," & ex.Message & "(" & Url & ")", ex)
  209. End If
  210. Finally
  211. Request.Abort()
  212. End Try
  213. End Function
  214. ''' <summary>
  215. ''' 以多线程下载网页文件的方式获取网页源代码。
  216. ''' </summary>
  217. ''' <param name="Url">网页的 Url。</param>
  218. Public Function NetGetCodeByDownload(Url As String, Optional Timeout As Integer = 45000, Optional IsJson As Boolean = False) As String
  219. Dim Temp As String = PathTemp & "Cache\Code\" & Url.GetHashCode() & "_" & GetUuid()
  220. Dim NewTask As New LoaderDownload("源码获取 " & GetUuid() & "#", New List(Of NetFile) From {New NetFile({Url}, Temp, New FileChecker With {.IsJson = IsJson})})
  221. Try
  222. NewTask.WaitForExitTime(Timeout, TimeoutMessage:="连接服务器超时(" & Url & ")")
  223. NetGetCodeByDownload = ReadFile(Temp)
  224. File.Delete(Temp)
  225. Finally
  226. NewTask.Abort()
  227. End Try
  228. End Function
  229. ''' <summary>
  230. ''' 以多线程下载网页文件的方式获取网页源代码。
  231. ''' </summary>
  232. ''' <param name="Urls">网页的 Url 列表。</param>
  233. Public Function NetGetCodeByDownload(Urls As String(), Optional Timeout As Integer = 45000, Optional IsJson As Boolean = False) As String
  234. Dim Temp As String = PathTemp & "Cache\Code\" & Urls(0).GetHashCode() & "_" & GetUuid()
  235. Dim NewTask As New LoaderDownload("源码获取 " & GetUuid() & "#", New List(Of NetFile) From {New NetFile(Urls, Temp, New FileChecker With {.IsJson = IsJson})})
  236. Try
  237. NewTask.WaitForExitTime(Timeout, TimeoutMessage:="连接服务器超时(第一下载源:" & Urls(0) & ")")
  238. NetGetCodeByDownload = ReadFile(Temp)
  239. File.Delete(Temp)
  240. Finally
  241. NewTask.Abort()
  242. End Try
  243. End Function
  244. ''' <summary>
  245. ''' 从网络中直接下载文件。这不能下载 CDN 中的文件。
  246. ''' </summary>
  247. ''' <param name="Url">网络 Url。</param>
  248. ''' <param name="LocalFile">下载的本地地址。</param>
  249. Public Sub NetDownload(Url As String, LocalFile As String)
  250. Log("[Net] 直接下载文件:" & Url)
  251. '初始化
  252. Try
  253. '建立目录
  254. Directory.CreateDirectory(GetPathFromFullPath(LocalFile))
  255. '尝试删除原文件
  256. File.Delete(LocalFile)
  257. Catch ex As Exception
  258. Throw New WebException("预处理下载文件路径失败(" & LocalFile & ")。", ex)
  259. End Try
  260. '下载
  261. Using Client As New WebClient
  262. Try
  263. Client.Headers(HttpRequestHeader.UserAgent) = "PCL2/" & VersionStandardCode & " Mozilla/5.0 AppleWebKit/537.36 Chrome/63.0.3239.132 Safari/537.36"
  264. Client.Headers(HttpRequestHeader.Referer) = "http://" & VersionCode & ".pcl2.server/"
  265. Client.DownloadFile(Url, LocalFile)
  266. Catch ex As Exception
  267. File.Delete(LocalFile)
  268. Throw New WebException("直接下载文件失败(" & Url & ")。", ex)
  269. End Try
  270. End Using
  271. End Sub
  272. ''' <summary>
  273. ''' 发送一个网络请求并获取返回内容,会重试三次并在最长 45s 后超时。
  274. ''' </summary>
  275. ''' <param name="Url">请求的服务器地址。</param>
  276. ''' <param name="Method">请求方式(POST 或 GET)。</param>
  277. ''' <param name="Data">请求的内容。</param>
  278. ''' <param name="ContentType">请求的套接字类型。</param>
  279. ''' <param name="DontRetryOnRefused">当返回 40x 时不重试。</param>
  280. 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
  281. Dim RetryCount As Integer = 0
  282. Dim RetryException As Exception = Nothing
  283. Dim StartTime As Long = GetTimeTick()
  284. Try
  285. Retry:
  286. Select Case RetryCount
  287. Case 0 '正常尝试
  288. Return NetRequestOnce(Url, Method, Data, ContentType, 15000, Headers)
  289. Case 1 '慢速重试
  290. Thread.Sleep(500)
  291. Return NetRequestOnce(Url, Method, Data, ContentType, 25000, Headers)
  292. Case Else '快速重试
  293. If GetTimeTick() - StartTime > 5500 Then
  294. '若前两次加载耗费 5 秒以上,才进行重试
  295. Thread.Sleep(500)
  296. Return NetRequestOnce(Url, Method, Data, ContentType, 4000, Headers)
  297. Else
  298. Throw RetryException
  299. End If
  300. End Select
  301. Catch ex As ThreadInterruptedException
  302. Throw
  303. Catch ex As Exception
  304. If ex.InnerException IsNot Nothing AndAlso ex.InnerException.Message.Contains("(40") AndAlso DontRetryOnRefused Then RetryCount = 999
  305. Select Case RetryCount
  306. Case 0
  307. If ModeDebug Then Log(ex, "[Net] 网络请求第一次失败(" & Url & ")")
  308. RetryException = ex
  309. RetryCount += 1
  310. GoTo Retry
  311. Case 1
  312. If ModeDebug Then Log(ex, "[Net] 网络请求第二次失败(" & Url & ")")
  313. RetryCount += 1
  314. GoTo Retry
  315. Case Else
  316. Throw
  317. End Select
  318. End Try
  319. End Function
  320. ''' <summary>
  321. ''' 同时发送多个网络请求并要求返回内容。
  322. ''' </summary>
  323. 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)
  324. Dim Threads As New List(Of Thread)
  325. Dim RequestResult = Nothing
  326. Dim RequestEx As Exception = Nothing
  327. Dim FailCount As Integer = 0
  328. For i = 1 To RequestCount
  329. Dim th As New Thread(Sub()
  330. Try
  331. RequestResult = NetRequestOnce(Url, Method, Data, ContentType, 30000, Headers)
  332. Catch ex As Exception
  333. FailCount += 1
  334. RequestEx = ex
  335. End Try
  336. End Sub)
  337. th.Start()
  338. Threads.Add(th)
  339. Thread.Sleep(i * 250)
  340. If RequestResult IsNot Nothing Then GoTo RequestFinished
  341. Next
  342. Do While True
  343. If RequestResult IsNot Nothing Then
  344. RequestFinished:
  345. For Each th In Threads
  346. If th.IsAlive Then th.Interrupt()
  347. Next
  348. Return RequestResult
  349. ElseIf FailCount = RequestCount Then
  350. For Each th In Threads
  351. If th.IsAlive Then th.Interrupt()
  352. Next
  353. Throw RequestEx
  354. End If
  355. Thread.Sleep(20)
  356. Loop
  357. Throw New Exception("未知错误")
  358. End Function
  359. ''' <summary>
  360. ''' 发送一次网络请求并获取返回内容。
  361. ''' </summary>
  362. 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
  363. If RunInUi() AndAlso Not Url.Contains("//127.") Then Throw New Exception("在 UI 线程执行了网络请求")
  364. Url = SecretCdnSign(Url)
  365. If MakeLog Then Log("[Net] 发起网络请求(" & Method & "," & Url & "),最大超时 " & Timeout)
  366. Dim DataStream As Stream = Nothing
  367. Dim Resp As WebResponse = Nothing
  368. Dim Req As HttpWebRequest
  369. Try
  370. Req = WebRequest.Create(New Uri(Url))
  371. Req.Method = Method
  372. Dim SendData As Byte()
  373. If TypeOf Data Is Byte() Then
  374. SendData = Data
  375. Else
  376. SendData = New UTF8Encoding(False).GetBytes(Data.ToString)
  377. End If
  378. If Headers IsNot Nothing Then
  379. For Each Pair In Headers
  380. Req.Headers.Add(Pair.Key, Pair.Value)
  381. Next
  382. End If
  383. Req.ContentType = ContentType
  384. Req.Timeout = Timeout
  385. SecretHeadersSign(Url, Req)
  386. If Url.StartsWith("https", StringComparison.OrdinalIgnoreCase) Then Req.ProtocolVersion = HttpVersion.Version11
  387. If Method = "POST" OrElse Method = "PUT" Then
  388. Req.ContentLength = SendData.Length
  389. DataStream = Req.GetRequestStream()
  390. DataStream.WriteTimeout = Timeout
  391. DataStream.ReadTimeout = Timeout
  392. DataStream.Write(SendData, 0, SendData.Length)
  393. DataStream.Close()
  394. End If
  395. Resp = Req.GetResponse()
  396. DataStream = Resp.GetResponseStream()
  397. DataStream.WriteTimeout = Timeout
  398. DataStream.ReadTimeout = Timeout
  399. Using Reader As New StreamReader(DataStream)
  400. Return Reader.ReadToEnd()
  401. End Using
  402. Catch ex As ThreadInterruptedException
  403. Throw
  404. Catch ex As WebException
  405. If ex.Status = WebExceptionStatus.Timeout Then
  406. Throw New WebException("连接服务器超时,请检查你的网络环境是否良好(" & Url & ")", ex)
  407. Else
  408. '获取请求失败的返回
  409. Dim Res As String = ""
  410. Try
  411. If ex.Response Is Nothing Then Exit Try
  412. DataStream = ex.Response.GetResponseStream()
  413. DataStream.WriteTimeout = Timeout
  414. DataStream.ReadTimeout = Timeout
  415. Using Reader As New StreamReader(DataStream)
  416. Res = Reader.ReadToEnd()
  417. End Using
  418. Catch
  419. End Try
  420. Throw New WebException("网络请求失败(" & Url & "," & ex.Message & ")" & If(String.IsNullOrEmpty(Res), "", vbCrLf & Res), ex)
  421. End If
  422. Catch ex As Exception
  423. Throw New WebException("网络请求失败(" & Url & ")", ex)
  424. Finally
  425. If DataStream IsNot Nothing Then DataStream.Dispose()
  426. If Resp IsNot Nothing Then Resp.Dispose()
  427. End Try
  428. End Function
  429. ''' <summary>
  430. ''' 最大线程数。
  431. ''' </summary>
  432. Public NetTaskThreadLimit As Integer
  433. ''' <summary>
  434. ''' 速度下限。
  435. ''' </summary>
  436. Public NetTaskSpeedLimitLow As Long = 1024 * 1024L
  437. ''' <summary>
  438. ''' 速度上限。若无限制则为 -1。
  439. ''' </summary>
  440. Public NetTaskSpeedLimitHigh As Long = -1
  441. ''' <summary>
  442. ''' 基于限速,当前可以下载的剩余量。
  443. ''' </summary>
  444. Public NetTaskSpeedLimitLeft As Long = -1
  445. Private ReadOnly NetTaskSpeedLimitLeftLock As New Object
  446. Private NetTaskSpeedLimitLeftLast As Long
  447. ''' <summary>
  448. ''' 正在运行中的线程数。
  449. ''' </summary>
  450. Public NetTaskThreadCount As Integer = 0
  451. Private ReadOnly NetTaskThreadCountLock As New Object
  452. ''' <summary>
  453. ''' 下载源。
  454. ''' </summary>
  455. Public Class NetSource
  456. Public Id As Integer
  457. Public Url As String
  458. Public FailCount As Integer
  459. Public Ex As Exception
  460. Public Thread As NetThread
  461. Public IsFailed As Boolean
  462. Public Overrides Function ToString() As String
  463. Return Url
  464. End Function
  465. End Class
  466. ''' <summary>
  467. ''' 下载进度标示。
  468. ''' </summary>
  469. Public Enum NetState
  470. ''' <summary>
  471. ''' 尚未进行已存在检查。
  472. ''' </summary>
  473. WaitForCheck = -1
  474. ''' <summary>
  475. ''' 尚未开始。
  476. ''' </summary>
  477. WaitForDownload = 0
  478. ''' <summary>
  479. ''' 正在连接,尚未获取文件大小。
  480. ''' </summary>
  481. Connect = 1
  482. ''' <summary>
  483. ''' 已获取文件大小,尚未有有效下载。
  484. ''' </summary>
  485. [Get] = 2
  486. ''' <summary>
  487. ''' 正在下载。
  488. ''' </summary>
  489. Download = 3
  490. ''' <summary>
  491. ''' 正在合并文件。
  492. ''' </summary>
  493. Merge = 4
  494. ''' <summary>
  495. ''' 不进行下载,因为已发现现存的文件。
  496. ''' </summary>
  497. WaitForCopy = 5
  498. ''' <summary>
  499. ''' 已完成。
  500. ''' </summary>
  501. Finish = 6
  502. ''' <summary>
  503. ''' 已失败。
  504. ''' </summary>
  505. [Error] = 7
  506. End Enum
  507. ''' <summary>
  508. ''' 预下载检查行为。
  509. ''' </summary>
  510. Public Enum NetPreDownloadBehaviour
  511. ''' <summary>
  512. ''' 当文件已存在时,显示提示以提醒用户是否继续下载。
  513. ''' </summary>
  514. HintWhileExists
  515. ''' <summary>
  516. ''' 当文件已存在或正在下载时,直接退出下载函数执行,不对用户进行提示。
  517. ''' </summary>
  518. ExitWhileExistsOrDownloading
  519. ''' <summary>
  520. ''' 不进行已存在检查。
  521. ''' </summary>
  522. IgnoreCheck
  523. End Enum
  524. ''' <summary>
  525. ''' 下载线程。
  526. ''' </summary>
  527. Public Class NetThread
  528. Implements IEnumerable(Of NetThread)
  529. ''' <summary>
  530. ''' 对应的下载任务。
  531. ''' </summary>
  532. Public Task As NetFile
  533. ''' <summary>
  534. ''' 对应的线程。
  535. ''' </summary>
  536. Public Thread As Thread
  537. ''' <summary>
  538. ''' 链表中的下一个线程。
  539. ''' </summary>
  540. Public NextThread As NetThread
  541. Private ReadOnly Iterator Property [Next]() As IEnumerable(Of NetThread)
  542. Get
  543. Dim CurrentChain As NetThread = Me
  544. While CurrentChain IsNot Nothing
  545. Yield CurrentChain
  546. CurrentChain = CurrentChain.NextThread
  547. End While
  548. End Get
  549. End Property
  550. Public Function GetEnumerator() As IEnumerator(Of NetThread) Implements IEnumerable(Of NetThread).GetEnumerator
  551. Return [Next].GetEnumerator()
  552. End Function
  553. Private Function IEnumerable_GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator
  554. Return [Next].GetEnumerator()
  555. End Function
  556. ''' <summary>
  557. ''' 分配给任务中每个线程(无论其是否失败)的编号。
  558. ''' </summary>
  559. Public Uuid As Integer
  560. ''' <summary>
  561. ''' 是否为第一个线程。
  562. ''' </summary>
  563. Public ReadOnly Property IsFirstThread As Boolean
  564. Get
  565. Return DownloadStart = 0 AndAlso Task.FileSize = -2
  566. End Get
  567. End Property
  568. ''' <summary>
  569. ''' 该线程的缓存文件。
  570. ''' </summary>
  571. Public Temp As String
  572. ''' <summary>
  573. ''' 线程下载起始位置。
  574. ''' </summary>
  575. Public DownloadStart As Long
  576. ''' <summary>
  577. ''' 线程下载结束位置。
  578. ''' </summary>
  579. Public ReadOnly Property DownloadEnd As Long
  580. Get
  581. SyncLock Task.LockChain
  582. If NextThread Is Nothing Then
  583. If Task.IsUnknownSize Then
  584. Return 1024 * 1024 * 1024 '1G
  585. Else
  586. Return Task.FileSize - 1
  587. End If
  588. Else
  589. Return NextThread.DownloadStart - 1
  590. End If
  591. End SyncLock
  592. End Get
  593. End Property
  594. ''' <summary>
  595. ''' 线程未下载的文件大小。
  596. ''' </summary>
  597. Public ReadOnly Property DownloadUndone As Long
  598. Get
  599. Return DownloadEnd + 1 - (DownloadStart + DownloadDone)
  600. End Get
  601. End Property
  602. ''' <summary>
  603. ''' 线程已下载的文件大小。
  604. ''' </summary>
  605. Public DownloadDone As Long = 0
  606. ''' <summary>
  607. ''' 上次记速时的时间。
  608. ''' </summary>
  609. Private SpeedLastTime As Long = GetTimeTick()
  610. ''' <summary>
  611. ''' 上次记速时的已下载大小。
  612. ''' </summary>
  613. Private SpeedLastDone As Long = 0
  614. ''' <summary>
  615. ''' 当前的下载速度,单位为 Byte / 秒。
  616. ''' </summary>
  617. Public ReadOnly Property Speed As Long
  618. Get
  619. If GetTimeTick() - SpeedLastTime > 200 Then
  620. Dim DeltaTime As Long = GetTimeTick() - SpeedLastTime
  621. _Speed = (DownloadDone - SpeedLastDone) / (DeltaTime / 1000)
  622. SpeedLastDone = DownloadDone
  623. SpeedLastTime += DeltaTime
  624. End If
  625. Return _Speed
  626. End Get
  627. End Property
  628. Private _Speed As Long = 0
  629. ''' <summary>
  630. ''' 线程初始化时的时间。
  631. ''' </summary>
  632. Public InitTime As Long = GetTimeTick()
  633. ''' <summary>
  634. ''' 上次接受到有效数据的时间,-1 表示尚未有有效数据。
  635. ''' </summary>
  636. Public LastReceiveTime As Long = -1
  637. ''' <summary>
  638. ''' 当前线程的状态。
  639. ''' </summary>
  640. Public State As NetState = NetState.WaitForDownload
  641. ''' <summary>
  642. ''' 是否已经结束。
  643. ''' </summary>
  644. Public ReadOnly Property IsEnded As Boolean
  645. Get
  646. Return State = NetState.Finish OrElse State = NetState.Error
  647. End Get
  648. End Property
  649. ''' <summary>
  650. ''' 当前选取的是哪一个 Url。
  651. ''' </summary>
  652. Public Source As NetSource
  653. End Class
  654. ''' <summary>
  655. ''' 下载单个文件。
  656. ''' </summary>
  657. Public Class NetFile
  658. #Region "属性"
  659. ''' <summary>
  660. ''' 所属的文件列表任务。
  661. ''' </summary>
  662. Public Tasks As New List(Of LoaderDownload)
  663. ''' <summary>
  664. ''' 所有下载源。
  665. ''' </summary>
  666. Public Sources As NetSource()
  667. ''' <summary>
  668. ''' 用于在第一个线程出错时切换下载源。
  669. ''' </summary>
  670. Private FirstThreadSource As Integer = 0
  671. ''' <summary>
  672. ''' 所有已经被标记为失败的,但未完整尝试过的,不允许断点续传的下载源。
  673. ''' </summary>
  674. Public SourcesOnce As New List(Of NetSource)
  675. ''' <summary>
  676. ''' 获取从某个源开始,第一个可用的源。
  677. ''' </summary>
  678. Private Function GetSource(Optional Id As Integer = 0) As NetSource
  679. If Id >= Sources.Count OrElse Id < 0 Then Id = 0
  680. SyncLock LockSource
  681. If Not IsSourceFailed(False) Then
  682. '存在多线程可用源
  683. Dim CurrentSource As NetSource = Sources(Id)
  684. While CurrentSource.IsFailed
  685. Id += 1
  686. If Id >= Sources.Count Then Id = 0
  687. CurrentSource = Sources(Id)
  688. End While
  689. Return CurrentSource
  690. ElseIf SourcesOnce.Count > 0 Then
  691. '仅存在单线程可用源
  692. Return SourcesOnce(0)
  693. Else
  694. '没有可用源
  695. Return Nothing
  696. End If
  697. End SyncLock
  698. End Function
  699. ''' <summary>
  700. ''' 是否已经没有可用源了。
  701. ''' </summary>
  702. Public Function IsSourceFailed(Optional AllowOnceSource As Boolean = True) As Boolean
  703. If AllowOnceSource AndAlso SourcesOnce.Count > 0 Then Return False
  704. SyncLock LockSource
  705. For Each Source As NetSource In Sources
  706. If Not Source.IsFailed Then Return False
  707. Next
  708. End SyncLock
  709. Return True
  710. End Function
  711. ''' <summary>
  712. ''' 存储在本地的带文件名的地址。
  713. ''' </summary>
  714. Public LocalPath As String = Nothing
  715. ''' <summary>
  716. ''' 存储在本地的文件名。
  717. ''' </summary>
  718. Public LocalName As String = Nothing
  719. ''' <summary>
  720. ''' 当前的下载状态。
  721. ''' </summary>
  722. Public State As NetState = NetState.WaitForCheck
  723. ''' <summary>
  724. ''' 导致下载失败的原因。
  725. ''' </summary>
  726. Public Ex As New List(Of Exception)
  727. '''' <summary>
  728. '''' 文件进行整体重试的计数。
  729. '''' </summary>
  730. 'Private RetryCount As Integer = 0
  731. ''' <summary>
  732. ''' 作为文件组成部分的线程链表。
  733. ''' </summary>
  734. Private Threads As NetThread
  735. ''' <summary>
  736. ''' 文件的总大小。若为 -2 则为未获取,若为 -1 则为无法获取准确大小。
  737. ''' </summary>
  738. Public FileSize As Long = -2
  739. ''' <summary>
  740. ''' 该文件是否无法获取准确大小。
  741. ''' </summary>
  742. Public IsUnknownSize As Boolean = False
  743. ''' <summary>
  744. ''' 该文件是否不需要分割。
  745. ''' </summary>
  746. Public ReadOnly Property IsNoSplit As Boolean
  747. Get
  748. Return IsUnknownSize OrElse FileSize < FilePieceLimit
  749. End Get
  750. End Property
  751. ''' <summary>
  752. ''' 为不需要分割的小文件进行临时存储。
  753. ''' </summary>
  754. Private SmailFileCache As List(Of Byte)
  755. ''' <summary>
  756. ''' 文件的已下载大小。
  757. ''' </summary>
  758. Public DownloadDone As Long = 0
  759. Private ReadOnly LockDone As New Object
  760. ''' <summary>
  761. ''' 文件的校验规则。
  762. ''' </summary>
  763. Public Check As FileChecker
  764. ''' <summary>
  765. ''' 上次记速时的时间。
  766. ''' </summary>
  767. Private SpeedLastTime As Long = GetTimeTick()
  768. ''' <summary>
  769. ''' 上次记速时的已下载大小。
  770. ''' </summary>
  771. Private SpeedLastDone As Long = 0
  772. ''' <summary>
  773. ''' 当前的下载速度,单位为 Byte / 秒。
  774. ''' </summary>
  775. Public ReadOnly Property Speed As Long
  776. Get
  777. If GetTimeTick() - SpeedLastTime > 200 Then
  778. Dim DeltaTime As Long = GetTimeTick() - SpeedLastTime
  779. _Speed = (DownloadDone - SpeedLastDone) / (DeltaTime / 1000)
  780. SpeedLastDone = DownloadDone
  781. SpeedLastTime += DeltaTime
  782. End If
  783. Return _Speed
  784. End Get
  785. End Property
  786. Private _Speed As Long = 0
  787. ''' <summary>
  788. ''' 该文件是否由本地文件直接拷贝完成。
  789. ''' </summary>
  790. Public IsCopy As Boolean = False
  791. ''' <summary>
  792. ''' 本文件的显示进度。
  793. ''' </summary>
  794. Public ReadOnly Property Progress As Double
  795. Get
  796. Select Case State
  797. Case NetState.WaitForCheck
  798. Return 0
  799. Case NetState.WaitForCopy
  800. Return 0.2
  801. Case NetState.WaitForDownload
  802. Return 0.01
  803. Case NetState.Connect
  804. Return 0.02
  805. Case NetState.Get
  806. Return 0.04
  807. Case NetState.Download
  808. '正在下载中,对应 5% ~ 99%
  809. Dim OriginalProgress As Double = If(IsUnknownSize, 0.5, DownloadDone / Math.Max(FileSize, 1))
  810. OriginalProgress = 1 - (1 - OriginalProgress) ^ 0.9
  811. Return OriginalProgress * 0.94 + 0.05
  812. Case NetState.Merge
  813. Return 0.99
  814. Case NetState.Finish, NetState.Error
  815. Return 1
  816. Case Else
  817. Throw New ArgumentOutOfRangeException("文件状态未知:" & State)
  818. End Select
  819. End Get
  820. End Property
  821. ''' <summary>
  822. ''' 各个线程建立连接成功的总次数。
  823. ''' </summary>
  824. Private ConnectCount As Integer = 0
  825. ''' <summary>
  826. ''' 各个线程建立连接成功的总时间。
  827. ''' </summary>
  828. Private ConnectTime As Long = 0
  829. ''' <summary>
  830. ''' 各个线程建立连接成功的平均时间,单位为毫秒,-1 代表尚未有成功连接。
  831. ''' </summary>
  832. Private ReadOnly Property ConnectAverage As Integer
  833. Get
  834. SyncLock LockCount
  835. Return If(ConnectCount = 0, -1, ConnectTime / ConnectCount)
  836. End SyncLock
  837. End Get
  838. End Property
  839. Private Const FilePieceLimit As Long = 256 * 1024
  840. Public ReadOnly RandomCode As Integer = RandomInteger(0, 999999)
  841. Public ReadOnly LockCount As New Object
  842. Public ReadOnly LockState As New Object
  843. Public ReadOnly LockChain As New Object
  844. Public ReadOnly LockSource As New Object
  845. Public ReadOnly LockTasks As New Object
  846. Private ReadOnly Uuid As Integer = GetUuid()
  847. Public Overrides Function Equals(obj As Object) As Boolean
  848. Dim file = TryCast(obj, NetFile)
  849. Return file IsNot Nothing AndAlso Uuid = file.Uuid
  850. End Function
  851. #End Region
  852. ''' <summary>
  853. ''' 新建一个需要下载的文件。
  854. ''' </summary>
  855. ''' <param name="LocalPath">包含文件名的本地地址。</param>
  856. Public Sub New(Urls As String(), LocalPath As String, Optional Check As FileChecker = Nothing)
  857. Dim Sources As New List(Of NetSource)
  858. Dim Count As Integer = 0
  859. Urls = Urls.Distinct.ToArray
  860. For Each Source As String In Urls
  861. Sources.Add(New NetSource With {.FailCount = 0, .Url = SecretCdnSign(Source.Replace(vbCr, "").Replace(vbLf, "").Trim), .Id = Count, .IsFailed = False, .Ex = Nothing})
  862. Count += 1
  863. Next
  864. Me.Sources = Sources.ToArray
  865. Me.LocalPath = LocalPath
  866. Me.Check = Check
  867. Me.LocalName = GetFileNameFromPath(LocalPath)
  868. End Sub
  869. ''' <summary>
  870. ''' 尝试开始一个新的下载线程。
  871. ''' </summary>
  872. Public Function TryBeginThread() As Boolean
  873. Try
  874. '条件检测
  875. If NetTaskThreadCount >= NetTaskThreadLimit OrElse IsSourceFailed() OrElse
  876. (IsNoSplit AndAlso Threads IsNot Nothing AndAlso Threads.State <> NetState.Error) Then Return False
  877. If State >= NetState.Merge OrElse State = NetState.WaitForCheck Then Return False
  878. SyncLock LockState
  879. If State < NetState.Connect Then State = NetState.Connect
  880. End SyncLock
  881. '初始化参数
  882. Dim StartPosition As Long, StartSource As NetSource = Nothing
  883. Dim Th As Thread, ThreadInfo As NetThread
  884. SyncLock LockChain
  885. '获取线程起点与下载源
  886. '不分割
  887. If IsNoSplit Then GoTo Capture
  888. '单线程
  889. If IsSourceFailed(False) Then
  890. '确认没有其他线程正使用此点
  891. If SourcesOnce(0).Thread IsNot Nothing AndAlso SourcesOnce(0).Thread.State <> NetState.Error Then Return False
  892. '占用此点
  893. Capture:
  894. SmailFileCache = Nothing
  895. Threads = Nothing
  896. NetManager.DownloadDone -= DownloadDone
  897. SyncLock LockDone
  898. DownloadDone = 0
  899. End SyncLock
  900. SpeedLastDone = 0
  901. State = NetState.Get
  902. End If
  903. '首个开始点
  904. If Threads Is Nothing Then
  905. StartPosition = 0
  906. StartSource = GetSource(FirstThreadSource)
  907. If StartSource Is Nothing Then
  908. '没有可用源了
  909. Throw New Exception("无可用源,请反馈此问题。")
  910. Else
  911. '有可用源
  912. FirstThreadSource = StartSource.Id + 1
  913. GoTo StartThread
  914. End If
  915. End If
  916. '寻找失败点
  917. For Each Thread As NetThread In Threads
  918. If Thread.State = NetState.Error AndAlso Thread.DownloadUndone > 0 Then
  919. StartPosition = Thread.DownloadStart + Thread.DownloadDone
  920. StartSource = GetSource(Thread.Source.Id + 1)
  921. GoTo StartThread
  922. End If
  923. Next
  924. '是否禁用多线程,以及规定碎片大小
  925. Dim TargetUrl As String = GetSource().Url
  926. If TargetUrl.Contains("pcl2-server") OrElse TargetUrl.Contains("gitcode.net") OrElse TargetUrl.Contains("github.com") Then Return False
  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 < FilePieceLimit 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. '延迟过长会导致某些特别慢的链接迟迟不被掐死
  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. 'BMCLAPI 的部分源在高频率请求下会返回 403,所以不应因此禁用下载源
  1165. If ex.Message.Contains("该下载源不支持") OrElse ex.Message.Contains("未能解析") OrElse ex.Message.Contains("(404)") OrElse
  1166. ex.Message.Contains("(502)") OrElse ex.Message.Contains("无返回数据") OrElse ex.Message.Contains("空间不足") OrElse ex.Message.Contains("获取到的片大小不一致") OrElse
  1167. (Info.Source.FailCount >= MathClamp(NetTaskThreadLimit, 5, 40) AndAlso DownloadDone < 1) OrElse
  1168. Info.Source.FailCount > NetTaskThreadLimit Then
  1169. Dim IsThisFail As Boolean = False
  1170. SyncLock LockSource
  1171. If Info.Source.Thread IsNot Nothing AndAlso Info.Source.Thread.Equals(Info) Then
  1172. '单线程下,本线程出错
  1173. SourcesOnce.RemoveAt(0)
  1174. GoTo Wrong
  1175. ElseIf Not Info.Source.IsFailed Then
  1176. '多线程下,本线程出错
  1177. Wrong:
  1178. Info.Source.IsFailed = True
  1179. IsThisFail = True
  1180. End If
  1181. End SyncLock
  1182. '本线程引发下载源被禁用
  1183. If IsThisFail Then
  1184. Log("[Download] " & LocalName & " " & Uuid & "#:下载源被禁用(" & Info.Source.Id & "):" & Info.Source.Url)
  1185. Log(ex, "下载源 " & Info.Source.Id & " 已被禁用", If(ex.Message.Contains("不支持断点续传") OrElse ex.Message.Contains("(404)") OrElse ex.Message.Contains("(416)"), LogLevel.Developer, LogLevel.Debug))
  1186. If IsSourceFailed() Then
  1187. '没有可用源
  1188. Log("[Download] 文件 " & LocalName & " 已无可用下载源")
  1189. Dim ExampleEx As Exception = Nothing
  1190. SyncLock LockSource
  1191. For Each Source As NetSource In Sources
  1192. Log("[Download] 已禁用的下载源:" & Source.Url)
  1193. If Source.Ex IsNot Nothing Then
  1194. ExampleEx = Source.Ex
  1195. Log(Source.Ex, "下载源禁用原因", LogLevel.Developer)
  1196. End If
  1197. Next
  1198. End SyncLock
  1199. Fail(ExampleEx)
  1200. ElseIf ex.Message.Contains("空间不足") Then
  1201. '没有空间
  1202. Fail(ex)
  1203. End If
  1204. End If
  1205. End If
  1206. '首线程错误
  1207. If FileSize = -2 Then
  1208. SyncLock LockChain
  1209. Threads = Nothing
  1210. End SyncLock
  1211. End If
  1212. Finally
  1213. If ResultStream IsNot Nothing Then ResultStream.Dispose()
  1214. SyncLock NetTaskThreadCountLock
  1215. NetTaskThreadCount -= 1
  1216. End SyncLock
  1217. If ((FileSize >= 0 AndAlso DownloadDone >= FileSize) OrElse (FileSize = -1 AndAlso DownloadDone > 0)) AndAlso State < NetState.Merge Then Merge()
  1218. End Try
  1219. End Sub
  1220. '下载文件的最终收束事件
  1221. ''' <summary>
  1222. ''' 下载完成。合并文件。
  1223. ''' </summary>
  1224. Private Sub Merge()
  1225. '状态判断
  1226. SyncLock LockState
  1227. If State < NetState.Merge Then
  1228. State = NetState.Merge
  1229. Else
  1230. Exit Sub
  1231. End If
  1232. End SyncLock
  1233. Dim RetryCount As Integer = 0
  1234. Dim MergeFile As Stream = Nothing, AddWriter As BinaryWriter = Nothing
  1235. Try
  1236. Retry:
  1237. SyncLock LockChain
  1238. If ModeDebug Then Log("[Download] " & LocalName & ":正在合并文件")
  1239. '创建文件夹
  1240. If File.Exists(LocalPath) Then File.Delete(LocalPath)
  1241. Dim Info As New FileInfo(LocalPath)
  1242. Info.Directory.Create()
  1243. '合并文件
  1244. If IsNoSplit Then
  1245. '仅有一个线程,从缓存中输出
  1246. MergeFile = New FileStream(LocalPath, FileMode.Create)
  1247. AddWriter = New BinaryWriter(MergeFile)
  1248. AddWriter.Write(SmailFileCache.ToArray)
  1249. AddWriter.Dispose() : AddWriter = Nothing
  1250. MergeFile.Dispose() : MergeFile = Nothing
  1251. ElseIf Threads.DownloadDone = DownloadDone AndAlso Threads.Temp IsNot Nothing Then
  1252. '仅有一个文件,直接复制
  1253. CopyFile(Threads.Temp, LocalPath)
  1254. Else
  1255. '有多个线程,合并
  1256. MergeFile = New FileStream(LocalPath, FileMode.Create)
  1257. AddWriter = New BinaryWriter(MergeFile)
  1258. For Each Thread As NetThread In Threads
  1259. If Thread.DownloadDone = 0 OrElse Thread.Temp Is Nothing Then Continue For
  1260. Using fs As New FileStream(Thread.Temp, FileMode.Open, FileAccess.Read, FileShare.Read)
  1261. Dim TempReader As New BinaryReader(fs)
  1262. AddWriter.Write(TempReader.ReadBytes(fs.Length))
  1263. TempReader.Close()
  1264. End Using
  1265. Next
  1266. AddWriter.Dispose() : AddWriter = Nothing
  1267. MergeFile.Dispose() : MergeFile = Nothing
  1268. End If
  1269. '写入大小要求
  1270. If Not IsUnknownSize AndAlso Check IsNot Nothing Then
  1271. If Check.ActualSize = -1 Then
  1272. Check.ActualSize = FileSize
  1273. ElseIf Check.ActualSize <> FileSize Then
  1274. Throw New Exception("文件大小不一致:任务要求为 " & Check.ActualSize & " B,网络获取结果为 " & FileSize & "B")
  1275. End If
  1276. End If
  1277. '检查文件
  1278. Dim CheckResult As String = Check?.Check(LocalPath)
  1279. If CheckResult IsNot Nothing Then
  1280. Log("[Download] " & Uuid & "# 的下载线程细节:")
  1281. For Each Th As NetThread In Threads
  1282. Log("[Download] " & Th.Uuid & "#,状态 " & GetStringFromEnum(CType(Th.State, [Enum])) & ",字节范围 " & Th.DownloadStart & "~" & (Th.DownloadStart + Th.DownloadDone) & ",字节剩余 " & Th.DownloadUndone)
  1283. Next
  1284. Throw New Exception(CheckResult)
  1285. End If
  1286. '后处理
  1287. If IsNoSplit Then
  1288. SmailFileCache = Nothing
  1289. Else
  1290. For Each Thread As NetThread In Threads
  1291. If Thread.Temp IsNot Nothing Then File.Delete(Thread.Temp)
  1292. Next
  1293. End If
  1294. Finish()
  1295. End SyncLock
  1296. Catch ex As Exception
  1297. Log(ex, "合并文件出错(" & LocalName & ")")
  1298. If MergeFile IsNot Nothing Then
  1299. MergeFile.Dispose() : MergeFile = Nothing
  1300. End If
  1301. If AddWriter IsNot Nothing Then
  1302. AddWriter.Dispose() : AddWriter = Nothing
  1303. End If
  1304. '重试
  1305. If RetryCount <= 3 Then
  1306. Threading.Thread.Sleep(RandomInteger(500, 1000))
  1307. RetryCount += 1
  1308. GoTo Retry
  1309. End If
  1310. Fail(ex)
  1311. End Try
  1312. End Sub
  1313. ''' <summary>
  1314. ''' 下载失败。
  1315. ''' </summary>
  1316. Private Sub Fail(Optional RaiseEx As Exception = Nothing)
  1317. SyncLock LockState
  1318. If State >= NetState.Finish Then Exit Sub
  1319. If RaiseEx IsNot Nothing Then Ex.Add(RaiseEx)
  1320. '凉凉
  1321. State = NetState.Error
  1322. End SyncLock
  1323. Try
  1324. If File.Exists(LocalPath) Then File.Delete(LocalPath)
  1325. Catch
  1326. End Try
  1327. SyncLock NetManager.LockRemain
  1328. NetManager.FileRemain -= 1
  1329. Log("[Download] " & LocalName & ":已失败,剩余文件 " & NetManager.FileRemain)
  1330. 'If NetManage.FileRemainList.Contains(LocalPath) Then
  1331. ' NetManage.FileRemainList.Remove(LocalPath)
  1332. 'Else
  1333. ' Log("ERROR " & LocalPath)
  1334. 'End If
  1335. End SyncLock
  1336. For Each Task In Tasks
  1337. Task.OnFileFail(Me)
  1338. Next
  1339. End Sub
  1340. ''' <summary>
  1341. ''' 下载中断。
  1342. ''' </summary>
  1343. Public Sub Abort(CausedByTask As LoaderDownload)
  1344. '确认任务移除
  1345. SyncLock LockTasks
  1346. Tasks.Remove(CausedByTask)
  1347. If Tasks.Count > 0 Then Exit Sub
  1348. End SyncLock
  1349. '确认中断
  1350. SyncLock LockState
  1351. If State >= NetState.Finish Then Exit Sub
  1352. State = NetState.Error
  1353. End SyncLock
  1354. SyncLock NetManager.LockRemain
  1355. NetManager.FileRemain -= 1
  1356. If ModeDebug Then Log("[Download] " & LocalName & ":已取消,剩余文件 " & NetManager.FileRemain)
  1357. 'If NetManage.FileRemainList.Contains(LocalPath) Then
  1358. ' NetManage.FileRemainList.Remove(LocalPath)
  1359. 'Else
  1360. ' Log("ERROR " & LocalPath)
  1361. 'End If
  1362. End SyncLock
  1363. End Sub
  1364. '状态改变接口
  1365. ''' <summary>
  1366. ''' 将该文件设置为已下载完成。
  1367. ''' </summary>
  1368. Public Sub Finish(Optional PrintLog As Boolean = True)
  1369. SyncLock LockState
  1370. If State >= NetState.Finish Then Exit Sub
  1371. State = NetState.Finish
  1372. End SyncLock
  1373. SyncLock NetManager.LockRemain
  1374. NetManager.FileRemain -= 1
  1375. If PrintLog Then Log("[Download] " & LocalName & ":已完成,剩余文件 " & NetManager.FileRemain)
  1376. 'If NetManage.FileRemainList.Contains(LocalPath) Then
  1377. ' NetManage.FileRemainList.Remove(LocalPath)
  1378. 'Else
  1379. ' Log("ERROR " & LocalPath)
  1380. 'End If
  1381. End SyncLock
  1382. SyncLock LockTasks
  1383. For Each Task In Tasks
  1384. Task.OnFileFinish(Me)
  1385. Next
  1386. End SyncLock
  1387. End Sub
  1388. End Class
  1389. ''' <summary>
  1390. ''' 下载一系列文件的加载器。
  1391. ''' </summary>
  1392. Public Class LoaderDownload
  1393. Inherits LoaderBase
  1394. #Region "属性"
  1395. ''' <summary>
  1396. ''' 需要下载的文件。
  1397. ''' </summary>
  1398. Public Files As List(Of NetFile)
  1399. Private ReadOnly FilesLock As New Object
  1400. ''' <summary>
  1401. ''' 剩余未完成的文件数。(用于减轻 FilesLock 的占用)
  1402. ''' </summary>
  1403. Private FileRemain As Integer
  1404. Private ReadOnly FileRemainLock As New Object
  1405. ''' <summary>
  1406. ''' 用于显示的百分比进度。
  1407. ''' </summary>
  1408. Public Overrides Property Progress As Double
  1409. Get
  1410. If State >= LoadState.Finished Then Return 1
  1411. If Files.Count = 0 Then Return 0 '必须返回 0,否则在获取列表的时候会错觉已经下载完了
  1412. Return _Progress
  1413. End Get
  1414. Set(value As Double)
  1415. Throw New Exception("文件下载不允许指定进度")
  1416. End Set
  1417. End Property
  1418. Private _Progress As Double = 0
  1419. ''' <summary>
  1420. ''' 任务中的文件的连续失败计数。
  1421. ''' </summary>
  1422. Public Property FailCount As Integer
  1423. Get
  1424. Return _FailCount
  1425. End Get
  1426. Set(value As Integer)
  1427. _FailCount = value
  1428. If State = LoadState.Loading AndAlso value >= Math.Min(10000, Math.Max(FileRemain * 5.5, NetTaskThreadLimit * 5.5 + 3)) Then
  1429. Log("[Download] 由于同加载器中失败次数过多引发强制失败:连续失败了 " & value & " 次", LogLevel.Debug)
  1430. On Error Resume Next
  1431. Dim ExList As New List(Of Exception)
  1432. SyncLock FilesLock
  1433. For Each File In Files
  1434. For Each Source In File.Sources
  1435. If Source.Ex IsNot Nothing Then
  1436. ExList.Add(Source.Ex)
  1437. If ExList.Count > 10 Then GoTo FinishExCatch
  1438. End If
  1439. Next
  1440. Next
  1441. End SyncLock
  1442. FinishExCatch:
  1443. OnFail(ExList)
  1444. End If
  1445. End Set
  1446. End Property
  1447. Private _FailCount As Integer = 0
  1448. #End Region
  1449. ''' <summary>
  1450. ''' 刷新公开属性。由 NetManager 每 0.2 秒调用一次。
  1451. ''' </summary>
  1452. Public Sub RefreshStat()
  1453. '计算进度
  1454. Dim NewProgress As Double = 0
  1455. Dim TotalProgress As Double = 0
  1456. SyncLock FilesLock
  1457. For Each File In Files
  1458. If File.IsCopy Then
  1459. NewProgress += File.Progress * 0.2
  1460. TotalProgress += 0.2
  1461. Else
  1462. NewProgress += File.Progress '* If(File.Progress < 1, 0.9, 1)
  1463. TotalProgress += 1
  1464. End If
  1465. Next
  1466. End SyncLock
  1467. If TotalProgress > 0 Then NewProgress /= TotalProgress
  1468. '刷新进度
  1469. If NewProgress < 1 AndAlso NewProgress > 0 Then NewProgress = 1 - (1 - NewProgress) ^ 0.9 'MathBezier(NewProgress, 0, 0.05, 1, 0.8, 0.0001)
  1470. _Progress = NewProgress * 0.99 + 0.01
  1471. End Sub
  1472. Public Sub New(Name As String, FileTasks As List(Of NetFile))
  1473. Me.Name = Name
  1474. Files = FileTasks
  1475. End Sub
  1476. Public Overrides Sub Start(Optional Input As Object = Nothing, Optional IsForceRestart As Boolean = False)
  1477. SyncLock FilesLock
  1478. If Input IsNot Nothing Then Files = Input
  1479. '去重
  1480. Dim ResultArray As New List(Of NetFile)
  1481. For i = 0 To Files.Count - 1
  1482. For ii = i + 1 To Files.Count - 1
  1483. If Files(i).LocalPath = Files(ii).LocalPath Then GoTo NextElement
  1484. Next
  1485. ResultArray.Add(Files(i))
  1486. NextElement:
  1487. Next i
  1488. Files = ResultArray
  1489. '设置剩余文件数
  1490. SyncLock FileRemainLock
  1491. For Each File In Files
  1492. If File.State <> NetState.Finish Then FileRemain += 1
  1493. Next
  1494. End SyncLock
  1495. End SyncLock
  1496. State = LoadState.Loading
  1497. '开始执行
  1498. RunInNewThread(Sub()
  1499. Try
  1500. '输入检测
  1501. If Files.Count = 0 Then
  1502. OnFinish()
  1503. Exit Sub
  1504. End If
  1505. For Each File As NetFile In Files
  1506. If File Is Nothing Then Throw New ArgumentException("存在空文件请求!")
  1507. For Each Source As NetSource In File.Sources
  1508. If Not (Source.Url.ToLower.StartsWith("https://") OrElse Source.Url.ToLower.StartsWith("http://")) Then
  1509. Source.Ex = New ArgumentException("输入的下载链接不正确!")
  1510. Source.IsFailed = True
  1511. End If
  1512. Next
  1513. If File.IsSourceFailed() Then Throw New ArgumentException("输入的下载链接不正确!")
  1514. If Not File.LocalPath.ToLower.Contains(":\") Then Throw New ArgumentException("输入的本地文件地址不正确!")
  1515. If File.LocalPath.EndsWith("\") Then Throw New ArgumentException("请输入含文件名的完整文件路径!")
  1516. '文件夹检测
  1517. Dim DirPath As String = New FileInfo(File.LocalPath).Directory.FullName
  1518. If Not Directory.Exists(DirPath) Then Directory.CreateDirectory(DirPath)
  1519. Next
  1520. '接入下载管理器
  1521. NetManager.Start(Me)
  1522. '将文件分配给多个线程以进行已存在查找
  1523. Dim Folders As New List(Of String) '可能会用于已存在查找的文件夹列表
  1524. Dim FoldersFinal As New List(Of String) '最终用于查找的列表
  1525. If Not Setup.Get("SystemDebugSkipCopy") Then '在设置中禁用复制
  1526. Folders.Add(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) & "\.minecraft\") '总是添加官启文件夹,因为 HMCL 会把所有文件存在这里
  1527. For Each Folder In McFolderList
  1528. Folders.Add(Folder.Path)
  1529. Next
  1530. Folders = Folders.Distinct.ToList
  1531. For Each Folder In Folders
  1532. If Folder <> PathMcFolder AndAlso Directory.Exists(Folder) Then FoldersFinal.Add(Folder)
  1533. Next
  1534. End If
  1535. '最多 5 个线程,最少每个线程分配 10 个文件
  1536. SyncLock FilesLock
  1537. Dim FilesPerThread As Integer = Math.Max(5, Files.Count / 10 + 1)
  1538. Dim FilesInThread As New List(Of NetFile)
  1539. For Each File In Files
  1540. FilesInThread.Add(File)
  1541. If FilesInThread.Count = FilesPerThread Then
  1542. Dim FilesToRun As New List(Of NetFile)
  1543. FilesToRun.AddRange(FilesInThread)
  1544. RunInNewThread(Sub() StartCopy(FilesToRun, FoldersFinal), "NetTask FileCopy " & Uuid)
  1545. FilesInThread.Clear()
  1546. End If
  1547. Next
  1548. If FilesInThread.Count > 0 Then
  1549. Dim FilesToRun As New List(Of NetFile)
  1550. FilesToRun.AddRange(FilesInThread)
  1551. RunInNewThread(Sub() StartCopy(FilesToRun, FoldersFinal), "NetTask FileCopy " & Uuid)
  1552. FilesInThread.Clear()
  1553. End If
  1554. End SyncLock
  1555. Catch ex As Exception
  1556. OnFail(New List(Of Exception) From {ex})
  1557. End Try
  1558. End Sub, "NetTask " & Uuid & " Main")
  1559. End Sub
  1560. Private Sub StartCopy(Files As List(Of NetFile), FolderList As List(Of String))
  1561. Try
  1562. If ModeDebug Then Log("[Download] 检查线程分配文件数:" & Files.Count)
  1563. '试图从已存在的 Minecraft 文件夹中寻找目标文件
  1564. Dim ExistFiles As New List(Of KeyValuePair(Of NetFile, String)) '{NetFile, Target As String}
  1565. For Each File As NetFile In Files
  1566. Dim ExistFilePath As String = Nothing
  1567. '判断是否有已存在的文件
  1568. If File.Check IsNot Nothing AndAlso McFolderList IsNot Nothing AndAlso PathMcFolder IsNot Nothing AndAlso File.Check.CanUseExistsFile AndAlso File.LocalPath.StartsWith(PathMcFolder) Then
  1569. Dim Relative = File.LocalPath.Replace(PathMcFolder, "")
  1570. For Each Folder In FolderList
  1571. Dim Target = Folder & Relative
  1572. If File.Check.Check(Target) Is Nothing Then
  1573. ExistFilePath = Target
  1574. Exit For
  1575. End If
  1576. Next
  1577. End If
  1578. '若存在,则改变状态
  1579. SyncLock LockState
  1580. If ExistFilePath IsNot Nothing Then
  1581. File.State = NetState.WaitForCopy
  1582. File.IsCopy = True
  1583. ExistFiles.Add(New KeyValuePair(Of NetFile, String)(File, ExistFilePath))
  1584. Else
  1585. File.State = NetState.WaitForDownload
  1586. File.IsCopy = False
  1587. End If
  1588. End SyncLock
  1589. Next
  1590. '复制已存在的文件
  1591. For Each FileToken In ExistFiles
  1592. Dim File As NetFile = FileToken.Key
  1593. Dim LocalPath As String = FileToken.Value
  1594. Dim RetryCount As Integer = 0
  1595. Retry:
  1596. Try
  1597. Log("[Download] 复制已存在的文件(" & LocalPath & ")")
  1598. CopyFile(LocalPath, File.LocalPath)
  1599. File.Finish(False)
  1600. Catch ex As Exception
  1601. RetryCount += 1
  1602. Log(ex, String.Format("复制已存在的文件失败,重试第 {2} 次({0} -> {1})", LocalPath, File.LocalPath, RetryCount))
  1603. If RetryCount < 3 Then
  1604. Thread.Sleep(200)
  1605. GoTo Retry
  1606. End If
  1607. File.State = NetState.WaitForDownload
  1608. File.IsCopy = False
  1609. End Try
  1610. Next
  1611. Catch ex As Exception
  1612. Log(ex, "下载已存在文件查找失败", LogLevel.Feedback)
  1613. End Try
  1614. End Sub
  1615. Public Sub OnFileFinish(File As NetFile)
  1616. '要求全部文件完成
  1617. SyncLock FileRemainLock
  1618. FileRemain -= 1
  1619. If FileRemain > 0 Then Exit Sub
  1620. End SyncLock
  1621. OnFinish()
  1622. End Sub
  1623. Public Sub OnFinish()
  1624. RaisePreviewFinish()
  1625. SyncLock LockState
  1626. If State > LoadState.Loading Then Exit Sub
  1627. State = LoadState.Finished
  1628. End SyncLock
  1629. End Sub
  1630. Public Sub OnFileFail(File As NetFile)
  1631. '将下载源的错误加入主错误列表
  1632. For Each Source In File.Sources
  1633. If Not IsNothing(Source.Ex) Then File.Ex.Add(Source.Ex)
  1634. Next
  1635. OnFail(File.Ex)
  1636. End Sub
  1637. Public Sub OnFail(ExList As List(Of Exception))
  1638. SyncLock LockState
  1639. If State > LoadState.Loading Then Exit Sub
  1640. If ExList Is Nothing OrElse ExList.Count = 0 Then ExList = New List(Of Exception) From {New Exception("未知错误!")}
  1641. '寻找第一个不是 404 的下载源
  1642. Dim UsefulExs = ExList.Where(Function(e) Not e.Message.Contains("(404)")).ToList
  1643. [Error] = If(UsefulExs.Count > 0, UsefulExs(0), ExList(0))
  1644. '获取实际失败的文件
  1645. SyncLock FilesLock
  1646. For Each File In Files
  1647. If File.State = NetState.Error Then
  1648. [Error] = New Exception("文件下载失败:" & File.LocalPath & vbCrLf & Join(
  1649. File.Sources.Select(Function(s) If(s.Ex Is Nothing, s.Url, s.Ex.Message & "(" & s.Url & ")")).ToList(),
  1650. vbCrLf), [Error])
  1651. Exit For
  1652. End If
  1653. Next
  1654. End SyncLock
  1655. '在设置 Error 对象后再更改为失败,避免 WaitForExit 无法捕获错误
  1656. State = LoadState.Failed
  1657. End SyncLock
  1658. '中断所有文件
  1659. SyncLock FilesLock
  1660. For Each TaskFile In Files
  1661. If TaskFile.State < NetState.Merge Then TaskFile.State = NetState.Error
  1662. Next
  1663. End SyncLock
  1664. '在退出同步锁后再进行日志输出
  1665. Dim ErrOutput As New List(Of String)
  1666. For Each Ex As Exception In ExList
  1667. ErrOutput.Add(GetExceptionDetail(Ex))
  1668. Next
  1669. Log("[Download] " & Join(ErrOutput.Distinct.ToArray, vbCrLf))
  1670. End Sub
  1671. Public Overrides Sub Abort()
  1672. SyncLock LockState
  1673. If State >= LoadState.Finished Then Exit Sub
  1674. State = LoadState.Aborted
  1675. End SyncLock
  1676. Log("[Download] " & Name & " 已取消!")
  1677. '中断所有文件
  1678. SyncLock FilesLock
  1679. For Each TaskFile In Files
  1680. TaskFile.Abort(Me)
  1681. Next
  1682. End SyncLock
  1683. End Sub
  1684. End Class
  1685. Public NetManager As New NetManagerClass
  1686. ''' <summary>
  1687. ''' 下载文件管理。
  1688. ''' </summary>
  1689. Public Class NetManagerClass
  1690. #Region "属性"
  1691. ''' <summary>
  1692. ''' 需要下载的文件。为“本地地址 - 文件对象”键值对。
  1693. ''' </summary>
  1694. Public Files As New Dictionary(Of String, NetFile)
  1695. Public ReadOnly LockFiles As New Object
  1696. ''' <summary>
  1697. ''' 当前的所有下载任务。
  1698. ''' </summary>
  1699. Public Tasks As New List(Of LoaderDownload)
  1700. Private ReadOnly LockTasks As New Object
  1701. ''' <summary>
  1702. ''' 已下载完成的大小。
  1703. ''' </summary>
  1704. Public Property DownloadDone As Long
  1705. Get
  1706. Return _DownloadDone
  1707. End Get
  1708. Set(value As Long)
  1709. SyncLock LockDone
  1710. _DownloadDone = value
  1711. End SyncLock
  1712. End Set
  1713. End Property
  1714. Private _DownloadDone As Long = 0
  1715. Private ReadOnly LockDone As New Object
  1716. ''' <summary>
  1717. ''' 尚未完成下载的文件数。
  1718. ''' </summary>
  1719. Public FileRemain As Integer = 0
  1720. Public ReadOnly LockRemain As New Object
  1721. ''' <summary>
  1722. ''' 上次记速时的已下载大小。
  1723. ''' </summary>
  1724. Private SpeedLastDone As Long = 0
  1725. ''' <summary>
  1726. ''' 最近 10 次下载速度的记录,较新的在后面。间隔为 0.2 秒,故记录了 2 秒的速度。
  1727. ''' </summary>
  1728. Public SpeedLast As New List(Of Long) From {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
  1729. '这些属性由 RefreshStat 刷新
  1730. ''' <summary>
  1731. ''' 当前的全局下载速度,单位为 Byte / 秒。
  1732. ''' </summary>
  1733. Public Speed As Long = 0
  1734. Public ReadOnly Uuid As Integer = GetUuid()
  1735. #End Region
  1736. ''' <summary>
  1737. ''' 进度与下载速度由下载管理线程每隔约 0.2 秒刷新一次。
  1738. ''' </summary>
  1739. Private Sub RefreshStat()
  1740. Try
  1741. Dim DeltaTime As Long = GetTimeTick() - RefreshStatLast
  1742. RefreshStatLast += DeltaTime
  1743. #Region "刷新整体速度"
  1744. '计算即时速度
  1745. Dim ActualSpeed As Double = Math.Max(0, (DownloadDone - SpeedLastDone) / (DeltaTime / 1000))
  1746. SpeedLast.Add(ActualSpeed)
  1747. SpeedLast.RemoveAt(0)
  1748. SpeedLastDone = DownloadDone
  1749. '计算用于显示的速度
  1750. 'If SpeedLast(9) = 0 Then
  1751. ' Speed = 0
  1752. 'Else
  1753. 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
  1754. 'End If
  1755. '计算新的速度下限
  1756. SpeedLast.Add(ActualSpeed)
  1757. SpeedLast.RemoveAt(0)
  1758. Dim Limit As Long = Math.Min(Math.Min(Math.Min(Math.Min(SpeedLast(5), SpeedLast(6)), SpeedLast(7)), SpeedLast(8)), SpeedLast(9)) * 0.9
  1759. If Limit > NetTaskSpeedLimitLow Then
  1760. NetTaskSpeedLimitLow = Limit
  1761. Log("[Download] " & "速度下限已提升到 " & GetString(Limit))
  1762. End If
  1763. #End Region
  1764. #Region "刷新下载任务属性"
  1765. SyncLock LockTasks
  1766. For Each Task In Tasks
  1767. Task.RefreshStat()
  1768. Next
  1769. End SyncLock
  1770. #End Region
  1771. Catch ex As Exception
  1772. Log(ex, "刷新下载公开属性失败")
  1773. End Try
  1774. End Sub
  1775. Private RefreshStatLast As Long
  1776. ''' <summary>
  1777. ''' 启动监控线程,用于新增下载线程。
  1778. ''' </summary>
  1779. Private Sub StartManager()
  1780. If IsManagerStarted Then Exit Sub
  1781. IsManagerStarted = True
  1782. RunInNewThread(
  1783. 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. '等待 40 ms:BMCLAPI 部分时候有 20QPS 的限制
  1836. Thread.Sleep(40)
  1837. Loop While NewThreadCount > 0 AndAlso IsSuccess
  1838. End If
  1839. '等待 40 ms
  1840. Thread.Sleep(40)
  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