Esempio n. 1
0
        //根据解析出来的map文件,比较本地文件的md5,如果不同,则需要重新下载
        private int checkLocalFileMD5()
        {
            UpdateLog.DEBUG_LOG("检查本地文件md5+++");

            int ret   = CodeDefine.RET_SUCCESS;
            int total = _parsedMapDataList.Count;

            _checkedCount = 0;

            for (int i = 0; i < _parsedMapDataList.Count; i++)
            {
                MapFileData fileData = _parsedMapDataList[i];
                if (fileData.Name.ToLower().Contains("localversion.xml") || fileData.Name.ToLower().Contains("resourceassetbundles"))
                {
                    continue;
                }
                string localFile    = (_storeDir + "/" + fileData.Dir + fileData.Name).Replace("\\", "/").Replace("//", "/");
                string localFileMD5 = MD5.MD5File(localFile);
                if (localFileMD5.Equals("") || fileData.Md5.Equals(localFileMD5) == false)
                {
                    MapFileDataListForDownload.Add(fileData);
                }
                _checkedCount++;
            }

            if (_checkedCount > 0)
            {
                UpdateLog.WARN_LOG("需要下载文件");
            }

            UpdateLog.DEBUG_LOG("检查本地文件md5---");
            return(ret);
        }
Esempio n. 2
0
        private int repairResource()
        {
            int ret = CodeDefine.RET_INIT;

            if (_mapFileDataList == null || _mapFileDataList.Count == 0)
            {
                ret = CodeDefine.RET_SUCCESS;
                UpdateLog.DEBUG_LOG("没有资源需要修复");
                updateLocalPathVersion();
                return(ret);
            }
            UpdateLog.DEBUG_LOG("开始资源修复");

            for (int i = 0; i < _mapFileDataList.Count; ++i)
            {
                _totalSize += _mapFileDataList[i].FileSize;
            }

            if (!Pause(_totalSize))
            {
                ret = CodeDefine.RET_SKIP_BY_CANCEL;
            }
            else
            {
                ret = _repairDownload.DownloadFileByMultiThread(_mapFileDataList);
            }

            if (ret >= CodeDefine.RET_SUCCESS)
            {
                updateLocalPathVersion();
            }

            return(ret);
        }
Esempio n. 3
0
        public void threadFunc()
        {
            while (_stop == false)
            {
                T data = getTask();
                if (data == null)
                {
                    Console.WriteLine(Thread.CurrentThread.Name + " is sleeping");
                    Thread.Sleep(20);
                    if (_waitWhileWorking)
                    {
                        lock (_taskList)
                        {
                            if (_taskList.Count == 0)
                            {
                                return;
                            }
                        }
                    }
                }
                else
                {
                    dowork(data);
                }
            }

            UpdateLog.DEBUG_LOG("Thread abort: " + Thread.CurrentThread.Name);
        }
Esempio n. 4
0
 /// <summary>
 /// 普通资源下载
 /// </summary>
 private void ThreadFunc()
 {
     while (!_stop)
     {
         if (_pause)
         {
             UpdateLog.DEBUG_LOG("Thread pause : " + Thread.CurrentThread.Name);
             _threadManger.Reset();
             _threadManger.WaitOne();
         }
         T task = GetTask();
         if (task == null)
         {
             if (!_stop)
             {
                 _threadManger.Reset();
                 _threadManger.WaitOne();
             }
         }
         else
         {
             Dowork(task);
         }
     }
     UpdateLog.DEBUG_LOG("Thread abort: " + Thread.CurrentThread.Name);
 }
Esempio n. 5
0
        public override int Work()
        {
            if (!CheckLastFlowResult())
            {
                return(LastFlowResult);
            }
            UpdateLog.DEBUG_LOG("下载base资源+++");
            int ret = CodeDefine.RET_FAIL;

            if (!_backDownload && needTransResource())
            {
                ret = CodeDefine.RET_SKIP_BY_FORCE_TRANS_RESOURCE;
                return(ret);
            }

            //本地段号为0时,强制做分段资源下载,下载第一段,当段号为0时,前面就已经做了转移资源了
            if (_localBaseResVersion == "0" || _enableDwonBase)
            {
                ret = DownloadBaseRes(false);
            }
            else if (_backDownload)
            {
                BackgroundDownload();
                ret = CodeDefine.RET_SKIP_BY_BACKDOWNLOAD;
            }
            else
            {
                ret = CodeDefine.RET_SUCCESS;
                UpdateLog.DEBUG_LOG("不需要下载分段资源");
            }

            UpdateLog.DEBUG_LOG("下载base资源---");
            return(ret);
        }
