SUpdateManager.lua.txt 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  1. require("Base/GlobalFunctions.lua")
  2. local tUpdateConfig = {
  3. -- ignoreUpdate = true,
  4. ignoreUpdate = false,
  5. hotfixLuaUrl = "http://192.168.1.135:80/files/sframework_update/hotfix.lua",
  6. httpRequestTimeoutTime = 3,
  7. resourceVersionUrlBase = "http://192.168.1.135:80/files/sframework_update/Bundles/";
  8. resourceVersionName = "version.json",
  9. }
  10. local SUpdateManager = SUpdateManager or {}
  11. local tUpdateState = {
  12. usInvaild = "usInvaild",
  13. usStart = "usStart",
  14. usShowUI = "usShowUI",
  15. usHotfixLua = "usHotfixLua",
  16. usGetResVersion = "usGetResVersion",
  17. usCalcUpdateResInfo = "usCalcUpdateResInfo",
  18. usDownloadResource = "usDownloadResource",
  19. usFinish = "usFinish"
  20. }
  21. SUpdateManager._updateState = tUpdateState.usInvaild
  22. SUpdateManager._rVersionInfo = nil
  23. SUpdateManager._lVersionInfo = nil
  24. SUpdateManager._rVersionInfoJson = nil
  25. SUpdateManager._willDownloadBytes = 0
  26. SUpdateManager._willDownloadFileList = nil
  27. local function stepState(newState)
  28. local oldState = SUpdateManager._updateState
  29. print("----> SUpdateManager StepState " .. oldState .. " -> " .. newState)
  30. SUpdateManager._updateState = newState
  31. end
  32. local function retryUpdate()
  33. print("----------> retryUpdate")
  34. require("Base/CoroutineHelper.lua"):Start(SUpdateManager.ProcessUpdate)
  35. end
  36. function SUpdateManager.Awake(luaRoot)
  37. print("SUpdateManager.Awake ~")
  38. local dataPath = CS.UnityEngine.Application.dataPath
  39. local streamingAssetsPath = CS.UnityEngine.Application.streamingAssetsPath
  40. local persistentDataPath = CS.UnityEngine.Application.persistentDataPath
  41. print("Application.dataPath -> " .. dataPath)
  42. print("Application.streamingAssetsPath -> " .. streamingAssetsPath)
  43. print("Application.persistentDataPath -> " .. persistentDataPath)
  44. end
  45. function SUpdateManager.Start(luaRoot)
  46. print("SUpdateManager.Start ~")
  47. stepState(tUpdateState.usStart)
  48. -- Register Event
  49. local eventDispatchCenter = require("Base/SEventDispatchCenter.lua")
  50. eventDispatchCenter:RegisterEvent(eventDispatchCenter.EventType.UPDATE_RETRY, retryUpdate)
  51. -- Process Show Update UI.
  52. require("Base/UIHelper.lua"):OpenUI("Update/SUIPanelUpdate.lua")
  53. stepState(tUpdateState.usShowUI)
  54. -- Check Ignore Update.
  55. if tUpdateConfig.ignoreUpdate == true then
  56. stepState(tUpdateState.usFinish)
  57. print("SUpdateManager.ignoreUpdate == true, Jump Update!")
  58. require("Base/CoroutineHelper.lua"):Start(SUpdateManager.ProcessUpdate)
  59. return
  60. end
  61. -- Process Update.
  62. stepState(tUpdateState.usHotfixLua)
  63. require("Base/CoroutineHelper.lua"):Start(SUpdateManager.ProcessUpdate)
  64. end
  65. function SUpdateManager.OnDestroy()
  66. print("SUpdateManager.OnDestroy ~")
  67. local eventDispatchCenter = require("Base/SEventDispatchCenter.lua")
  68. eventDispatchCenter:UnregisterEvent(eventDispatchCenter.EventType.UPDATE_RETRY, retryUpdate)
  69. end
  70. function SUpdateManager.tryHotfixLuaLogic()
  71. print("----> Process usHotfixLua Start ...")
  72. require("Base/CoroutineHelper.lua"):WaitForEndOfFrame()
  73. local eventDispatchCenter = require("Base/SEventDispatchCenter.lua")
  74. eventDispatchCenter:DispatchEvent(eventDispatchCenter.EventType.UPDATE_STATE_INFO, "Communication With Server ...")
  75. require("Base/CoroutineHelper.lua"):Wait(1)
  76. local hotfixLuaUrl = tUpdateConfig.hotfixLuaUrl
  77. --print("-------------> hotfixLuaUrl: " .. hotfixLuaUrl)
  78. local luaRequest = CS.UnityEngine.Networking.UnityWebRequest.Get(hotfixLuaUrl)
  79. luaRequest.timeout = tUpdateConfig.httpRequestTimeoutTime
  80. require("Base/CoroutineHelper.lua"):WaitSendWebRequest(luaRequest)
  81. if luaRequest.result == CS.UnityEngine.Networking.UnityWebRequest.Result.ConnectionError or luaRequest.result == CS.UnityEngine.Networking.UnityWebRequest.Result.ProtocolError then
  82. Warn("SUpdateManager -> UpdateLogic luaRequest Error -> " .. tostring(luaRequest.error))
  83. eventDispatchCenter:DispatchEvent(eventDispatchCenter.EventType.UPDATE_STATE_INFO, "Communication With Server ... Error: " .. tostring(luaRequest.error))
  84. eventDispatchCenter:DispatchEvent(eventDispatchCenter.EventType.UPDATE_SHOW_TIPS, "Connect Failed", "Connection To Resrouce Server Failed!\nPlease Check Your Network State.\nClick Yes Try Again. Click No Exit Game.")
  85. --print("-------> Hotfix Step Failed")
  86. return
  87. end
  88. local luaCode = luaRequest.downloadHandler.text
  89. CS.SFramework.SLuaEnv.Instance:DoString(luaCode)
  90. print("----> Process usHotfixLua Finish ...")
  91. eventDispatchCenter:DispatchEvent(eventDispatchCenter.EventType.UPDATE_STATE_INFO, "Communication With Server ... Success")
  92. require("Base/CoroutineHelper.lua"):Wait(1)
  93. stepState(tUpdateState.usGetResVersion)
  94. require("Base/CoroutineHelper.lua"):Start(SUpdateManager.ProcessUpdate)
  95. end
  96. function SUpdateManager.tryGetResVersionLogic()
  97. print("----> Process usGetResVersion Start ...")
  98. require("Base/CoroutineHelper.lua"):WaitForEndOfFrame()
  99. local eventDispatchCenter = require("Base/SEventDispatchCenter.lua")
  100. eventDispatchCenter:DispatchEvent(eventDispatchCenter.EventType.UPDATE_STATE_INFO, "Communication With Resource Server ...")
  101. require("Base/CoroutineHelper.lua"):Wait(1)
  102. local platformName = CS.SFramework.SPlatformInfoR.GetBuildPlatformName()
  103. local resVersionUrl = tUpdateConfig.resourceVersionUrlBase .. platformName .. "/" .. tUpdateConfig.resourceVersionName
  104. --print("------------> resVersionUrl: " .. tostring(resVersionUrl))
  105. local luaRequest = CS.UnityEngine.Networking.UnityWebRequest.Get(resVersionUrl)
  106. luaRequest.timeout = tUpdateConfig.httpRequestTimeoutTime
  107. require("Base/CoroutineHelper.lua"):WaitSendWebRequest(luaRequest)
  108. if luaRequest.result == CS.UnityEngine.Networking.UnityWebRequest.Result.ConnectionError or luaRequest.result == CS.UnityEngine.Networking.UnityWebRequest.Result.ProtocolError then
  109. -- Notice User, Choose;
  110. Warn("SUpdateManager -> UpdateLogic resVersionRequest Error -> " .. tostring(luaRequest.error))
  111. eventDispatchCenter:DispatchEvent(eventDispatchCenter.EventType.UPDATE_STATE_INFO, "Communication With Resource Server ... Error: " .. tostring(luaRequest.error))
  112. --print("-------> GetResVersion Step Failed")
  113. return
  114. end
  115. local jsonConverter = require("Base/json.lua")
  116. local remoteVersionJson = luaRequest.downloadHandler.text
  117. print("remoteVersionJson -> " .. remoteVersionJson)
  118. local localVersionJson = CS.SFramework.SResourceManagerR.GetLocalVersionJson()
  119. print("localVersionJson -> " .. localVersionJson)
  120. --require("Base/CoroutineHelper.lua"):Wait(1)
  121. local remoteVersionInfo = jsonConverter:decode(remoteVersionJson)
  122. local localVersionInfo = jsonConverter:decode(localVersionJson)
  123. local rversion = remoteVersionInfo.version
  124. local lversion = localVersionInfo.version
  125. local stateMessage = string.format("Remote Version: %d Local Version: %d", rversion, lversion)
  126. print(stateMessage)
  127. eventDispatchCenter:DispatchEvent(eventDispatchCenter.EventType.UPDATE_STATE_INFO, stateMessage)
  128. SUpdateManager._lVersionInfo = localVersionInfo
  129. SUpdateManager._rVersionInfo = remoteVersionInfo
  130. SUpdateManager._rVersionInfoJson = remoteVersionJson
  131. require("Base/CoroutineHelper.lua"):Wait(1)
  132. eventDispatchCenter:DispatchEvent(eventDispatchCenter.EventType.UPDATE_STATE_INFO, "Commuication With ResourceServer ... Success")
  133. require("Base/CoroutineHelper.lua"):Wait(1)
  134. if rversion == lversion then
  135. print("lversion == rversion no need update.")
  136. stepState(tUpdateState.usFinish)
  137. require("Base/CoroutineHelper.lua"):Start(SUpdateManager.ProcessUpdate)
  138. return
  139. end
  140. print("----> Process usGetResVersion Finish ...")
  141. --require("Base/CoroutineHelper.lua"):Wait(1)
  142. stepState(tUpdateState.usCalcUpdateResInfo)
  143. require("Base/CoroutineHelper.lua"):Start(SUpdateManager.ProcessUpdate)
  144. end
  145. function SUpdateManager.tryCalcUpdateResInfoLogic()
  146. print("----> Process usCalcUpdateResInfo Start ...")
  147. require("Base/CoroutineHelper.lua"):WaitForEndOfFrame()
  148. local eventDispatchCenter = require("Base/SEventDispatchCenter.lua")
  149. eventDispatchCenter:DispatchEvent(eventDispatchCenter.EventType.UPDATE_STATE_INFO, "Prepare Calc Update Resource ...")
  150. require("Base/CoroutineHelper.lua"):Wait(1)
  151. local lVersionInfo = SUpdateManager._lVersionInfo
  152. local rVersionInfo = SUpdateManager._rVersionInfo
  153. local localResourceCache = {}
  154. local localResourceCount = 0
  155. for _, oneFileInfo in pairs(lVersionInfo.fileInfo) do
  156. localResourceCache[oneFileInfo.fileName] = oneFileInfo
  157. localResourceCount = localResourceCount + 1
  158. end
  159. print("----> Cache Local Resource Count: " .. tostring(localResourceCount))
  160. local willDownloadFileCount = 0
  161. local willDownloadBytes = 0
  162. local willDownloadFileList = {}
  163. for _, oneFileInfo in pairs(rVersionInfo.fileInfo) do
  164. local lFile = localResourceCache[oneFileInfo.fileName]
  165. if lFile ~= nil and lFile.hashInfo ~= oneFileInfo.hashInfo then
  166. willDownloadFileCount = willDownloadFileCount + 1
  167. willDownloadBytes = willDownloadBytes + oneFileInfo.fileSize
  168. willDownloadFileList[oneFileInfo.fileName] = oneFileInfo
  169. end
  170. end
  171. SUpdateManager._willDownloadBytes = willDownloadBytes
  172. SUpdateManager._willDownloadFileList = willDownloadFileList
  173. SUpdateManager._willDownloadFileCount = willDownloadFileCount
  174. print("----> will download file count: " .. tostring(willDownloadFileCount))
  175. eventDispatchCenter:DispatchEvent(eventDispatchCenter.EventType.UPDATE_STATE_INFO, "Prepare Calc Update Resource ... Success")
  176. local totalSize = CS.System.Math.Round(willDownloadBytes / 1024 / 1024, 2)
  177. local tipsInfo = string.format(
  178. "Found new version:%s ...\nFile Count:%d FileSize:%s MB",
  179. rVersionInfo.version, willDownloadFileCount, tostring(totalSize)
  180. )
  181. eventDispatchCenter:DispatchEvent(eventDispatchCenter.EventType.UPDATE_SHOW_TIPS, "Download Tips", tipsInfo)
  182. print("----> Process usCalcUpdateResInfo Finish ...")
  183. stepState(tUpdateState.usDownloadResource)
  184. --require("Base/CoroutineHelper.lua"):Start(SUpdateManager.ProcessUpdate)
  185. end
  186. function SUpdateManager.tryDownloadResourceLogic()
  187. print("----> Process usDownloadResource Start ...")
  188. require("Base/CoroutineHelper.lua"):WaitForEndOfFrame()
  189. local eventDispatchCenter = require("Base/SEventDispatchCenter.lua")
  190. eventDispatchCenter:DispatchEvent(eventDispatchCenter.EventType.UPDATE_STATE_INFO, "Prepare To Clean Local Resources ...")
  191. require("Base/CoroutineHelper.lua"):Wait(1)
  192. local willDownloadByte = SUpdateManager._willDownloadBytes
  193. local willDownloadFileList = SUpdateManager._willDownloadFileList
  194. local willDownloadFileCount = SUpdateManager._willDownloadFileCount
  195. -- Step 1: Try To Delete All Local File(PersistentPath) That Need Update.
  196. local cleanedCount = 1
  197. for fileName, fileInfo in pairs(willDownloadFileList) do
  198. CS.SFramework.SResourceManagerR.TryDeleteAssetBundle(fileInfo.fileName)
  199. local stateMessage = string.format("Clean Local Files(%d/%d) -> %s", cleanedCount, willDownloadFileCount, fileName)
  200. eventDispatchCenter:DispatchEvent(eventDispatchCenter.EventType.UPDATE_STATE_INFO, stateMessage)
  201. cleanedCount = cleanedCount + 1
  202. eventDispatchCenter:DispatchEvent(eventDispatchCenter.EventType.UPDATE_PROGRESS_PERCENT, cleanedCount / willDownloadFileCount)
  203. require("Base/CoroutineHelper.lua"):Wait(1)
  204. end
  205. print("----> Success Clean Local File Count: " .. tostring(cleanedCount))
  206. eventDispatchCenter:DispatchEvent(eventDispatchCenter.EventType.UPDATE_STATE_INFO, "Clean All Local Resources ... Success")
  207. require("Base/CoroutineHelper.lua"):Wait(1)
  208. -- Step 2: Download Each File One By One And Write It On Right Path.
  209. eventDispatchCenter:DispatchEvent(eventDispatchCenter.EventType.UPDATE_STATE_INFO, "Prepare To Download Remote Resources ...")
  210. local downloadStartTime = CS.UnityEngine.Time.realtimeSinceStartup
  211. local downloadedBytes = 0
  212. local downloadSpeed = ""
  213. for fileName, fileInfo in pairs(willDownloadFileList) do
  214. local baseDownloadedBytes = downloadedBytes
  215. local platformName = CS.SFramework.SPlatformInfoR.GetBuildPlatformName()
  216. local donwloadLink = tUpdateConfig.resourceVersionUrlBase .. platformName .. "/" .. fileInfo.fileName
  217. local luaRequest = CS.UnityEngine.Networking.UnityWebRequest.Get(donwloadLink)
  218. luaRequest.timeout = tUpdateConfig.httpRequestTimeoutTime
  219. local downloadPercent = 0
  220. eventDispatchCenter:DispatchEvent(eventDispatchCenter.EventType.UPDATE_PROGRESS_PERCENT, downloadPercent)
  221. luaRequest:SendWebRequest()
  222. repeat
  223. downloadPercent = luaRequest.downloadProgress
  224. if downloadPercent < 0 then downloadPercent = 0 end
  225. local fileDownloadBytes = baseDownloadedBytes + luaRequest.downloadedBytes
  226. downloadSpeed = CS.SFramework.SToolFunctionR.GetDownloadSpeed(fileDownloadBytes, CS.UnityEngine.Time.realtimeSinceStartup - downloadStartTime)
  227. -- update download info to show information.
  228. local stateMessage = string.format(
  229. "Downloading: %s From %s \nPercent: %d Speed:%s",
  230. fileName, donwloadLink, downloadPercent * 100, downloadSpeed
  231. )
  232. eventDispatchCenter:DispatchEvent(eventDispatchCenter.EventType.UPDATE_STATE_INFO, stateMessage)
  233. eventDispatchCenter:DispatchEvent(eventDispatchCenter.EventType.UPDATE_PROGRESS_PERCENT, downloadPercent)
  234. require("Base/CoroutineHelper.lua"):WaitForEndOfFrame()
  235. until luaRequest.isDone
  236. eventDispatchCenter:DispatchEvent(eventDispatchCenter.EventType.UPDATE_PROGRESS_PERCENT, 1)
  237. downloadedBytes = downloadedBytes + luaRequest.downloadedBytes
  238. downloadSpeed = CS.SFramework.SToolFunctionR.GetDownloadSpeed(downloadedBytes, CS.UnityEngine.Time.realtimeSinceStartup - downloadStartTime)
  239. -- update download speed
  240. local stateMessage = string.format("Downloading: %s \nPercent: %d Speed:%s Success", fileName, downloadPercent * 100, downloadSpeed)
  241. eventDispatchCenter:DispatchEvent(eventDispatchCenter.EventType.UPDATE_STATE_INFO, stateMessage)
  242. require("Base/CoroutineHelper.lua"):Wait(1)
  243. CS.SFramework.SResourceManagerR.SaveAssetBundle(fileInfo.fileName, luaRequest.downloadHandler.data)
  244. stateMessage = string.format("Download And Save %s Success", fileName)
  245. eventDispatchCenter:DispatchEvent(eventDispatchCenter.EventType.UPDATE_STATE_INFO, stateMessage)
  246. require("Base/CoroutineHelper.lua"):Wait(1)
  247. end
  248. downloadSpeed = CS.SFramework.SToolFunctionR.GetDownloadSpeed(downloadedBytes, CS.UnityEngine.Time.realtimeSinceStartup - downloadStartTime)
  249. -- update download speed
  250. eventDispatchCenter:DispatchEvent(eventDispatchCenter.EventType.UPDATE_STATE_INFO, "All Remote Resource Download Compelete ... Speed: " .. tostring(downloadSpeed))
  251. require("Base/CoroutineHelper.lua"):Wait(1)
  252. -- Step 3: Try Write version.json(Remote Version) To PersistentPath.
  253. CS.SFramework.SResourceManagerR.SaveRemoteVersionJson(SUpdateManager._rVersionInfoJson)
  254. eventDispatchCenter:DispatchEvent(eventDispatchCenter.EventType.UPDATE_STATE_INFO, "All Files Download Finish ...")
  255. print("----> Process usDownloadResource Finish ...")
  256. require("Base/CoroutineHelper.lua"):Wait(1)
  257. -- Step 4: Change currentState And retry
  258. stepState(tUpdateState.usFinish)
  259. require("Base/CoroutineHelper.lua"):Start(SUpdateManager.ProcessUpdate)
  260. end
  261. function SUpdateManager.tryFinishLogic()
  262. print("----> Process usFinish Start ...")
  263. require("Base/CoroutineHelper.lua"):WaitForEndOfFrame()
  264. local eventDispatchCenter = require("Base/SEventDispatchCenter.lua")
  265. eventDispatchCenter:DispatchEvent(eventDispatchCenter.EventType.UPDATE_STATE_INFO, "All Data Updated ... Success")
  266. require("Base/CoroutineHelper.lua"):Wait(1)
  267. print("----> Process usFinish Finish ...")
  268. require("Base/CoroutineHelper.lua"):Wait(1)
  269. -- jump scene
  270. LoadResource("scenes/start.unity")
  271. --LoadResource("scenes/gameb.unity")
  272. --CS.UnityEngine.SceneManagement.SceneManager.LoadScene("GameA")
  273. CS.UnityEngine.SceneManagement.SceneManager.LoadScene("GameA")
  274. end
  275. function SUpdateManager.ProcessUpdate()
  276. local currentState = SUpdateManager._updateState
  277. print("SUpdateManager.ProcessUpdate Start ... ... State: " .. tostring(currentState))
  278. if currentState == tUpdateState.usHotfixLua then
  279. require("Base/CoroutineHelper.lua"):Start(SUpdateManager.tryHotfixLuaLogic)
  280. return
  281. end
  282. if currentState == tUpdateState.usGetResVersion then
  283. require("Base/CoroutineHelper.lua"):Start(SUpdateManager.tryGetResVersionLogic)
  284. return
  285. end
  286. if currentState == tUpdateState.usCalcUpdateResInfo then
  287. require("Base/CoroutineHelper.lua"):Start(SUpdateManager.tryCalcUpdateResInfoLogic)
  288. return
  289. end
  290. if currentState == tUpdateState.usDownloadResource then
  291. require("Base/CoroutineHelper.lua"):Start(SUpdateManager.tryDownloadResourceLogic)
  292. return
  293. end
  294. if currentState == tUpdateState.usFinish then
  295. require("Base/CoroutineHelper.lua"):Start(SUpdateManager.tryFinishLogic)
  296. return
  297. end
  298. print("SUpdateManager.ProcessUpdate All Step Finish But Run ... ... Error State: " .. tostring(currentState))
  299. end
  300. return SUpdateManager