Updater.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575
  1. 
  2. using System;
  3. using System.Collections;
  4. using System.Collections.Generic;
  5. using System.IO;
  6. using UnityEngine;
  7. using UnityEngine.Networking;
  8. public interface IUpdater
  9. {
  10. void OnStart();
  11. void OnMessage(string msg);
  12. void OnProgress(float progress);
  13. void OnVersion(string ver);
  14. void OnClear();
  15. }
  16. public class Updater : MonoBehaviour, IUpdater
  17. {
  18. enum Step
  19. {
  20. Wait,
  21. Copy,
  22. Coping,
  23. Versions,
  24. Prepared,
  25. Download,
  26. }
  27. private Step _step;
  28. [SerializeField] private string baseURL = "http://127.0.0.1:7888/DLC/";
  29. [SerializeField] private string gameScene = "Game.unity";
  30. [SerializeField] private bool enableVFS = true;
  31. public bool development;
  32. public IUpdater listener { get; set; }
  33. private string _platform;
  34. private string _savePath;
  35. private IEnumerator _checking;
  36. private void Start()
  37. {
  38. _savePath = string.Format("{0}/DLC/", UnityEngine.Application.persistentDataPath);
  39. _platform = GetPlatformForAssetBundles(UnityEngine.Application.platform);
  40. _step = Step.Wait;
  41. LoadModule.updatePath = _savePath;
  42. }
  43. public void StartUpdate()
  44. {
  45. GameLog.Log("StartUpdate.Development:" + development);
  46. #if UNITY_EDITOR
  47. if (development)
  48. {
  49. LoadModule.runtimeMode = false;
  50. StartCoroutine(LoadGameScene());
  51. return;
  52. }
  53. #endif
  54. OnStart();
  55. if (_checking != null)
  56. {
  57. StopCoroutine(_checking);
  58. }
  59. _checking = Checking();
  60. StartCoroutine(_checking);
  61. }
  62. private IEnumerator LoadGameScene()
  63. {
  64. OnMessage("正在初始化");
  65. var init = LoadModule.Initialize();
  66. yield return init;
  67. if (string.IsNullOrEmpty(init.error))
  68. {
  69. LoadModule.AddSearchPath("Assets/_Scenes");
  70. init.Release();
  71. OnProgress(0);
  72. OnMessage("加载游戏场景");
  73. //var scene = LoadModule.LoadSceneAsync(gameScene, false);
  74. //while (!scene.isDone)
  75. //{
  76. // OnProgress(scene.progress);
  77. // yield return null;
  78. //}
  79. }
  80. else
  81. {
  82. init.Release();
  83. //var mb = MessageBox.Show("提示", "初始化异常错误:" + init.error + "请联系技术支持");
  84. //yield return mb;
  85. Quit();
  86. }
  87. }
  88. private void OnComplete()
  89. {
  90. //if (enableVFS)
  91. //{
  92. // string dataPath = _savePath + Versions.Dataname;
  93. // var downloads = _downloader.downloads;
  94. // if (downloads.Count > 0 && File.Exists(dataPath))
  95. // {
  96. // OnMessage("更新本地版本信息");
  97. // var files = new List<VFile>(downloads.Count);
  98. // foreach (var download in downloads)
  99. // {
  100. // files.Add(new VFile
  101. // {
  102. // name = download.name,
  103. // hash = download.hash,
  104. // len = download.len,
  105. // });
  106. // }
  107. // var file = files[0];
  108. // if (!file.name.Equals(Versions.Dataname))
  109. // Versions.UpdateDisk(dataPath, files);
  110. // }
  111. // Versions.LoadDisk(dataPath);
  112. //}
  113. //OnProgress(1);
  114. //OnMessage("更新完成");
  115. //var version = Versions.LoadVersion(_savePath + Versions.Filename);
  116. //if (version > 0)
  117. // OnVersion(version.ToString());
  118. StartCoroutine(LoadGameScene());
  119. }
  120. public void Clear()
  121. {
  122. }
  123. private void Quit()
  124. {
  125. #if UNITY_EDITOR
  126. UnityEditor.EditorApplication.isPlaying = false;
  127. #else
  128. Application.Quit();
  129. #endif
  130. }
  131. private void OnDestroy()
  132. {
  133. }
  134. //private void AddDownload(VFile item)
  135. //{
  136. // //_downloader.AddDownload(GetDownloadURL(item.name), item.name, _savePath + item.name, item.hash, item.len);
  137. //}
  138. //private void PrepareDownloads()
  139. //{
  140. // if (enableVFS)
  141. // {
  142. // var path = string.Format("{0}{1}", _savePath, Versions.Dataname);
  143. // if (!File.Exists(path))
  144. // {
  145. // //AddDownload(_versions[0]);
  146. // return;
  147. // }
  148. // Versions.LoadDisk(path);
  149. // }
  150. // for (var i = 1; i < _versions.Count; i++)
  151. // {
  152. // var item = _versions[i];
  153. // if (Versions.IsNew(string.Format("{0}{1}", _savePath, item.name), item.len, item.hash))
  154. // // AddDownload(item);
  155. // }
  156. //}
  157. #region Get
  158. private static string GetPlatformForAssetBundles(RuntimePlatform target)
  159. {
  160. // ReSharper disable once SwitchStatementMissingSomeCases
  161. switch (target)
  162. {
  163. case RuntimePlatform.Android:
  164. return "Android";
  165. case RuntimePlatform.IPhonePlayer:
  166. return "iOS";
  167. case RuntimePlatform.WebGLPlayer:
  168. return "WebGL";
  169. case RuntimePlatform.WindowsPlayer:
  170. case RuntimePlatform.WindowsEditor:
  171. return "Windows";
  172. case RuntimePlatform.OSXEditor:
  173. case RuntimePlatform.OSXPlayer:
  174. return "iOS"; // OSX
  175. default:
  176. return null;
  177. }
  178. }
  179. private string GetDownloadURL(string filename)
  180. {
  181. return string.Format("{0}{1}/{2}", baseURL, _platform, filename);
  182. }
  183. private static string GetStreamingAssetsPath()
  184. {
  185. if (UnityEngine.Application.platform == RuntimePlatform.Android)
  186. return UnityEngine.Application.streamingAssetsPath;
  187. if (UnityEngine.Application.platform == RuntimePlatform.WindowsPlayer ||
  188. UnityEngine.Application.platform == RuntimePlatform.WindowsEditor)
  189. return "file:///" + UnityEngine.Application.streamingAssetsPath;
  190. return "file://" + UnityEngine.Application.streamingAssetsPath;
  191. }
  192. #endregion
  193. #region Step
  194. /// <summary>
  195. /// 主协程,状态推进器
  196. /// </summary>
  197. /// <returns></returns>
  198. private IEnumerator Checking()
  199. {
  200. if (!Directory.Exists(_savePath))
  201. {
  202. Directory.CreateDirectory(_savePath);
  203. }
  204. if (_step == Step.Wait)
  205. {
  206. if (enableVFS)
  207. _step = Step.Copy;
  208. else
  209. {
  210. yield return null;
  211. _step = Step.Copy;
  212. }
  213. }
  214. if (_step == Step.Copy)
  215. {
  216. // yield return RequestCopy();
  217. }
  218. if (_step == Step.Coping)
  219. {
  220. //var path = _savePath + Versions.Filename + ".tmp";
  221. //List<VFile> versions = Versions.LoadVersions(path);
  222. //var basePath = GetStreamingAssetsPath() + "/";
  223. //yield return UpdateCopy(versions, basePath);
  224. _step = Step.Versions;
  225. }
  226. if (_step == Step.Versions)
  227. {
  228. // yield return RequestVersions();
  229. }
  230. if (_step == Step.Prepared)
  231. {
  232. //OnMessage("正在检查版本信息...");
  233. //var totalSize = _downloader.size;
  234. //if (totalSize > 0)
  235. //{
  236. // var tips = string.Format("发现内容更新,总计需要下载 {0} 内容", Downloader.GetDisplaySize(totalSize));
  237. // var mb = MessageBox.Show("提示", tips, "下载", "退出");
  238. // yield return mb;
  239. // if (mb.isOk)
  240. // {
  241. // _downloader.StartDownload();
  242. _step = Step.Download;
  243. // }
  244. // else
  245. // {
  246. // Quit();
  247. // }
  248. }
  249. else
  250. {
  251. OnComplete();
  252. }
  253. }
  254. //private IEnumerator RequestVFS()
  255. //{
  256. // var mb = MessageBox.Show("提示", "是否开启VFS?开启有助于提升IO性能和数据安全。", "开启");
  257. // yield return mb;
  258. // enableVFS = mb.isOk;
  259. //}
  260. //private IEnumerator RequestCopy()
  261. //{
  262. // var v1 = Versions.LoadVersion(_savePath + Versions.Filename);
  263. // var basePath = GetStreamingAssetsPath() + "/";
  264. // var request = UnityWebRequest.Get(basePath + Versions.Filename);
  265. // var path = _savePath + Versions.Filename + ".tmp";
  266. // request.downloadHandler = new DownloadHandlerFile(path);
  267. // // 请求版本文件
  268. // yield return request.SendWebRequest();
  269. // if (string.IsNullOrEmpty(request.error))
  270. // {
  271. // int v2 = Versions.LoadVersion(path);
  272. // // 服务器版本号大于本地版本号==》解压
  273. // if (v2 > v1)
  274. // {
  275. // var mb = MessageBox.Show("提示", "是否将资源解压到本地?", "解压", "跳过");
  276. // yield return mb;
  277. // _step = mb.isOk ? Step.Coping : Step.Versions;
  278. // }
  279. // else
  280. // {
  281. // Versions.LoadVersions(path);
  282. // _step = Step.Versions;
  283. // }
  284. // }
  285. // else
  286. // _step = Step.Versions;
  287. // request.Dispose();
  288. //}
  289. //private IEnumerator UpdateCopy(IList<VFile> versions, string basePath)
  290. //{
  291. // VFile version = versions[0];
  292. // if (version.name.Equals(Versions.Dataname))
  293. // {
  294. // var request = UnityWebRequest.Get(basePath + version.name);
  295. // request.downloadHandler = new DownloadHandlerFile(_savePath + version.name);
  296. // var req = request.SendWebRequest();
  297. // while (!req.isDone)
  298. // {
  299. // OnMessage("正在复制文件");
  300. // OnProgress(req.progress);
  301. // yield return null;
  302. // }
  303. // request.Dispose();
  304. // }
  305. // else
  306. // {
  307. // for (var index = 0; index < versions.Count; index++)
  308. // {
  309. // var item = versions[index];
  310. // var request = UnityWebRequest.Get(basePath + item.name);
  311. // request.downloadHandler = new DownloadHandlerFile(_savePath + item.name);
  312. // yield return request.SendWebRequest();
  313. // request.Dispose();
  314. // OnMessage(string.Format("正在复制文件:{0}/{1}", index, versions.Count));
  315. // OnProgress(index * 1f / versions.Count);
  316. // }
  317. // }
  318. //}
  319. /// <summary>
  320. /// 获取版本信息
  321. /// </summary>
  322. /// <returns></returns>
  323. //private IEnumerator RequestVersions()
  324. //{
  325. // OnMessage("正在获取版本信息...");
  326. // if (Application.internetReachability == NetworkReachability.NotReachable)
  327. // {
  328. // var mb = MessageBox.Show("提示", "请检查网络连接状态", "重试", "退出");
  329. // yield return mb;
  330. // if (mb.isOk)
  331. // StartUpdate();
  332. // else
  333. // Quit();
  334. // yield break;
  335. // }
  336. // var url = GetDownloadURL(Versions.Filename);
  337. // GameLog.Log(url);
  338. // var request = UnityWebRequest.Get(url);
  339. // request.downloadHandler = new DownloadHandlerFile(_savePath + Versions.Filename);
  340. // yield return request.SendWebRequest();
  341. // var error = request.error;
  342. // request.Dispose();
  343. // if (!string.IsNullOrEmpty(error))
  344. // {
  345. // var mb = MessageBox.Show("提示", string.Format("获取服务器版本失败:{0}", error), "重试", "退出");
  346. // yield return mb;
  347. // if (mb.isOk)
  348. // StartUpdate();
  349. // else
  350. // Quit();
  351. // yield break;
  352. // }
  353. // try
  354. // {
  355. // _versions = Versions.LoadVersions(_savePath + Versions.Filename, true);
  356. // if (_versions.Count > 0)
  357. // {
  358. // //PrepareDownloads();
  359. // _step = Step.Prepared;
  360. // }
  361. // else
  362. // OnComplete();
  363. // }
  364. // catch (Exception e)
  365. // {
  366. // GameLog.LogException(e);
  367. // MessageBox.Show("提示", "版本文件加载失败", "重试", "退出").onComplete +=
  368. // delegate (MessageBox.EventId id)
  369. // {
  370. // if (id == MessageBox.EventId.Ok)
  371. // StartUpdate();
  372. // else
  373. // Quit();
  374. // };
  375. // }
  376. //}
  377. #endregion
  378. #region IUpdater
  379. public void OnMessage(string msg)
  380. {
  381. if (listener != null)
  382. {
  383. listener.OnMessage(msg);
  384. }
  385. }
  386. public void OnProgress(float progress)
  387. {
  388. if (listener != null)
  389. {
  390. listener.OnProgress(progress);
  391. }
  392. }
  393. public void OnVersion(string ver)
  394. {
  395. if (listener != null)
  396. {
  397. listener.OnVersion(ver);
  398. }
  399. }
  400. //private void OnUpdate(long progress, long size, float speed)
  401. //{
  402. // //OnMessage(string.Format("下载中...{0}/{1}, 速度:{2}",
  403. // // Downloader.GetDisplaySize(progress),
  404. // // Downloader.GetDisplaySize(size),
  405. // // Downloader.GetDisplaySpeed(speed)));
  406. // //OnProgress(progress * 1f / size);
  407. //}
  408. public void OnStart()
  409. {
  410. if (listener != null)
  411. {
  412. listener.OnStart();
  413. }
  414. }
  415. public void OnClear()
  416. {
  417. OnMessage("数据清除完毕");
  418. OnProgress(0);
  419. //_versions.Clear();
  420. //_downloader.Clear();
  421. _step = Step.Wait;
  422. _reachabilityChanged = false;
  423. LoadModule.Clear();
  424. if (listener != null)
  425. {
  426. listener.OnClear();
  427. }
  428. if (Directory.Exists(_savePath))
  429. {
  430. Directory.Delete(_savePath, true);
  431. }
  432. }
  433. #endregion
  434. #region INetworkMonitorListener
  435. private bool _reachabilityChanged;
  436. //public void OnReachablityChanged(NetworkReachability reachability)
  437. //{
  438. // if (_step == Step.Wait)
  439. // return;
  440. // _reachabilityChanged = true;
  441. // if (_step == Step.Download)
  442. // //_downloader.Stop();
  443. // if (reachability == NetworkReachability.NotReachable)
  444. // {
  445. // MessageBox.Show("提示!", "找不到网络,请确保手机已经联网", "确定", "退出").onComplete += delegate (MessageBox.EventId id)
  446. // {
  447. // if (id == MessageBox.EventId.Ok)
  448. // {
  449. // if (_step == Step.Download)
  450. // _downloader.Restart();
  451. // else
  452. // StartUpdate();
  453. // _reachabilityChanged = false;
  454. // }
  455. // else
  456. // Quit();
  457. // };
  458. // }
  459. // else
  460. // {
  461. // if (_step == Step.Download)
  462. // _downloader.Restart();
  463. // else
  464. // StartUpdate();
  465. // _reachabilityChanged = false;
  466. // MessageBox.CloseAll();
  467. // }
  468. //}
  469. private void OnApplicationFocus(bool hasFocus)
  470. {
  471. if (_reachabilityChanged || _step == Step.Wait)
  472. return;
  473. if (hasFocus)
  474. {
  475. //MessageBox.CloseAll();
  476. if (_step == Step.Download)
  477. {
  478. }
  479. // _downloader.Restart();
  480. else
  481. StartUpdate();
  482. }
  483. else
  484. {
  485. if (_step == Step.Download)
  486. {
  487. }
  488. //_downloader.Stop();
  489. }
  490. }
  491. #endregion
  492. }