SUpdateManager.lua.txt 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  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. -- lFile == nil => add file edit file
  166. if lFile == nil or (lFile ~= nil and lFile.hashInfo ~= oneFileInfo.hashInfo) then
  167. willDownloadFileCount = willDownloadFileCount + 1
  168. willDownloadBytes = willDownloadBytes + oneFileInfo.fileSize
  169. willDownloadFileList[oneFileInfo.fileName] = oneFileInfo
  170. end
  171. -- remove file
  172. localResourceCache[oneFileInfo.fileName] = nil
  173. end
  174. for _, removeFileInfo in pairs(localResourceCache) do
  175. willDownloadFileCount = willDownloadFileCount + 1
  176. willDownloadBytes = willDownloadBytes + removeFileInfo.fileSize
  177. willDownloadFileList[removeFileInfo.fileName] = removeFileInfo
  178. end
  179. SUpdateManager._willDownloadBytes = willDownloadBytes
  180. SUpdateManager._willDownloadFileList = willDownloadFileList
  181. SUpdateManager._willDownloadFileCount = willDownloadFileCount
  182. print("----> will download file count: " .. tostring(willDownloadFileCount))
  183. eventDispatchCenter:DispatchEvent(eventDispatchCenter.EventType.UPDATE_STATE_INFO, "Prepare Calc Update Resource ... Success")
  184. local totalSize = CS.System.Math.Round(willDownloadBytes / 1024 / 1024, 2)
  185. local tipsInfo = string.format(
  186. "Found new version:%s ...\nFile Count:%d FileSize:%s MB",
  187. rVersionInfo.version, willDownloadFileCount, tostring(totalSize)
  188. )
  189. eventDispatchCenter:DispatchEvent(eventDispatchCenter.EventType.UPDATE_SHOW_TIPS, "Download Tips", tipsInfo)
  190. print("----> Process usCalcUpdateResInfo Finish ...")
  191. stepState(tUpdateState.usDownloadResource)
  192. --require("Base/CoroutineHelper.lua"):Start(SUpdateManager.ProcessUpdate)
  193. end
  194. function SUpdateManager.tryDownloadResourceLogic()
  195. print("----> Process usDownloadResource Start ...")
  196. require("Base/CoroutineHelper.lua"):WaitForEndOfFrame()
  197. local eventDispatchCenter = require("Base/SEventDispatchCenter.lua")
  198. eventDispatchCenter:DispatchEvent(eventDispatchCenter.EventType.UPDATE_STATE_INFO, "Prepare To Clean Local Resources ...")
  199. require("Base/CoroutineHelper.lua"):Wait(1)
  200. local willDownloadByte = SUpdateManager._willDownloadBytes
  201. local willDownloadFileList = SUpdateManager._willDownloadFileList
  202. local willDownloadFileCount = SUpdateManager._willDownloadFileCount
  203. -- Step 1: Try To Delete All Local File(PersistentPath) That Need Update.
  204. local cleanedCount = 1
  205. for fileName, fileInfo in pairs(willDownloadFileList) do
  206. CS.SFramework.SResourceManagerR.TryDeleteAssetBundle(fileInfo.fileName)
  207. local stateMessage = string.format("Clean Local Files(%d/%d) -> %s", cleanedCount, willDownloadFileCount, fileName)
  208. eventDispatchCenter:DispatchEvent(eventDispatchCenter.EventType.UPDATE_STATE_INFO, stateMessage)
  209. cleanedCount = cleanedCount + 1
  210. eventDispatchCenter:DispatchEvent(eventDispatchCenter.EventType.UPDATE_PROGRESS_PERCENT, cleanedCount / willDownloadFileCount)
  211. require("Base/CoroutineHelper.lua"):Wait(1)
  212. end
  213. print("----> Success Clean Local File Count: " .. tostring(cleanedCount))
  214. eventDispatchCenter:DispatchEvent(eventDispatchCenter.EventType.UPDATE_STATE_INFO, "Clean All Local Resources ... Success")
  215. require("Base/CoroutineHelper.lua"):Wait(1)
  216. -- Step 2: Download Each File One By One And Write It On Right Path.
  217. eventDispatchCenter:DispatchEvent(eventDispatchCenter.EventType.UPDATE_STATE_INFO, "Prepare To Download Remote Resources ...")
  218. local downloadStartTime = CS.UnityEngine.Time.realtimeSinceStartup
  219. local downloadedBytes = 0
  220. local downloadSpeed = ""
  221. for fileName, fileInfo in pairs(willDownloadFileList) do
  222. local baseDownloadedBytes = downloadedBytes
  223. local platformName = CS.SFramework.SPlatformInfoR.GetBuildPlatformName()
  224. local donwloadLink = tUpdateConfig.resourceVersionUrlBase .. platformName .. "/" .. fileInfo.fileName
  225. local luaRequest = CS.UnityEngine.Networking.UnityWebRequest.Get(donwloadLink)
  226. luaRequest.timeout = tUpdateConfig.httpRequestTimeoutTime
  227. local downloadPercent = 0
  228. eventDispatchCenter:DispatchEvent(eventDispatchCenter.EventType.UPDATE_PROGRESS_PERCENT, downloadPercent)
  229. luaRequest:SendWebRequest()
  230. repeat
  231. downloadPercent = luaRequest.downloadProgress
  232. if downloadPercent < 0 then downloadPercent = 0 end
  233. local fileDownloadBytes = baseDownloadedBytes + luaRequest.downloadedBytes
  234. downloadSpeed = CS.SFramework.SToolFunctionR.GetDownloadSpeed(fileDownloadBytes, CS.UnityEngine.Time.realtimeSinceStartup - downloadStartTime)
  235. -- update download info to show information.
  236. local stateMessage = string.format(
  237. "Downloading: %s From %s \nPercent: %.2f Speed:%s",
  238. fileName, donwloadLink, downloadPercent * 100, downloadSpeed
  239. )
  240. eventDispatchCenter:DispatchEvent(eventDispatchCenter.EventType.UPDATE_STATE_INFO, stateMessage)
  241. eventDispatchCenter:DispatchEvent(eventDispatchCenter.EventType.UPDATE_PROGRESS_PERCENT, downloadPercent)
  242. require("Base/CoroutineHelper.lua"):WaitForEndOfFrame()
  243. until luaRequest.isDone
  244. eventDispatchCenter:DispatchEvent(eventDispatchCenter.EventType.UPDATE_PROGRESS_PERCENT, 1)
  245. downloadedBytes = downloadedBytes + luaRequest.downloadedBytes
  246. downloadSpeed = CS.SFramework.SToolFunctionR.GetDownloadSpeed(downloadedBytes, CS.UnityEngine.Time.realtimeSinceStartup - downloadStartTime)
  247. -- update download speed
  248. local stateMessage = string.format("Downloading: %s \nPercent: %.2f Speed:%s Success", fileName, downloadPercent * 100, downloadSpeed)
  249. eventDispatchCenter:DispatchEvent(eventDispatchCenter.EventType.UPDATE_STATE_INFO, stateMessage)
  250. require("Base/CoroutineHelper.lua"):Wait(1)
  251. CS.SFramework.SResourceManagerR.SaveAssetBundle(fileInfo.fileName, luaRequest.downloadHandler.data)
  252. stateMessage = string.format("Download And Save %s Success", fileName)
  253. eventDispatchCenter:DispatchEvent(eventDispatchCenter.EventType.UPDATE_STATE_INFO, stateMessage)
  254. require("Base/CoroutineHelper.lua"):Wait(1)
  255. end
  256. downloadSpeed = CS.SFramework.SToolFunctionR.GetDownloadSpeed(downloadedBytes, CS.UnityEngine.Time.realtimeSinceStartup - downloadStartTime)
  257. -- update download speed
  258. eventDispatchCenter:DispatchEvent(eventDispatchCenter.EventType.UPDATE_STATE_INFO, "All Remote Resource Download Compelete ... Speed: " .. tostring(downloadSpeed))
  259. require("Base/CoroutineHelper.lua"):Wait(1)
  260. -- Step 3: Try Write version.json(Remote Version) To PersistentPath.
  261. CS.SFramework.SResourceManagerR.SaveRemoteVersionJson(SUpdateManager._rVersionInfoJson)
  262. eventDispatchCenter:DispatchEvent(eventDispatchCenter.EventType.UPDATE_STATE_INFO, "All Files Download Finish ...")
  263. print("----> Process usDownloadResource Finish ...")
  264. require("Base/CoroutineHelper.lua"):Wait(1)
  265. -- Step 4: Change currentState And retry
  266. stepState(tUpdateState.usFinish)
  267. require("Base/CoroutineHelper.lua"):Start(SUpdateManager.ProcessUpdate)
  268. end
  269. function SUpdateManager.tryFinishLogic()
  270. print("----> Process usFinish Start ...")
  271. require("Base/CoroutineHelper.lua"):WaitForEndOfFrame()
  272. local eventDispatchCenter = require("Base/SEventDispatchCenter.lua")
  273. eventDispatchCenter:DispatchEvent(eventDispatchCenter.EventType.UPDATE_STATE_INFO, "All Data Updated ... Success")
  274. require("Base/CoroutineHelper.lua"):Wait(1)
  275. print("----> Process usFinish Finish ...")
  276. require("Base/CoroutineHelper.lua"):Wait(1)
  277. -- jump scene
  278. LoadResource("scenes/start.unity")
  279. --LoadResource("scenes/gameb.unity")
  280. --CS.UnityEngine.SceneManagement.SceneManager.LoadScene("GameA")
  281. CS.UnityEngine.SceneManagement.SceneManager.LoadScene("Start")
  282. end
  283. function SUpdateManager.ProcessUpdate()
  284. local currentState = SUpdateManager._updateState
  285. print("SUpdateManager.ProcessUpdate Start ... ... State: " .. tostring(currentState))
  286. if currentState == tUpdateState.usHotfixLua then
  287. require("Base/CoroutineHelper.lua"):Start(SUpdateManager.tryHotfixLuaLogic)
  288. return
  289. end
  290. if currentState == tUpdateState.usGetResVersion then
  291. require("Base/CoroutineHelper.lua"):Start(SUpdateManager.tryGetResVersionLogic)
  292. return
  293. end
  294. if currentState == tUpdateState.usCalcUpdateResInfo then
  295. require("Base/CoroutineHelper.lua"):Start(SUpdateManager.tryCalcUpdateResInfoLogic)
  296. return
  297. end
  298. if currentState == tUpdateState.usDownloadResource then
  299. require("Base/CoroutineHelper.lua"):Start(SUpdateManager.tryDownloadResourceLogic)
  300. return
  301. end
  302. if currentState == tUpdateState.usFinish then
  303. require("Base/CoroutineHelper.lua"):Start(SUpdateManager.tryFinishLogic)
  304. return
  305. end
  306. print("SUpdateManager.ProcessUpdate All Step Finish But Run ... ... Error State: " .. tostring(currentState))
  307. end
  308. return SUpdateManager