ModMod.vb 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903
  1. Imports System.IO.Compression
  2. Public Module ModMod
  3. Public Class McMod
  4. #Region "基础"
  5. ''' <summary>
  6. ''' Mod 文件的地址。
  7. ''' </summary>
  8. Public ReadOnly Path As String
  9. Public Sub New(Path As String)
  10. Me.Path = If(Path, "")
  11. End Sub
  12. ''' <summary>
  13. ''' Mod 的完整文件名。
  14. ''' </summary>
  15. Public ReadOnly Property FileName As String
  16. Get
  17. Return GetFileNameFromPath(Path)
  18. End Get
  19. End Property
  20. ''' <summary>
  21. ''' Mod 的完整文件名,去除最后的 .disabled。
  22. ''' </summary>
  23. Public ReadOnly Property RawFileName As String
  24. Get
  25. Return FileName.Replace(".disabled", "")
  26. End Get
  27. End Property
  28. ''' <summary>
  29. ''' Mod 的状态。
  30. ''' </summary>
  31. Public ReadOnly Property State As McModState
  32. Get
  33. Load()
  34. If Not IsFileAvailable Then
  35. Return McModState.Unavaliable
  36. ElseIf Path.EndsWith(".disabled") Then
  37. Return McModState.Disabled
  38. Else
  39. Return McModState.Fine
  40. End If
  41. End Get
  42. End Property
  43. Public Enum McModState As Integer
  44. Fine = 0
  45. Disabled = 1
  46. Unavaliable = 2
  47. End Enum
  48. #End Region
  49. #Region "信息项"
  50. ''' <summary>
  51. ''' Mod 的名称。若不可用则为 ModID 或无扩展的文件名。
  52. ''' </summary>
  53. Public Property Name As String
  54. Get
  55. If _Name Is Nothing Then Load()
  56. If _Name Is Nothing Then _Name = _ModId
  57. If _Name Is Nothing Then _Name = GetFileNameWithoutExtentionFromPath(Path)
  58. Return _Name
  59. End Get
  60. Set(value As String)
  61. If _Name Is Nothing AndAlso value IsNot Nothing AndAlso
  62. value.ToLower <> "name" AndAlso value.Count > 1 AndAlso Val(value).ToString <> value Then
  63. _Name = value
  64. End If
  65. End Set
  66. End Property
  67. Private _Name As String = Nothing
  68. ''' <summary>
  69. ''' Mod 的描述信息。
  70. ''' </summary>
  71. Public Property Description As String
  72. Get
  73. If _Description Is Nothing Then Load()
  74. If _Description Is Nothing AndAlso FileUnavailableReason IsNot Nothing Then _Description = FileUnavailableReason.Message
  75. 'If _Description Is Nothing Then _Description = Path
  76. Return _Description
  77. End Get
  78. Set(value As String)
  79. If _Description Is Nothing AndAlso value IsNot Nothing AndAlso value.Count > 2 Then
  80. _Description = value.ToString.Trim(vbLf)
  81. '优化显示:若以 [a-zA-Z0-9] 结尾,加上小数点句号
  82. If _Description.ToLower.LastIndexOfAny("qwertyuiopasdfghjklzxcvbnm0123456789") = _Description.Count - 1 Then _Description += "."
  83. End If
  84. End Set
  85. End Property
  86. Private _Description As String = Nothing
  87. ''' <summary>
  88. ''' Mod 的版本,不保证符合版本格式规范。
  89. ''' </summary>
  90. Public Property Version As String
  91. Get
  92. If _Version Is Nothing Then Load()
  93. Return _Version
  94. End Get
  95. Set(value As String)
  96. If _Version IsNot Nothing AndAlso (_Version.Contains(".") OrElse _Version.Contains("-")) Then Exit Property
  97. If value IsNot Nothing AndAlso value.ToLower.Contains("version") Then value = "version" '需要修改的标识
  98. _Version = value
  99. End Set
  100. End Property
  101. Private _Version As String = Nothing
  102. ''' <summary>
  103. ''' 用于依赖检查的 ModID。
  104. ''' </summary>
  105. Public Property ModId As String
  106. Get
  107. If _ModId Is Nothing Then Load()
  108. Return _ModId
  109. End Get
  110. Set(value As String)
  111. If value Is Nothing Then Exit Property
  112. value = RegexSeek(value.ToLower, "[0-9a-z_-]+")
  113. If value IsNot Nothing AndAlso value.ToLower <> "name" AndAlso value.Count > 1 AndAlso Val(value).ToString <> value Then
  114. If Not PossibleModId.Contains(value) Then PossibleModId.Add(value)
  115. If _ModId Is Nothing Then _ModId = value
  116. End If
  117. End Set
  118. End Property
  119. Private _ModId As String = Nothing
  120. ''' <summary>
  121. ''' 其他可能的 ModID。
  122. ''' </summary>
  123. Public PossibleModId As New List(Of String)
  124. ''' <summary>
  125. ''' Mod 的主页。
  126. ''' </summary>
  127. Public Property Url As String
  128. Get
  129. If _Url Is Nothing Then Load()
  130. Return _Url
  131. End Get
  132. Set(value As String)
  133. If _Url Is Nothing AndAlso value IsNot Nothing AndAlso value.StartsWith("http") Then
  134. _Url = value
  135. End If
  136. End Set
  137. End Property
  138. Private _Url As String = Nothing
  139. ''' <summary>
  140. ''' Mod 的作者列表。
  141. ''' </summary>
  142. Public Property Authors As String
  143. Get
  144. If _Authors Is Nothing Then Load()
  145. Return _Authors
  146. End Get
  147. Set(value As String)
  148. If _Authors Is Nothing AndAlso Not String.IsNullOrWhiteSpace(value) Then
  149. _Authors = value
  150. End If
  151. End Set
  152. End Property
  153. Private _Authors As String = Nothing
  154. ''' <summary>
  155. ''' 依赖项,其中包括了 Minecraft 的版本要求。格式为 ModID - VersionRequirement,若无版本要求则为 Nothing。
  156. ''' </summary>
  157. Public ReadOnly Property Dependencies As Dictionary(Of String, String)
  158. Get
  159. Load()
  160. Return _Dependencies
  161. End Get
  162. End Property
  163. Private _Dependencies As New Dictionary(Of String, String)
  164. Private Sub AddDependency(ModID As String, Optional VersionRequirement As String = Nothing)
  165. '确保信息正确
  166. If ModID Is Nothing OrElse ModID.Count < 2 Then Exit Sub
  167. ModID = ModID.ToLower
  168. If ModID = "name" OrElse Val(ModID).ToString = ModID Then Exit Sub '跳过 name 与纯数字 id
  169. If VersionRequirement Is Nothing OrElse ((Not VersionRequirement.Contains(".")) AndAlso (Not VersionRequirement.Contains("-"))) OrElse VersionRequirement.Contains("$") Then
  170. VersionRequirement = Nothing
  171. Else
  172. If (Not VersionRequirement.StartsWith("[")) AndAlso (Not VersionRequirement.StartsWith("(")) AndAlso (Not VersionRequirement.EndsWith("]")) AndAlso (Not VersionRequirement.EndsWith(")")) Then VersionRequirement = "[" & VersionRequirement & ",)"
  173. End If
  174. '向依赖项中添加
  175. If _Dependencies.ContainsKey(ModID) Then
  176. If _Dependencies(ModID) Is Nothing Then _Dependencies(ModID) = VersionRequirement
  177. Else
  178. _Dependencies.Add(ModID, VersionRequirement)
  179. End If
  180. End Sub
  181. #End Region
  182. #Region "加载步骤标记"
  183. '1. 进行文件可用性检查
  184. ' 成功:继续第二步。
  185. ' 失败:标记 FileUnavailableReason, 并停止后续加载。
  186. ''' <summary>
  187. ''' 是否已进行 Mod 文件的基础加载。(这包括第一步和第二步)
  188. ''' </summary>
  189. Private IsLoaded As Boolean = False
  190. ''' <summary>
  191. ''' Mod 文件是否可被正常读取。
  192. ''' </summary>
  193. Public ReadOnly Property IsFileAvailable As Boolean
  194. Get
  195. Load()
  196. Return FileUnavailableReason Is Nothing
  197. End Get
  198. End Property
  199. ''' <summary>
  200. ''' Mod 文件出错的原因。若无错误,则为 Nothing。
  201. ''' </summary>
  202. Public ReadOnly Property FileUnavailableReason As Exception
  203. Get
  204. Load()
  205. Return _FileUnavailableReason
  206. End Get
  207. End Property
  208. Private _FileUnavailableReason As Exception = Nothing
  209. '2. 进行 .class 以外的信息获取
  210. ' 成功:标记 IsInfoWithoutClassAvailable。
  211. ' 失败:什么也不干。如果需要补充信息的话,检测到 IsInfoWithoutClassAvailable 为 False,会自动继续加载。
  212. ''' <summary>
  213. ''' 是否已在不获取 .class 文件的前提下完成了所需信息的加载。
  214. ''' </summary>
  215. Private IsInfoWithoutClassAvailable As Boolean = False
  216. '3. 尝试从 .class 文件中获取信息
  217. ' 成功:标记 IsInfoWithClassAvailable。
  218. ' 失败:什么也不干。
  219. ''' <summary>
  220. ''' 是否已进行 .class 文件的信息获取。
  221. ''' </summary>
  222. Private IsInfoWithClassLoaded As Boolean = False
  223. ''' <summary>
  224. ''' 是否已在 .class 文件中完成了所需信息的加载。
  225. ''' </summary>
  226. Private IsInfoWithClassAvailable As Boolean = False
  227. #End Region
  228. #Region "加载"
  229. ''' <summary>
  230. ''' 初始化所有数据。
  231. ''' </summary>
  232. Private Sub Init()
  233. _Name = Nothing
  234. _Description = Nothing
  235. _Version = Nothing
  236. _ModId = Nothing
  237. PossibleModId = New List(Of String)
  238. _Dependencies = New Dictionary(Of String, String)
  239. IsLoaded = False
  240. _FileUnavailableReason = Nothing
  241. IsInfoWithoutClassAvailable = False
  242. IsInfoWithClassLoaded = False
  243. IsInfoWithClassAvailable = False
  244. End Sub
  245. ''' <summary>
  246. ''' 进行文件可用性检查与 .class 以外的信息获取。
  247. ''' </summary>
  248. Public Sub Load(Optional ForceReload As Boolean = False)
  249. If IsLoaded AndAlso Not ForceReload Then Exit Sub
  250. '初始化
  251. Init()
  252. '阶段 1:基础可用性检查
  253. Dim Jar As ZipArchive
  254. Try
  255. '打开 Jar 文件
  256. If Path.Length < 2 Then Throw New FileNotFoundException("错误的 Mod 文件路径(" & If(Path, "null") & ")")
  257. If Not File.Exists(Path) Then Throw New FileNotFoundException("未找到 Mod 文件(" & Path & ")")
  258. Jar = New ZipArchive(New FileStream(Path, FileMode.Open))
  259. If Jar.Entries.Count = 0 Then Throw New FileFormatException("文件内容为空")
  260. Catch ex As UnauthorizedAccessException
  261. Log(ex, "Mod 文件由于无权限无法打开(" & Path & ")", LogLevel.Developer)
  262. _FileUnavailableReason = New UnauthorizedAccessException("没有读取此文件的权限,请尝试右键以管理员身份运行 PCL", ex)
  263. Jar = Nothing
  264. Catch ex As Exception
  265. Log(ex, "Mod 文件无法打开(" & Path & ")", LogLevel.Developer)
  266. _FileUnavailableReason = ex
  267. Jar = Nothing
  268. End Try
  269. '阶段 2:信息获取
  270. If Jar IsNot Nothing Then LoadWithoutClass(Jar)
  271. '阶段 3: Class 信息获取
  272. If Jar IsNot Nothing AndAlso Not IsInfoWithoutClassAvailable Then LoadWithClass(Jar)
  273. '释放文件
  274. Try
  275. If Jar IsNot Nothing Then Jar.Dispose()
  276. Catch
  277. End Try
  278. '完成标记
  279. IsLoaded = True
  280. End Sub
  281. ''' <summary>
  282. ''' 进行不使用 .class 文件的信息获取。
  283. ''' </summary>
  284. Private Sub LoadWithoutClass(Jar As ZipArchive)
  285. #Region "尝试使用 mcmod.info"
  286. Try
  287. '获取信息文件
  288. Dim InfoEntry As ZipArchiveEntry = Jar.GetEntry("mcmod.info")
  289. Dim InfoString As String = Nothing
  290. If InfoEntry IsNot Nothing Then
  291. InfoString = ReadFile(InfoEntry.Open())
  292. If InfoString.Length < 15 Then InfoString = Nothing
  293. End If
  294. If InfoString Is Nothing Then Exit Try
  295. '获取可用 Json 项
  296. Dim InfoObject As JObject
  297. Dim JsonObject = GetJson(InfoString)
  298. If JsonObject.Type = JTokenType.Array Then
  299. InfoObject = JsonObject(0)
  300. Else
  301. InfoObject = JsonObject("modList")(0)
  302. End If
  303. '从文件中获取 Mod 信息项
  304. Name = InfoObject("name")
  305. Description = InfoObject("description")
  306. Version = InfoObject("version")
  307. Url = InfoObject("url")
  308. ModId = InfoObject("modid")
  309. Dim AuthorJson As JArray = InfoObject("authorList")
  310. If AuthorJson IsNot Nothing Then
  311. Dim Author As New List(Of String)
  312. For Each Token In AuthorJson
  313. Author.Add(Token.ToString)
  314. Next
  315. If Author.Count > 0 Then Authors = Join(Author, ", ")
  316. End If
  317. Dim Reqs As JArray = InfoObject("requiredMods")
  318. If Reqs IsNot Nothing Then
  319. For Each Token As String In Reqs
  320. If Not String.IsNullOrEmpty(Token) Then
  321. Token = Token.Substring(Token.IndexOf(":") + 1)
  322. If Token.Contains("@") Then
  323. AddDependency(Token.Split("@")(0), Token.Split("@")(1))
  324. Else
  325. AddDependency(Token)
  326. End If
  327. End If
  328. Next
  329. End If
  330. Reqs = InfoObject("dependancies")
  331. If Reqs IsNot Nothing Then
  332. For Each Token As String In Reqs
  333. If Not String.IsNullOrEmpty(Token) Then
  334. Token = Token.Substring(Token.IndexOf(":") + 1)
  335. If Token.Contains("@") Then
  336. AddDependency(Token.Split("@")(0), Token.Split("@")(1))
  337. Else
  338. AddDependency(Token)
  339. End If
  340. End If
  341. Next
  342. End If
  343. Catch ex As Exception
  344. Log(ex, "读取 mcmod.info 时出现未知错误(" & Path & ")", LogLevel.Developer)
  345. End Try
  346. #End Region
  347. #Region "尝试使用 mods.toml"
  348. Try
  349. '获取 mods.toml 文件
  350. Dim TomlEntry As ZipArchiveEntry = Jar.GetEntry("META-INF/mods.toml")
  351. Dim TomlText As String = Nothing
  352. If TomlEntry IsNot Nothing Then
  353. TomlText = ReadFile(TomlEntry.Open())
  354. If TomlText.Length < 15 Then TomlText = Nothing
  355. End If
  356. If TomlText Is Nothing Then Exit Try
  357. '文件标准化:统一换行符为 vbLf,去除注释、头尾的空格、空行
  358. Dim Lines As New List(Of String)
  359. For Each Line In TomlText.Replace(vbCrLf, vbLf).Replace(vbCr, vbLf).Split(vbLf) '统一换行符
  360. If Line.StartsWith("#") Then '去除注释
  361. Continue For
  362. ElseIf Line.Contains("#") Then
  363. Line = Line.Substring(0, Line.IndexOf("#"))
  364. End If
  365. Line = Line.Trim(New Char() {" "c, " "c, " "c}) '去除头尾的空格
  366. If Line.Count > 0 Then Lines.Add(Line) '去除空行
  367. Next
  368. '读取文件数据
  369. Dim TomlData As New List(Of KeyValuePair(Of String, Dictionary(Of String, Object))) From {New KeyValuePair(Of String, Dictionary(Of String, Object))("", New Dictionary(Of String, Object))}
  370. For i = 0 To Lines.Count - 1
  371. Dim Line As String = Lines(i)
  372. If Line.StartsWith("[") AndAlso Line.EndsWith("]") Then
  373. '段落标记
  374. Dim Header = Line.Trim("[]".ToCharArray)
  375. TomlData.Add(New KeyValuePair(Of String, Dictionary(Of String, Object))(Header, New Dictionary(Of String, Object)))
  376. ElseIf Line.Contains("=") Then
  377. '字段标记
  378. Dim Key As String = Line.Substring(0, Line.IndexOf("=")).TrimEnd(New Char() {" "c, " "c, " "c})
  379. Dim RawValue As String = Line.Substring(Line.IndexOf("=") + 1).TrimStart(New Char() {" "c, " "c, " "c})
  380. Dim Value As Object
  381. If RawValue.StartsWith("""") AndAlso RawValue.EndsWith("""") Then
  382. '单行字符串
  383. Value = RawValue.Trim("""")
  384. ElseIf RawValue.StartsWith("'''") Then
  385. '多行字符串
  386. Dim ValueLines As New List(Of String) From {RawValue.TrimStart("'")}
  387. Do Until i >= Lines.Count - 1
  388. i += 1
  389. Dim ValueLine As String = Lines(i)
  390. If ValueLine.EndsWith("'''") Then
  391. ValueLines.Add(ValueLine.TrimEnd("'"))
  392. Exit Do
  393. Else
  394. ValueLines.Add(ValueLine)
  395. End If
  396. Loop
  397. Value = Join(ValueLines, vbLf).Trim(vbLf).Replace(vbLf, vbCrLf)
  398. ElseIf RawValue.ToLower = "true" OrElse RawValue.ToLower = "false" Then
  399. '布尔型
  400. Value = (RawValue.ToLower = "true")
  401. ElseIf Val(RawValue).ToString = RawValue Then
  402. '数字型
  403. Value = Val(RawValue)
  404. Else
  405. '不知道是个啥玩意儿,直接存储
  406. Value = RawValue
  407. End If
  408. TomlData.Last.Value(Key) = Value
  409. Else
  410. '不知道是个啥玩意儿
  411. Exit Try
  412. End If
  413. Next
  414. '从文件数据中获取信息
  415. Dim ModEntry As Dictionary(Of String, Object) = Nothing
  416. For Each TomlSubData In TomlData
  417. If TomlSubData.Key = "mods" Then
  418. ModEntry = TomlSubData.Value
  419. Exit For
  420. End If
  421. Next
  422. If ModEntry Is Nothing OrElse Not ModEntry.ContainsKey("modId") Then Exit Try
  423. ModId = ModEntry("modId")
  424. If _ModId Is Nothing Then Exit Try '设置了无效的 ModID
  425. If ModEntry.ContainsKey("displayName") Then Name = ModEntry("displayName")
  426. If ModEntry.ContainsKey("description") Then Description = ModEntry("description")
  427. If ModEntry.ContainsKey("version") Then Version = ModEntry("version")
  428. If TomlData(0).Value.ContainsKey("displayURL") Then Url = TomlData(0).Value("displayURL")
  429. If TomlData(0).Value.ContainsKey("authors") Then Authors = TomlData(0).Value("authors")
  430. For Each TomlSubData In TomlData
  431. If TomlSubData.Key.ToLower = $"dependencies.{ModId.ToLower}" Then
  432. Dim DepEntry As Dictionary(Of String, Object) = TomlSubData.Value
  433. If DepEntry.ContainsKey("modId") AndAlso DepEntry.ContainsKey("mandatory") AndAlso DepEntry("mandatory") AndAlso
  434. DepEntry.ContainsKey("side") AndAlso Not DepEntry("side").ToString.ToLower = "server" Then
  435. AddDependency(DepEntry("modId"), If(DepEntry.ContainsKey("versionRange"), DepEntry("versionRange"), Nothing))
  436. End If
  437. End If
  438. Next
  439. '加载成功
  440. GoTo Finished
  441. Catch ex As Exception
  442. Log(ex, "读取 mods.toml 时出现未知错误(" & Path & ")", LogLevel.Developer)
  443. End Try
  444. #End Region
  445. #Region "尝试使用 fabric.mod.json"
  446. Try
  447. '获取 fabric.mod.json 文件
  448. Dim FabricEntry As ZipArchiveEntry = Jar.GetEntry("fabric.mod.json")
  449. Dim FabricText As String = Nothing
  450. If FabricEntry IsNot Nothing Then
  451. FabricText = ReadFile(FabricEntry.Open(), Encoding.UTF8)
  452. If Not FabricText.Contains("schemaVersion") Then FabricText = Nothing
  453. End If
  454. If FabricText Is Nothing Then Exit Try
  455. Dim FabricObject As JObject = GetJson(FabricText)
  456. GotFabric:
  457. '从文件中获取 Mod 信息项
  458. If FabricObject.ContainsKey("name") Then Name = FabricObject("name")
  459. If FabricObject.ContainsKey("version") Then Version = FabricObject("version")
  460. If FabricObject.ContainsKey("description") Then Description = FabricObject("description")
  461. If FabricObject.ContainsKey("id") Then ModId = FabricObject("id")
  462. If FabricObject.ContainsKey("contact") Then Url = If(FabricObject("contact")("homepage"), "")
  463. Dim AuthorJson As JArray = FabricObject("authors")
  464. If AuthorJson IsNot Nothing Then
  465. Dim Author As New List(Of String)
  466. For Each Token In AuthorJson
  467. Author.Add(Token.ToString)
  468. Next
  469. If Author.Count > 0 Then Authors = Join(Author, ", ")
  470. End If
  471. 'If (Not FabricObject.ContainsKey("serverSideOnly")) OrElse FabricObject("serverSideOnly")("value").ToObject(Of Boolean) = False Then
  472. ' '添加 Minecraft 依赖
  473. ' Dim DepMinecraft As String = If(If(FabricObject("acceptedMinecraftVersions") IsNot Nothing, FabricObject("acceptedMinecraftVersions")("value"), ""), "")
  474. ' If DepMinecraft <> "" Then AddDependency("minecraft", DepMinecraft)
  475. ' '添加其他依赖
  476. ' Dim Deps As String = If(If(FabricObject("dependencies") IsNot Nothing, FabricObject("dependencies")("value"), ""), "")
  477. ' If Deps <> "" Then
  478. ' For Each Dep In Deps.Split(";")
  479. ' If Dep = "" OrElse Not Dep.StartsWith("required-") Then Continue For
  480. ' Dep = Dep.Substring(Dep.IndexOf(":") + 1)
  481. ' If Dep.Contains("@") Then
  482. ' AddDependency(Dep.Split("@")(0), Dep.Split("@")(1))
  483. ' Else
  484. ' AddDependency(Dep)
  485. ' End If
  486. ' Next
  487. ' End If
  488. 'End If
  489. '加载成功
  490. GoTo Finished
  491. Catch ex As Exception
  492. Log(ex, "读取 fabric.mod.json 时出现未知错误(" & Path & ")", LogLevel.Developer)
  493. End Try
  494. #End Region
  495. #Region "尝试使用 fml_cache_annotation.json"
  496. Try
  497. '获取 fml_cache_annotation.json 文件
  498. Dim FmlEntry As ZipArchiveEntry = Jar.GetEntry("META-INF/fml_cache_annotation.json")
  499. Dim FmlText As String = Nothing
  500. If FmlEntry IsNot Nothing Then
  501. FmlText = ReadFile(FmlEntry.Open(), Encoding.UTF8)
  502. If Not FmlText.Contains("Lnet/minecraftforge/fml/common/Mod;") Then FmlText = Nothing
  503. End If
  504. If FmlText Is Nothing Then Exit Try
  505. Dim FmlJson As JObject = GetJson(FmlText)
  506. '获取可用 Json 项
  507. Dim FmlObject As JObject = Nothing
  508. For Each ModFilePair In FmlJson
  509. Dim ModFileAnnos As JArray = ModFilePair.Value("annotations")
  510. If ModFileAnnos IsNot Nothing Then
  511. '先获取 Mod
  512. For Each ModFileAnno In ModFileAnnos
  513. Dim Name As String = If(ModFileAnno("name"), "")
  514. If Name = "Lnet/minecraftforge/fml/common/Mod;" Then
  515. FmlObject = ModFileAnno("values")
  516. GoTo Got
  517. End If
  518. Next
  519. End If
  520. Next
  521. Exit Try
  522. Got:
  523. '从文件中获取 Mod 信息项
  524. If FmlObject.ContainsKey("useMetadata") AndAlso If(FmlObject("useMetadata")("value"), "").ToString.ToLower = "true" Then
  525. '要求使用 mcmod.info 中的信息
  526. Dim value As String = FmlObject("modid")("value")
  527. If value Is Nothing Then Exit Try
  528. value = RegexSeek(value.ToLower, "[0-9a-z_]+")
  529. If value IsNot Nothing AndAlso value.ToLower <> "name" AndAlso value.Count > 1 AndAlso Val(value).ToString <> value Then
  530. If Not PossibleModId.Contains(value) Then PossibleModId.Add(value)
  531. End If
  532. Exit Try
  533. End If
  534. If FmlObject.ContainsKey("name") Then Name = FmlObject("name")("value")
  535. If FmlObject.ContainsKey("version") Then Version = FmlObject("version")("value")
  536. If FmlObject.ContainsKey("modid") Then ModId = FmlObject("modid")("value")
  537. If (Not FmlObject.ContainsKey("serverSideOnly")) OrElse FmlObject("serverSideOnly")("value").ToObject(Of Boolean) = False Then
  538. '添加 Minecraft 依赖
  539. Dim DepMinecraft As String = If(If(FmlObject("acceptedMinecraftVersions") IsNot Nothing, FmlObject("acceptedMinecraftVersions")("value"), ""), "")
  540. If DepMinecraft <> "" Then AddDependency("minecraft", DepMinecraft)
  541. '添加其他依赖
  542. Dim Deps As String = If(If(FmlObject("dependencies") IsNot Nothing, FmlObject("dependencies")("value"), ""), "")
  543. If Deps <> "" Then
  544. For Each Dep In Deps.Split(";")
  545. If Dep = "" OrElse Not Dep.StartsWith("required-") Then Continue For
  546. Dep = Dep.Substring(Dep.IndexOf(":") + 1)
  547. If Dep.Contains("@") Then
  548. AddDependency(Dep.Split("@")(0), Dep.Split("@")(1))
  549. Else
  550. AddDependency(Dep)
  551. End If
  552. Next
  553. End If
  554. End If
  555. Catch ex As Exception
  556. Log(ex, "读取 fml_cache_annotation.json 时出现未知错误(" & Path & ")", LogLevel.Developer)
  557. End Try
  558. #End Region
  559. Finished:
  560. #Region "将 Version 代号转换为 META-INF 中的版本"
  561. If _Version = "version" Then
  562. Try
  563. Dim MetaEntry As ZipArchiveEntry = Jar.GetEntry("META-INF/MANIFEST.MF")
  564. If MetaEntry IsNot Nothing Then
  565. Dim MetaString As String = ReadFile(MetaEntry.Open()).Replace(" :", ":").Replace(": ", ":")
  566. If MetaString.Contains("Implementation-Version:") Then
  567. MetaString = MetaString.Substring(MetaString.IndexOf("Implementation-Version:") + "Implementation-Version:".Count)
  568. MetaString = MetaString.Substring(0, MetaString.IndexOfAny(vbCrLf.ToCharArray)).Trim
  569. Version = MetaString
  570. End If
  571. End If
  572. Catch ex As Exception
  573. Log("获取 META-INF 中的版本信息失败(" & Path & ")", LogLevel.Developer)
  574. Version = Nothing
  575. End Try
  576. End If
  577. If _Version IsNot Nothing AndAlso Not (_Version.Contains(".") OrElse _Version.Contains("-")) Then Version = Nothing
  578. #End Region
  579. IsInfoWithoutClassAvailable = _ModId IsNot Nothing AndAlso _Version IsNot Nothing
  580. End Sub
  581. ''' <summary>
  582. ''' 进行使用 .class 文件的信息获取。
  583. ''' </summary>
  584. Private Sub LoadWithClass(Jar As ZipArchive)
  585. Try
  586. '查找入口点文件
  587. Dim ModClass As String = Nothing
  588. Dim ModClassNotBest As String = Nothing '非完美匹配
  589. For Each Entry In Jar.Entries
  590. If Entry.Name.EndsWith(".class") Then
  591. Dim Temp As String = ReadFile(Entry.Open()).ToLower
  592. If Temp.Contains("#lnet/minecraftforge/fml/common/mod;") Then
  593. ModClass = Temp
  594. Exit For
  595. ElseIf Temp.Contains("modid") Then
  596. ModClassNotBest = Temp
  597. End If
  598. End If
  599. Next
  600. If ModClass Is Nothing Then ModClass = ModClassNotBest
  601. If ModClass Is Nothing Then Throw New FileNotFoundException("未找到 Mod 入口点")
  602. ModClass = ModClass.Replace("ljava/lang/string;", "")
  603. If ModClass.Count > 3000 Then ModClass = ModClass.Substring(0, 3000) '如果文件过大,截取前 3000 Byte
  604. Dim IndexHead As Integer, IndexTail As Integer, IncreaseCount As Integer
  605. '获取 ModID
  606. If _ModId Is Nothing Then
  607. IndexHead = ModClass.IndexOf("modid") + "modid".Length + 1
  608. IncreaseCount = 0
  609. Do While Convert.ToInt32(ModClass(IndexHead)) < 32
  610. IndexHead += 1
  611. IncreaseCount += 1
  612. If IncreaseCount > 10 Then Throw New Exception("ModID 头匹配失败")
  613. Loop
  614. IndexTail = IndexHead + 1
  615. IncreaseCount = 0
  616. Do Until Convert.ToInt32(ModClass(IndexTail)) < 32
  617. IndexTail += 1
  618. IncreaseCount += 1
  619. If IncreaseCount > 50 Then Throw New Exception("ModID 尾匹配失败")
  620. Loop
  621. ModId = ModClass.Substring(IndexHead, IndexTail - IndexHead)
  622. End If
  623. '获取 Version
  624. If _Version Is Nothing AndAlso ModClass.Contains("version") Then
  625. IndexHead = ModClass.IndexOf("version") + "version".Length + 1
  626. IncreaseCount = 0
  627. Do While Convert.ToInt32(ModClass(IndexHead)) < 32
  628. IndexHead += 1
  629. IncreaseCount += 1
  630. If IncreaseCount > 10 Then GoTo VersionFindFail
  631. Loop
  632. IndexTail = IndexHead + 1
  633. IncreaseCount = 0
  634. Do While ModClass(IndexTail) = "."c OrElse ModClass(IndexTail) = "-"c OrElse
  635. (ModClass(IndexTail) >= "0"c AndAlso ModClass(IndexTail) <= "9"c) OrElse
  636. (ModClass(IndexTail) >= "a"c AndAlso ModClass(IndexTail) <= "z"c)
  637. IndexTail += 1
  638. IncreaseCount += 1
  639. If IncreaseCount > 50 Then GoTo VersionFindFail
  640. Loop
  641. _Version = ModClass.Substring(IndexHead, IndexTail - IndexHead)
  642. End If
  643. VersionFindFail:
  644. '获取 Dependencies
  645. IndexHead = ModClass.IndexOf("dependencies")
  646. If IndexHead > 0 Then
  647. If ModClass.Count >= IndexHead + 300 Then ModClass = ModClass.Substring(IndexHead, 299)
  648. Dim Deps As List(Of String) = RegexSearch(ModClass, "(?<=required-((before|after|before-client|after-client)?):)[0-9a-z]+(@[\(\[]{1}[0-9.,]+[\)\]]{1})?")
  649. For Each Token As String In Deps
  650. If Not String.IsNullOrEmpty(Token) Then
  651. If Token.Contains("@") Then
  652. AddDependency(Token.Split("@")(0), Token.Split("@")(1))
  653. Else
  654. AddDependency(Token)
  655. End If
  656. End If
  657. Next
  658. End If
  659. Catch ex As Exception
  660. Log(ex, "Mod Class 信息不可用(" & If(Path, "null") & ")", LogLevel.Normal)
  661. End Try
  662. IsInfoWithClassAvailable = _ModId IsNot Nothing AndAlso _Version IsNot Nothing
  663. End Sub
  664. #End Region
  665. ''' <summary>
  666. ''' 是否可能为前置 Mod。
  667. ''' </summary>
  668. Public Function IsPresetMod() As Boolean
  669. Return Dependencies.Count = 0 AndAlso (Name IsNot Nothing) AndAlso (Name.ToLower.Contains("core") OrElse Name.ToLower.Contains("lib"))
  670. End Function
  671. ''' <summary>
  672. ''' 根据完整文件路径的文件扩展名判断是否为 Mod 文件。
  673. ''' </summary>
  674. Public Shared Function IsModFile(Path As String)
  675. If Path Is Nothing OrElse Not Path.Contains(".") Then Return False
  676. Path = Path.ToLower
  677. If Path.EndsWith(".jar") OrElse Path.EndsWith(".zip") OrElse Path.EndsWith(".litemod") OrElse
  678. Path.EndsWith(".jar.disabled") OrElse Path.EndsWith(".zip.disabled") OrElse Path.EndsWith(".litemod.disabled") Then Return True
  679. Return False
  680. End Function
  681. End Class
  682. '加载 Mod 列表
  683. Public McModLoader As New LoaderTask(Of String, List(Of McMod))("Mod List Loader", AddressOf McModLoad)
  684. Private Sub McModLoad(Loader As LoaderTask(Of String, List(Of McMod)))
  685. Try
  686. RunInUiWait(Sub() If FrmVersionMod IsNot Nothing Then FrmVersionMod.Load.ShowProgress = False)
  687. '获取 Mod 文件夹下的可用文件列表
  688. Dim ModFileList As New List(Of FileInfo)
  689. If Directory.Exists(Loader.Input) Then
  690. Dim RawName As String = Loader.Input.ToLower
  691. For Each File As FileInfo In EnumerateFiles(Loader.Input)
  692. If File.DirectoryName.ToLower & "\" <> RawName Then
  693. '仅当 Forge 1.13- 且文件夹名与版本号相同时,才加载该子文件夹下的 Mod
  694. If Not (PageVersionLeft.Version IsNot Nothing AndAlso PageVersionLeft.Version.Version.HasForge AndAlso
  695. PageVersionLeft.Version.Version.McCodeMain < 13 AndAlso
  696. File.Directory.Name = "1." & PageVersionLeft.Version.Version.McCodeMain & "." & PageVersionLeft.Version.Version.McCodeSub) Then
  697. Continue For
  698. End If
  699. End If
  700. If McMod.IsModFile(File.FullName) Then ModFileList.Add(File)
  701. Next
  702. End If
  703. '确定是否显示进度
  704. Loader.Progress = 0.03
  705. If ModFileList.Count > 100 Then RunInUi(Sub() If FrmVersionMod IsNot Nothing Then FrmVersionMod.Load.ShowProgress = True)
  706. '加载为 Mod 列表
  707. Dim ModList As New List(Of McMod)
  708. For Each ModFile As FileInfo In ModFileList
  709. Dim ModEntity As New McMod(ModFile.FullName)
  710. ModEntity.Load()
  711. ModList.Add(ModEntity)
  712. Loader.Progress += 0.9 / ModFileList.Count
  713. Next
  714. Loader.Progress = 0.93
  715. '排序
  716. ModList = Sort(ModList, Function(Left As McMod, Right As McMod) As Boolean
  717. If (Left.State = McMod.McModState.Unavaliable) <> (Right.State = McMod.McModState.Unavaliable) Then
  718. Return Left.State = McMod.McModState.Unavaliable
  719. Else
  720. Return Not Right.FileName.CompareTo(Left.FileName)
  721. End If
  722. End Function)
  723. Loader.Progress = 0.98
  724. '回设
  725. If Loader.IsAborted Then Exit Sub
  726. Loader.Output = ModList
  727. Catch ex As Exception
  728. Log(ex, "Mod 列表加载失败", LogLevel.Debug)
  729. Throw
  730. End Try
  731. End Sub
  732. #If DEBUG Then
  733. ''' <summary>
  734. ''' 检查 Mod 列表中存在的错误,返回错误信息的集合。
  735. ''' </summary>
  736. Public Function McModCheck(Version As McVersion, Mods As List(Of McMod)) As List(Of String)
  737. Dim Result As New List(Of String)
  738. '令所有 Mod 进行基础检查,并归纳需要检查的 Mod
  739. Dim CurrentModList As New List(Of McMod)
  740. For Each ModEntity In Mods
  741. If Not ModEntity.IsFileAvailable Then
  742. Result.Add("无法读取的 Mod 文件。" & vbCrLf & " - " & ModEntity.Path)
  743. Continue For
  744. End If
  745. If ModEntity.State = McMod.McModState.Fine AndAlso ModEntity.ModId IsNot Nothing Then CurrentModList.Add(ModEntity)
  746. Next
  747. '添加默认依赖
  748. Dim CurrentDependencies As New Dictionary(Of String, String()) '{DependencyVersion, Path}
  749. If Version.State = McVersionState.Forge Then CurrentDependencies.Add("forge", {Version.Version.ForgeVersion, "Forge"})
  750. CurrentDependencies.Add("minecraft", {Version.Version.McName, "Minecraft"})
  751. '检查重复的 Mod,并添加对应的依赖
  752. For Each ModEntity In CurrentModList
  753. For Each PossibleModId In ModEntity.PossibleModId
  754. If CurrentDependencies.ContainsKey(PossibleModId) Then
  755. If CurrentDependencies(PossibleModId)(2) = 1 Then
  756. Result.Add("重复添加了相同的 Mod,请尝试删除其中一个(ModID:" & PossibleModId & ")。" & vbCrLf &
  757. " - " & ModEntity.FileName & vbCrLf &
  758. " - " & CurrentDependencies(PossibleModId)(1))
  759. Else
  760. Log("[Minecraft] 由于可能有多个 ModID,跳过疑似的重复项(ModID:" & PossibleModId & ")。" & vbCrLf &
  761. " - " & ModEntity.FileName & vbCrLf &
  762. " - " & CurrentDependencies(PossibleModId)(1), LogLevel.Developer)
  763. End If
  764. Else
  765. CurrentDependencies.Add(PossibleModId, {ModEntity.Version, ModEntity.FileName, ModEntity.PossibleModId.Count})
  766. End If
  767. Next
  768. Next
  769. '检查依赖
  770. For Each ModEntity In CurrentModList
  771. Try
  772. For Each Dependency In ModEntity.Dependencies
  773. Dim ReqId As String = Dependency.Key
  774. If ReqId.Count < 2 Then Continue For '确保正常
  775. If ReqId = ModEntity.ModId Then Continue For '跳过自体引用
  776. If ReqId = "forgemultipartcbe" Then Continue For '跳过莫名其妙的引用
  777. If Dependency.Value IsNot Nothing Then
  778. '获取分段后的详细版本信息
  779. Dim ReqVersion As String = Dependency.Value
  780. Dim ReqVersionHeadCanEqual As Boolean = ReqVersion.StartsWith("[")
  781. Dim ReqVersionTailCanEqual As Boolean = ReqVersion.EndsWith("]")
  782. Dim ReqVersionHead As String
  783. Dim ReqVersionTail As String
  784. If ReqVersion.Contains(",") Then
  785. ReqVersionHead = ReqVersion.Split(",")(0).Trim("([ ".ToCharArray())
  786. ReqVersionTail = ReqVersion.Split(",")(1).Trim("]) ".ToCharArray())
  787. Else
  788. ReqVersionHead = ReqVersion.Trim("([]) ".ToCharArray())
  789. ReqVersionTail = ReqVersionHead
  790. If ReqId = "minecraft" AndAlso ReqVersionHead.Split(".").Count = 2 Then
  791. ReqVersionTail = ReqVersionHead.Split(".")(0) & "." & (Val(ReqVersionHead.Split(".")(1)) + 1)
  792. ReqVersionTailCanEqual = False
  793. End If
  794. End If
  795. If ReqVersionHead.StartsWith("1.") AndAlso ReqVersionHead.Contains("-") Then ReqVersionHead = ReqVersionHead.Substring(ReqVersionHead.LastIndexOf("-") + 1)
  796. If ReqVersionTail.StartsWith("1.") AndAlso ReqVersionTail.Contains("-") Then ReqVersionTail = ReqVersionTail.Substring(ReqVersionTail.LastIndexOf("-") + 1)
  797. '获取报错描述文本
  798. Dim VersionRequire As String
  799. If ReqVersionHead = ReqVersionTail Then
  800. VersionRequire = "应为 " & ReqVersionHead
  801. ElseIf ReqVersionHead.Contains(".") AndAlso ReqVersionTail.Contains(".") Then
  802. VersionRequire = "应为 " & ReqVersionHead & " 至 " & ReqVersionTail
  803. ElseIf ReqVersionHead.Contains(".") Then
  804. If ReqVersionHeadCanEqual Then
  805. VersionRequire = "最低应为 " & ReqVersionHead
  806. Else
  807. VersionRequire = "应高于 " & ReqVersionHead
  808. End If
  809. ElseIf ReqVersionTail.Contains(".") Then
  810. If ReqVersionTailCanEqual Then
  811. VersionRequire = "最高应为 " & ReqVersionHead
  812. Else
  813. VersionRequire = "应低于 " & ReqVersionHead
  814. End If
  815. Else
  816. VersionRequire = ""
  817. End If
  818. '检查前置 Mod 是否存在,并获取其版本
  819. If Not CurrentDependencies.ContainsKey(ReqId) Then
  820. Result.Add("缺少前置 Mod:" & ReqId & If(VersionRequire = "", "", ",其版本" & VersionRequire) & "。" & vbCrLf & " - " & ModEntity.FileName)
  821. Continue For
  822. End If
  823. Dim CurrentVersion As String = If(CurrentDependencies(ReqId)(0), "0.0")
  824. If CurrentVersion.StartsWith("1.") AndAlso CurrentVersion.Contains("-") Then CurrentVersion = CurrentVersion.Substring(CurrentVersion.LastIndexOf("-") + 1)
  825. '对比前置 Mod 头部版本
  826. If ReqVersionHead.Contains(".") Then
  827. If VersionSortInteger(ReqVersionHead, CurrentVersion) > If(ReqVersionHeadCanEqual, 0, -1) Then
  828. Result.Add(ReqId.Substring(0, 1).ToUpper & ReqId.Substring(1) & " 版本过低,其版本" & VersionRequire & ",而当前版本为 " & CurrentVersion & "。" & vbCrLf &
  829. " - " & ModEntity.FileName & If(ReqId <> "minecraft" AndAlso ReqId <> "forge", vbCrLf & " - 前置:" & CurrentDependencies(ReqId)(1), ""))
  830. Continue For
  831. End If
  832. End If
  833. '对比前置 Mod 尾部版本
  834. If ReqVersionTail.Contains(".") Then
  835. If VersionSortInteger(CurrentVersion, ReqVersionTail) > If(ReqVersionTailCanEqual, 0, -1) Then
  836. Result.Add(ReqId.Substring(0, 1).ToUpper & ReqId.Substring(1) & " 版本过高,其版本" & VersionRequire & ",而当前版本为 " & CurrentVersion & "。" & vbCrLf &
  837. " - " & ModEntity.FileName & If(ReqId <> "minecraft" AndAlso ReqId <> "forge", vbCrLf & " - 前置:" & CurrentDependencies(ReqId)(1), ""))
  838. Continue For
  839. End If
  840. End If
  841. Else
  842. If Not CurrentDependencies.ContainsKey(Dependency.Key) Then
  843. Result.Add("缺少前置 Mod:" & Dependency.Key & "。" & vbCrLf & " - " & ModEntity.FileName)
  844. Continue For
  845. End If
  846. End If
  847. Next
  848. Catch ex As Exception
  849. Result.Add("检查 Mod 时出错:" & GetExceptionSummary(ex) & vbCrLf & " - " & ModEntity.FileName)
  850. Log(ex, "检查 Mod 时出错")
  851. End Try
  852. Next
  853. If Result.Count = 0 Then
  854. Log("[Minecraft] Mod 检查未发现异常")
  855. Else
  856. Log("[Minecraft] Mod 检查异常结果:" & vbCrLf & Join(Result, vbCrLf))
  857. End If
  858. Return Result
  859. End Function
  860. #End If
  861. End Module