Esempio n. 6
0
        private int parseMapFiles()
        {
            UpdateLog.DEBUG_LOG("解析map文件+++");
            int num = 1;

            RepairList.Clear();
            this.BackDownloadList.Clear();
            _backDownloadDict.Clear();
            this._parsedMapDataList.Clear();
            string resourceUrl = "";

            for (int i = 0; i < this._currentData.VersionModelBaseList.Count; i++)
            {
                VersionModel model   = this._currentData.VersionModelBaseList[i];
                string       str2    = model.Map_url.Replace(@"\", "/");
                string       str3    = str2.Substring(str2.LastIndexOf("/") + 1);
                string       mapFile = Path.Combine(BaseFlow._storeDir, str3);
                resourceUrl = model.ResourceUrl;
                MapFileManage manage = new MapFileManage();
                num = manage.parseMapFile(mapFile, model.ResourceUrl, BaseFlow._storeDir);
                if (num <= -1)
                {
                    return(num);
                }
                this._parsedMapDataList.AddRange(manage.GetMapFileDataList());
            }
            UpdateLog.DEBUG_LOG("解析map文件---");
            return(num);
        }
Esempio n. 7
0
        /// <summary>
        /// 当前场景资源是否下载完了
        /// 需要判断队列中是否存在和是否正在下载
        /// </summary>
        /// <returns></returns>
        public bool IsCurSceneDownloadFinish()
        {
            int  curCount    = BackDownload.GetDataCount(DataLevel.CurScene);
            bool downloading = BackDownload.IsDateLevelDownloading(DataLevel.CurScene);

            UpdateLog.DEBUG_LOG(string.Format("当前场景资源个数剩余:{0} {1} ,是否还有正在下载的:{2}", curCount, DataLevel.CurScene, downloading));
            return(curCount == 0 && downloading == false);
        }
Esempio n. 8
0
 /// <summary>
 /// 检查上一个流程的结果
 /// </summary>
 /// <returns>true: 继续执行  false: 跳过</returns>
 public bool CheckLastFlowResult()
 {
     //失败或者跳过
     if (LastFlowResult < CodeDefine.RET_SUCCESS || LastFlowResult == CodeDefine.RET_SKIP_BY_CANCEL)
     {
         UpdateLog.DEBUG_LOG("Skip flow: " + GetType().Name);
         return(false);
     }
     return(true);
 }
Esempio n. 9
0
        public int BackgroundDownload()
        {
            UpdateLog.DEBUG_LOG("后台下载base资源+++");
            int ret = CodeDefine.RET_FAIL;

            ret = DownloadBaseRes(true);

            UpdateLog.DEBUG_LOG("后台下载base资源---");
            return(ret);
        }
Esempio n. 10
0
 private void callFinish(int ret)
 {
     if (_finishCallback != null)
     {
         _finishCallback(ret >= CodeDefine.RET_SUCCESS, ret);
     }
     else
     {
         UpdateLog.DEBUG_LOG("没有找到FinishCallback 回调函数");
     }
 }
Esempio n. 11
0
        //判断是否需要转移资源
        private bool checkNeedTrans()
        {
            UpdateLog.DEBUG_LOG("检查是否需要转移资源");
            bool            ret              = false;
            LocalVersionXml localXml         = getOldXmlData(_storedLocalXmlPath);
            string          storedAppVersion = localXml == null ? "" : localXml.LocalAppVersion;
            string          hasCopy          = localXml == null ? "" : localXml.HasCopy;

            //存储的app版本号不存在(没释放过资源, 本地LocalVersion.xml不存在)
            if (string.IsNullOrEmpty(storedAppVersion))
            {
                if (_inAppBaseVersion == "0")
                {
                    //同时包内分段号为0,则说明是下载器,需要强制释放资源
                    ret = true;
                    UpdateLog.DEBUG_LOG("inAppBaseVerson==0,需要强制转移资源");
                }
                else if (_platformType == PlatformType.IOS && !_forceTrans)
                {
                    string inAppXmlAppVer = getIOSAppVerInXml(_inAppLocalXmlPath);
                    if (!string.IsNullOrEmpty(inAppXmlAppVer) && _inAppClientVersion.CompareTo(inAppXmlAppVer) > 0)
                    {
                        ret = true;
                        UpdateLog.DEBUG_LOG("IOS平台,包内版本比包内xml中app版本更高,需要转移资源");
                    }
                    else
                    {
                        //没释放过资源,并且是ios平台,分段号又不为0,说明包内有资源可以运行,不做资源释放
                        ret = false;
                        UpdateLog.DEBUG_LOG("游戏启动,IOS平台,跳过转移资源");
                    }
                }
                else
                {
                    ret = true;
                    UpdateLog.DEBUG_LOG("需要转移资源");
                }
            }
            else if (_inAppClientVersion.CompareTo(storedAppVersion) > 0 || hasCopy.ToLower() != _hasCopyTag)
            {
                UpdateLog.DEBUG_LOG(string.Format("_inAppClientVersion={0} storedAppVersion={1} hasCopy={2}", _inAppClientVersion, storedAppVersion, hasCopy));
                //包内版本比本地版本要大,说明是新客户端,需要做新资源释放覆盖
                ret = true;
                UpdateLog.DEBUG_LOG("客户端更新或者上次转移失败,需要重新转移资源");
            }
            else
            {
                UpdateLog.DEBUG_LOG("不需要转移资源");
            }

            return(ret);
        }
Esempio n. 12
0
        private void transIOSRes()
        {
            UpdateLog.DEBUG_LOG("Trans resource from ipa!!!");
            string streamPath = _resourcePath;// Application.streamingAssetsPath;

            if (!Directory.Exists(streamPath))
            {
                UpdateLog.ERROR_LOG("转移资源无效,不是有效文件夹路径: " + streamPath);
                return;
            }
            _winFiles  = new List <string>(Directory.GetFiles(streamPath, "*", SearchOption.AllDirectories));
            nReadCount = _winFiles.Count;
            while (true)
            {
                string file = null;
                if (_winFiles.Count > 0)
                {
                    file = _winFiles[0];
                    _winFiles.RemoveAt(0);
                }
                if (file != null)
                {
                    try
                    {
                        string oldFilePath = file.Replace('\\', '/');
                        string newFilePath = file.Replace(streamPath, _outPath).Replace('\\', '/');
                        string fullPath    = newFilePath.Substring(0, newFilePath.LastIndexOf('/'));
                        if (!Directory.Exists(fullPath))
                        {
                            Directory.CreateDirectory(fullPath);
                        }
                        CopyFile(oldFilePath, newFilePath);
                        nWriteCount++;
                    }
                    catch (IOException ex)
                    {
                        UpdateLog.ERROR_LOG(ex.Message);
                    }
                }
                else
                {
                    break;
                }
                //Thread.Sleep(10);
            }

            Thread.Sleep(50);
            _success = (nWriteCount == nReadCount && nWriteCount != 0);

            UpdateLog.ERROR_LOG(string.Format("转移资源结束 {0}/{1}", nWriteCount, nReadCount));
        }
Esempio n. 13
0
        /// <summary>
        /// 保存文件
        /// </summary>
        /// <param name="baseVersion"></param>
        /// <param name="patchVersion"></param>
        /// <param name="hasCopy"></param>
        /// <param name="appVersion"></param>
        /// <returns></returns>
        public int save(string baseVersion = "", string patchVersion = "", string hasCopy = "", string appVersion = "")
        {
            UpdateLog.INFO_LOG(_TAG + "save()");
            int  ret       = CodeDefine.RET_SUCCESS;
            bool hasChange = false;

            try
            {
                if (!"".Equals(baseVersion) && baseVersion != _baseResVersion)
                {
                    _baseResVersion = baseVersion;
                    set(dom, "local_info/local_base_res_version", baseVersion);
                    hasChange = true;
                }
                if (!"".Equals(patchVersion) && patchVersion != _patchResVersion)
                {
                    _patchResVersion = patchVersion;
                    hasChange        = true;
                    set(dom, "local_info/local_patch_res_version", patchVersion);
                }
                if (!"".Equals(hasCopy) && hasCopy != _hasCopy)
                {
                    _hasCopy  = hasCopy;
                    hasChange = true;
                    set(dom, "local_info/hasCopy", hasCopy);
                }
                if (!"".Equals(appVersion) && appVersion != _localAppVersion)
                {
                    _localAppVersion = appVersion;
                    hasChange        = true;
                    set(dom, "local_info/local_app_version", appVersion);
                }
                if (hasChange)
                {
                    MonoXmlUtils.SaveXml(_localVersionXml, dom);
                }
                else
                {
                    UpdateLog.DEBUG_LOG("没有改动,不保存localversion.xml");
                }
            }
            catch (System.Exception ex)
            {
                ret = CodeDefine.RET_FAIL_SAVE_LOCAL_XML_FILE;
                UpdateLog.ERROR_LOG(_TAG + ex.Message + "\n" + ex.StackTrace);
                UpdateLog.EXCEPTION_LOG(ex);
            }

            return(ret);
        }
Esempio n. 14
0
        public override int Work()
        {
            if (!CheckLastFlowResult())
            {
                return(LastFlowResult);
            }
            UpdateLog.DEBUG_LOG("资源修复++++");
            int ret = CodeDefine.RET_INIT;

            ret = repairResource();
            UpdateLog.DEBUG_LOG("资源修复----");

            return(ret);
        }
Esempio n. 15
0
        public int DownloadBaseRes(bool downloadAll)
        {
            int ret = CodeDefine.RET_FAIL;

            _needDownloadList = needDownloadBaseResList();
            if (_needDownloadList.Count == 0)
            {
                UpdateLog.INFO_LOG("do not need download base res, the version is the latest one. : version = " + _localBaseResVersion);
                return(CodeDefine.RET_SUCCESS);
            }

            int currentState = 0;

            for (int i = 0; i < _needDownloadList.Count; i++)
            {
                currentState = int.Parse(_needDownloadList[i].ToVersion);
                var    toDownloadModel = _needDownloadList[i];
                string resourceUrl     = toDownloadModel.ResourceUrl.Replace("\\", "/");
                string resName         = resourceUrl.Substring(resourceUrl.LastIndexOf("/") + 1);
                string storePath       = System.IO.Path.Combine(_storeDir, resName);
                long   downloadedSize  = 0;
                if (checkFinishDownload(storePath, toDownloadModel, out downloadedSize))
                {
                    ret = CodeDefine.RET_SUCCESS;
                    UpdateLog.INFO_LOG("分段资源已经下载好了: " + storePath);
                    continue;
                }
                long totalSize        = long.Parse(toDownloadModel.FileSize);
                long mapSize          = long.Parse(toDownloadModel.Map_size);
                long needDownloadSize = totalSize - downloadedSize;
                UpdateLog.INFO_LOG("UpdateFlow: 需要下载基础资源 " + storePath + "totalSize = " + totalSize + " needDownloadSize=" + needDownloadSize);

                //后台下载不做提示
                if (!_backDownload && !Pause((int)totalSize))
                {
                    return(CodeDefine.RET_SKIP_BY_CANCEL);
                }

                ret = _fileDownload.DownloadUseBackCdn(storePath, toDownloadModel.ResourceUrl, (int)totalSize, true);

                //失败、非all、非后台下载都中断
                if (ret <= CodeDefine.RET_FAIL || !downloadAll || !_backDownload)
                {
                    break;
                }
            }

            UpdateLog.DEBUG_LOG("下载base资源---");
            return(ret);
        }
Esempio n. 16
0
        private int checkLocalFileMD5()
        {
            UpdateLog.DEBUG_LOG("检查本地文件md5+++");
            int count = this._parsedMapDataList.Count;

            this._checkedCount = 0;
            for (int i = 0; i < this._parsedMapDataList.Count; i++)
            {
                this._checkedCount++;
                MapFileData item = this._parsedMapDataList[i];
                string      path = BaseFlow._storeDir + "/" + item.Dir + item.Name;
                if (item.Name.ToLower().IndexOf("localversion.xml") == -1 || item.Name.ToLower().IndexOf("resourceassetbundles") == -1)
                {
                    string str2 = BaseFlow._appDir + "/" + item.Dir + item.Name;
                    if (File.Exists(path) || File.Exists(str2))
                    {
                        string str3 = MD5.MD5File(path);
                        if (string.IsNullOrEmpty(str3))
                        {
                            str3 = MD5.MD5File(str2);
                        }
                        if (!(!str3.Equals("") && item.Md5.Equals(str3)))
                        {
                            RepairList.Add(item);
                        }
                    }
                    else
                    {
                        if (item.Name.ToLower().IndexOf("resourceassetbundles") == -1)
                        {
                            RepairList.Add(item);
                            continue;
                            //后台下载(是否后台下载)
                            _backDownloadDict.Add(path, item);
                            this.BackDownloadList.Add(item);
                        }
                    }
                }
            }
            if (this._checkedCount > 0)
            {
                UpdateLog.WARN_LOG("需要下载文件");
            }

            MapFileDataListForDownload = RepairList;

            UpdateLog.DEBUG_LOG("检查本地文件md5---");
            return(1);
        }
Esempio n. 17
0
        //线程回调方法,用来做具体的下载动作
        public void ThreadCallBack(object state)
        {
            if (_abort)
            {
                return;
            }

            MapFileData fileData     = (MapFileData)state;
            string      saveFilePath = fileData.SaveDir + "/" + fileData.Dir + fileData.Name;

            //如果下载的文件失败个数超过10个,那么后面的文件就没有必要再下载了,需要检查网络
            lock (this._failDownloadFile)
            {
                if (_failDownloadFile.Count >= _MAX_ERROR_LIMIT)
                {
                    _failDownloadFile.Add(fileData);
                    return;
                }
            }

            int ret = downloadMapData(fileData, saveFilePath);

            lock (m_locker)
            {
                _currentDownloadFileCount++;

                if (ret == CodeDefine.RET_SKIP_BY_ABORT)
                {
                    UpdateLog.DEBUG_LOG("abort download: " + Thread.CurrentThread.Name);
                    return;
                }

                //当前文件下载失败,放到失败列表中
                if (ret <= CodeDefine.RET_FAIL)
                {
                    _failDownloadFile.Add(fileData);
                    return;
                }

                //文件下载成功后,对比md5是否正确,不正确也放到失败队列中
                string downloadFileMD5 = MD5.MD5File(saveFilePath);
                if (string.IsNullOrEmpty(downloadFileMD5) || !fileData.Md5.Equals(downloadFileMD5))
                {
                    _failDownloadFile.Add(fileData);
                }
            }
        }
Esempio n. 18
0
 /// <summary>
 /// 中断下载
 /// </summary>
 /// <param name="callback"></param>
 internal static void AbortAll(AbortFinishCallback callback)
 {
     UpdateLog.DEBUG_LOG("Abort back download!!!");
     lock (m_locker)
     {
         if (_threadPool != null)
         {
             _threadPool.WaitForFinish();
         }
         for (int i = 0; i < _httpInsList.Count; i++)
         {
             _httpInsList[i].Abort(null);
         }
     }
     if (callback != null)
     {
         callback(true);
     }
 }
Esempio n. 19
0
        public override int Work()
        {
            UpdateLog.DEBUG_LOG("更新流程结束++++");
            int ret = LastFlowResult;

            if (ret >= CodeDefine.RET_SUCCESS)
            {
                UpdateLog.DEBUG_LOG("更新流程正常结束");
            }
            else
            {
                UpdateLog.DEBUG_LOG("更新失败 ret=" + ret);
            }

            UpdateLog.DEBUG_LOG("更新流程结束----");

            callFinish(ret);

            return(ret);
        }
Esempio n. 20
0
        //解析本地所有的map文件
        private int parseMapFiles()
        {
            UpdateLog.DEBUG_LOG("解析map文件+++");
            int ret = CodeDefine.RET_SUCCESS;

            MapFileDataListForDownload.Clear();
            _parsedMapDataList.Clear();

            string resUrl = "";

            for (int i = 0; i < _currentData.VersionModelBaseList.Count; i++)
            {
                VersionModel mapModel = _currentData.VersionModelBaseList[i];

                //分段版本比本地分段更大,则跳过解析,本地可能没有
                if (LocalXml.BaseResVersion.CompareTo(mapModel.ToVersion.Replace("。", ".")) < 0)
                {
                    continue;
                }

                string mapUrl  = mapModel.Map_url.Replace("\\", "/");
                string mapName = mapUrl.Substring(mapUrl.LastIndexOf("/") + 1);
                UnityEngine.Debug.Log("mapName:" + mapName);
                string localMapFile = System.IO.Path.Combine(_storeDir, mapName);
                resUrl = mapModel.ResourceUrl;
                MapFileManage mapManager = new MapFileManage();
                ret = mapManager.parseMapFile(localMapFile, mapModel.ResourceUrl, _storeDir);

                if (ret <= CodeDefine.RET_FAIL)
                {
                    return(ret);
                }

                _parsedMapDataList.AddRange(mapManager.GetMapFileDataList());
            }

            UpdateLog.DEBUG_LOG("解析map文件---");
            return(ret);
        }
Esempio n. 21
0
 /// <summary>
 /// 高优先级下载
 /// </summary>
 private void HighPriorityThreadFunc()
 {
     while (!_stop)
     {
         if (_dataPool.GetHighPriorityQueueCount() == 0)
         {
             _highPriorityThread.Pause();
         }
         T task = GetTask();
         if (task == null)
         {
             if (!_stop)
             {
                 _highPriorityThread.Pause();
             }
         }
         else
         {
             Dowork(task);
         }
     }
     UpdateLog.DEBUG_LOG("Thread abort: " + Thread.CurrentThread.Name);
 }
Esempio n. 22
0
        public virtual bool Pause(int size = 0)
        {
            ConfirmAfterPause = false;
            _pause            = true;

            if (!_enablePause)
            {
                return(true);
            }

            if (_callDownloadNotice != null)
            {
                _callDownloadNotice(size);
            }

            //等待用户确认
            while (_pause)
            {
                UpdateLog.DEBUG_LOG("有下载,等待用户确认");
                Thread.Sleep(1000);
            }

            return(ConfirmAfterPause);
        }
Esempio n. 23
0
        /// <summary>
        /// 多线程下载文件
        /// </summary>
        /// <param name="mapFileDataList">文件列表</param>
        /// <returns>小于0失败</returns>
        public int DownloadFileByMultiThread(List <MapFileData> mapFileDataList)
        {
            int ret           = CodeDefine.RET_FAIL;
            int allRetryTimes = _RETRAY_TIMES;

            Download.MutiDownloadedSize = 0;
            _abort = false;

            if (mapFileDataList == null)
            {
                ret = CodeDefine.RET_FAIL;
                return(ret);
            }
            while (_failDownloadFile.Count <= _MAX_ERROR_LIMIT && allRetryTimes > 0)
            {
                _currentDownloadFileCount = 0;
                _failDownloadFile.Clear();
                _totalDownloadFileCount = mapFileDataList.Count;

                _threadPool = new HttpThreadPool <MapFileData>(_MAX_THREAD_COUNT, ThreadCallBack);
                for (int i = 0; i < mapFileDataList.Count; i++)
                {
                    MapFileData fileData = mapFileDataList[i];
                    _threadPool.addTask(fileData);
                }

                //等待所有文件下载完
                _threadPool.waitWhileWorking();

                if (_abort)
                {
                    UpdateLog.DEBUG_LOG("abort repaire download!!!");
                    _abort = false;
                    return(CodeDefine.RET_SKIP_BY_ABORT);
                }

                //当失败文件数小于_MAX_ERROR_LIMIT,则这些文件重新加到下载队列里面
                if (_failDownloadFile.Count != 0)
                {
                    for (int i = 0; i < _failDownloadFile.Count; i++)
                    {
                        UpdateLog.DEBUG_LOG("有文件下载失败" + _failDownloadFile[i].Name);
                    }
                    mapFileDataList.Clear();
                    mapFileDataList.AddRange(_failDownloadFile);
                    //_failDownloadFile.Clear();
                    ret = CodeDefine.RET_FAIL;
                }
                else
                {
                    mapFileDataList.Clear();
                    _failDownloadFile.Clear();
                    ret = CodeDefine.RET_SUCCESS;
                    break;
                }
                allRetryTimes--;
            }

            //到这里还有文件没有下载成功,则表示下载失败了
            if (mapFileDataList.Count > 0)
            {
                UpdateLog.DEBUG_LOG("更新失败,有" + mapFileDataList.Count + "个文件下载失败");
            }

            return(ret);
        }
Esempio n. 24
0
        public override int Work()
        {
            if (!CheckLastFlowResult())
            {
                return(LastFlowResult);
            }

            if (!CurrentRemoteData.EnableForceUpdate)
            {
                UpdateLog.DEBUG_LOG("Do not support force update client, skip download!!!");
                return(CodeDefine.RET_SUCCESS);
            }

            UpdateLog.DEBUG_LOG("开始下载客户端+++");
            int    ret        = CodeDefine.RET_INIT;
            var    localXml   = LocalXml;
            var    remoteData = CurrentRemoteData;
            string appVersion = localXml.LocalAppVersion;
            string clientUrl  = remoteData.ClientUrl.Replace("\\", "/");
            string clientName = clientUrl.Substring(clientUrl.LastIndexOf("/") + 1);
            string clientPath = System.IO.Path.Combine(_storeDir, clientName);

            //远端有更高客户端版本,则检查下载
            if (remoteData.AppVersion.CompareTo(appVersion) > 0)
            {
                if (_customDownClientFunc != null)
                {
                    UpdateLog.DEBUG_LOG("使用外部方法下载客户端");
                    _customDownClientFunc(remoteData.ClientUrl, _storeDir);
                    ret = CodeDefine.RET_SUCCESS;
                    callClientDownloadFinish(true);
                }
                else
                {
                    if (_ios)
                    {
                        callClientDownloadFinish(true);
                        return(CodeDefine.RET_SKIP_BY_DOWNLOAD_APP);
                    }

                    int appSize = int.Parse(remoteData.AppSize);

                    //下载前提醒,如果取消则直接退出当前流程
                    if (!Pause(appSize))
                    {
                        return(CodeDefine.RET_SKIP_BY_CANCEL);
                    }

                    ApkStorePath = clientPath;
                    ret          = _fileDownload.DownloadUseBackCdn(clientPath, clientUrl, appSize, true);

                    FileInfo clientFile = new FileInfo(clientPath);
                    if (ret >= CodeDefine.RET_SUCCESS && clientFile.Length < appSize)
                    {
                        ret = CodeDefine.RET_FAIL_EXCEPTION_DOWNLOAD;
                        UpdateLog.ERROR_LOG("download Client: size is not correct: " + clientFile.Length + " -> " + appSize);
                    }
                    callClientDownloadFinish(ret >= CodeDefine.RET_SUCCESS);
                }

                //下载成功则跳过后续流程
                if (ret == CodeDefine.RET_SUCCESS)
                {
                    ret = CodeDefine.RET_SKIP_BY_DOWNLOAD_APP;
                }
                UpdateLog.DEBUG_LOG("下载客户端结束");
            }
            else
            {
                if (File.Exists(clientPath))
                {
                    File.Delete(clientPath);
                    UpdateLog.DEBUG_LOG("删除已下载好的客户端!!!");
                }

                ret = CodeDefine.RET_SUCCESS;
            }
            UpdateLog.DEBUG_LOG("开始下载客户端---");
            return(ret);
        }
Esempio n. 25
0
        /// <summary>
        /// 在线程中执行更新流程
        /// </summary>
        private void updateFlowByThread()
        {
            bool continueFlow = false;

            CurrentFlow = null;
            _abortFlows = false;
            int resultCode   = CodeDefine.RET_SUCCESS;
            int runFlowCount = 0;

            while (true && !_abortFlows)
            {
                BaseFlow oldFlow = null;
                continueFlow = false;
                runFlowCount = 0;
                for (int i = 0; !_abortFlows && i < _flowList.Count; ++i)
                {
                    runFlowCount++;
                    CurrentFlow = _flowList[i];
                    UpdateLog.DEBUG_LOG(CurrentFlow.FlowName());

                    CurrentFlow.OnEnter(oldFlow);
                    resultCode = CurrentFlow.Work();
                    CurrentFlow.OnLeave(resultCode);

                    //更新客户端,跳过所有流程
                    if (resultCode == CodeDefine.RET_SKIP_BY_DOWNLOAD_APP)
                    {
                        UpdateLog.DEBUG_LOG("Download Client finish, skip all left flows!!!");
                        break;
                    }

                    //需要强制释放资源,重新走更新流程
                    if (resultCode == CodeDefine.RET_SKIP_BY_FORCE_TRANS_RESOURCE)
                    {
                        FlowInstance <Flow1TransResource>().SetForceUnzip();
                        continueFlow = true;
                        break;
                    }

                    //中断操作
                    if (resultCode == CodeDefine.RET_SKIP_BY_ABORT)
                    {
                        UpdateLog.DEBUG_LOG("Abort flow -> " + CurrentFlow.FlowName());
                        break;
                    }

                    if (resultCode == CodeDefine.RET_SKIP_BY_DISABLEDOWNLOAD)
                    {
                        UpdateLog.DEBUG_LOG("Not support download, skip all flows!!!");
                        break;
                    }

                    //取消操作
                    if (resultCode == CodeDefine.RET_SKIP_BY_CANCEL)
                    {
                        UpdateLog.DEBUG_LOG("Skip flow by cancel download option, exit game!!!");
                        break;
                    }

                    if (resultCode < CodeDefine.RET_SUCCESS)
                    {
                        break;
                    }

                    oldFlow = CurrentFlow;
                }

                if (!continueFlow)
                {
                    break;
                }
            }

            if (runFlowCount != _flowList.Count)
            {
                FlowInstance <FlowFinish>().FinishWithError(resultCode);
            }

            _threadFinish = true;

            //重新开启
            if (_restart)
            {
                UpdateLog.DEBUG_LOG("Restart update");
                StartUpdate();
            }
            else
            {
                UpdateLog.DEBUG_LOG("Finish update flow!!! " + resultCode);
            }
        }
Esempio n. 26
0
        public override int Work()
        {
            if (LastFlowResult == CodeDefine.RET_SKIP_BY_BACKDOWNLOAD)
            {
                UpdateLog.DEBUG_LOG("因为是后台下载分段,跳过资源释放流程");
                return(CodeDefine.RET_SUCCESS);
            }
            if (!CheckLastFlowResult())
            {
                return(LastFlowResult);
            }
            UpdateLog.DEBUG_LOG("释放分段资源+++");
            int ret = CodeDefine.RET_SUCCESS;

            for (int i = 0; i < _currentData.VersionModelBaseList.Count; i++)
            {
                VersionModel vModel = _currentData.VersionModelBaseList[i];
                //本地分段版本号更大,则跳过
                if (LocalXml.BaseResVersion.CompareTo(vModel.FromVersion) > 0)
                {
                    continue;
                }

                string resourceUrl       = vModel.ResourceUrl.Replace("\\", "/");
                string resourceName      = resourceUrl.Substring(resourceUrl.LastIndexOf("/") + 1);
                string localResourceFile = System.IO.Path.Combine(_storeDir, resourceName);

                if (!File.Exists(localResourceFile))
                {
                    UpdateLog.DEBUG_LOG("释放资源时,没有资源: " + localResourceFile);
                    continue;
                }

                //用大小比较
                FileInfo fileInfo             = new FileInfo(localResourceFile);
                long     toDownloadFileLenght = 0;
                if (long.TryParse(vModel.FileSize, out toDownloadFileLenght))
                {
                    if (fileInfo.Length == toDownloadFileLenght)
                    {
                        if (!HasTransedResource())
                        {
                            UpdateLog.DEBUG_LOG("还没有转移过资源,不能做资源释放,先跳转到转移资源流程!!!");
                            ret = CodeDefine.RET_SKIP_BY_FORCE_TRANS_RESOURCE;
                            break;
                        }

                        UpdateLog.DEBUG_LOG("释放分段资源: " + localResourceFile);
                        UnzipResource unzip = new UnzipResource(localResourceFile, _storeDir);
                        ret = unzip.UnzipRes();

                        //更新本地分段号
                        _localXml.BaseResVersion = vModel.ToVersion;
                        _localXml.save(_localXml);
                        //资源释放完了就删除下载好的资源
                        if (File.Exists(localResourceFile))
                        {
                            File.Delete(localResourceFile);
                        }
                    }
                    else
                    {
                        UpdateLog.DEBUG_LOG(string.Format("分段资源没下载完:{0} -> {1} ", localResourceFile, fileInfo.Length));
                    }
                }
            }

            UpdateLog.DEBUG_LOG("释放分段资源---");
            return(ret);
        }
Esempio n. 27
0
        private void unzipApk()
        {
            UpdateLog.DEBUG_LOG("Trans resource from apk!!!");
            UpdateLog.DEBUG_LOG("_resourcePath=" + _resourcePath);

            //res开始路径,从assets开始
            string APKStreamingAsset = "assets/";
            //跳过的资源路径,bin目录不做拷贝
            string skipResDir = "/bin/";
            string apkPath    = _resourcePath;

            if (!ForTest)
            {
                apkPath = apkPath.Replace("!/assets", "");
                apkPath = apkPath.Replace("jar:file://", "");
            }


            UpdateLog.DEBUG_LOG("apkPath=" + apkPath);
            UpdateLog.DEBUG_LOG("_outPath=" + _outPath);
            FileStream fileStream = null;

            try
            {
                fileStream = File.OpenRead(apkPath);// new FileStream(apkPath, FileMode.Open);
                ZipFile f = new ZipFile(fileStream);
                nReadCount = (Int32)f.Count;
                fileStream.Seek(0, SeekOrigin.Begin);
            }
            catch (System.Exception ex)
            {
                UpdateLog.ERROR_LOG(ex.Message);
            }

            if (fileStream == null)
            {
                UpdateLog.ERROR_LOG("文件读取失败");
                return;
            }

            using (ZipInputStream s = new ZipInputStream(fileStream))
            {
                ZipEntry entry = null;
                while ((entry = s.GetNextEntry()) != null)
                {
                    string unRootPath    = _outPath;
                    string directoryName = Path.GetDirectoryName(entry.Name).Replace("\\", "/") + "/";
                    if (directoryName.Contains(skipResDir))
                    {
                        ++nWriteCount;
                        continue;
                    }
                    if (!directoryName.StartsWith(APKStreamingAsset))
                    {
                        ++nWriteCount;
                        continue;
                    }

                    string fileName = Path.GetFileName(entry.Name);
                    // create directory;
                    if (!string.IsNullOrEmpty(directoryName))
                    {
                        unRootPath = Path.Combine(unRootPath, directoryName);
                        unRootPath = unRootPath.Replace(APKStreamingAsset, "");
                        unRootPath = unRootPath.Replace('\\', '/');
                        if (!Directory.Exists(unRootPath))
                        {
                            Directory.CreateDirectory(unRootPath);
                        }
                    }

                    if (!string.IsNullOrEmpty(fileName))
                    {
                        try
                        {
                            fileName = Path.Combine(unRootPath, fileName);
                            fileName = fileName.Replace('\\', '/');
                            using (FileStream streamWriter = File.Create(fileName))
                            {
                                int    size       = 0;
                                int    bufferSize = 512;
                                byte[] tempBuffer = new byte[bufferSize];
                                while (true)
                                {
                                    size = s.Read(tempBuffer, 0, bufferSize);
                                    if (size > 0)
                                    {
                                        streamWriter.Write(tempBuffer, 0, size);
                                    }
                                    else
                                    {
                                        break;
                                    }
                                }
                                streamWriter.Flush();
                                ++nWriteCount;
                                streamWriter.Close();
                            }
                        }
                        catch (Exception ex)
                        {
                            UpdateLog.ERROR_LOG(ex.Message);
                            UpdateLog.ERROR_LOG("文件损坏: " + entry.Name);
                        }
                        finally
                        {
                        }
                    }
                    else
                    {
                        ++nWriteCount;
                        UpdateLog.ERROR_LOG("trans error, file name is empty: " + entry.Name);
                    }
                }

                Thread.Sleep(50);

                _success = (nWriteCount == nReadCount && nWriteCount != 0);

                UpdateLog.DEBUG_LOG(string.Format("转移资源结束 {0}/{1}", nWriteCount, nReadCount));
            }
        }