Beispiel #1
0
 /// <summary>
 /// 获取当前场景下载信息
 /// </summary>
 /// <param name="total"></param>
 /// <param name="downloaded"></param>
 public void GetCurSceneTotalResSize(out long total, out long downloaded)
 {
     downloaded = 0;
     total      = 0;
     try
     {
         if (_sceneResList.ContainsKey(DataLevel.CurScene))
         {
             var resList = _sceneResList[DataLevel.CurScene];
             for (int i = 0; i < resList.Count; ++i)
             {
                 if (resList[i].Downloaded ||
                     (!resList[i].Downloading && File.Exists(resList[i].FullPath)))
                 {
                     downloaded += resList[i].FileSize;
                 }
                 total += resList[i].FileSize;
             }
         }
     }
     catch (System.Exception ex)
     {
         UpdateLog.ERROR_LOG(ex.Message + "\n" + ex.StackTrace);
     }
 }
Beispiel #2
0
        //下载
        private int downloadRemoteXml(string remoteUrl, string storeDir)
        {
            UpdateLog.INFO_LOG("下载resourceVersionXml " + remoteUrl);
            int ret = CodeDefine.RET_SUCCESS;

            if (string.IsNullOrEmpty(_remoteXmlName))
            {
                UpdateLog.ERROR_LOG("downloadResourceVersion(): resourceXmlName == null || \"\".Equals(resourceXmlName)");
                ret = CodeDefine.RET_FAIL_RES_XML_PATH_ERROR;
                return(ret);
            }

            string savePath = (storeDir + "/" + _remoteXmlName).Replace("\\", "/").Replace("//", "/");

            if (!Directory.Exists(storeDir))
            {
                Directory.CreateDirectory(storeDir);
            }
            if (File.Exists(savePath))
            {
                File.Delete(savePath);
                Thread.Sleep(1);
            }

            ret = _fileDownload.DownloadUseBackCdn(savePath, remoteUrl, 0, false);

            if (ret < CodeDefine.RET_SUCCESS)
            {
                UpdateLog.ERROR_LOG("downloadResourceVersion(): resource file is not exist or download fail!");
                ret = CodeDefine.RET_FAIL_DOWNLOAD_RES_XML;
            }

            return(ret);
        }
Beispiel #3
0
        /// <summary>
        /// 从文件解析
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public int parseLocalVersionXml(string path)
        {
            UpdateLog.INFO_LOG(_TAG + "parseLocalVersionXml(string path):  " + path);

            int ret = CodeDefine.RET_SUCCESS;

            try
            {
                var sp = MonoXmlUtils.LoadXmlEx(path);
                if (sp == null || sp.ToXml() == null)
                {
                    UpdateLog.ERROR_LOG(_TAG + "File not exist or invalid: " + path);
                    return(CodeDefine.RET_FAIL_PARSE_LOCAL_XML_FILE);
                }

                dom = sp.ToXml();
                _localVersionXml = path;
                parse(dom);
            }
            catch (System.Exception ex)
            {
                ret = CodeDefine.RET_FAIL_PARSE_LOCAL_XML_FILE;

                UpdateLog.ERROR_LOG(_TAG + ex.Message + "\n" + ex.StackTrace);
                UpdateLog.EXCEPTION_LOG(ex);
            }

            return(ret);
        }
Beispiel #4
0
        //字符串md5
        public static string MD5String(string text)
        {
            if (string.IsNullOrEmpty(text))
            {
                return("");
            }

            try
            {
                byte[] data = System.Text.Encoding.Default.GetBytes(text);//将字符编码为一个字节序列
                System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
                byte[] retVal = md5.ComputeHash(data);

                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < retVal.Length; i++)
                {
                    sb.Append(retVal[i].ToString("x2"));
                }
                return(sb.ToString());
            }
            catch (Exception ex)
            {
                UpdateLog.ERROR_LOG("calc md5 fail : " + ex.Message + "\n" + ex.StackTrace);
                UpdateLog.EXCEPTION_LOG(ex);
            }

            return("");
        }
Beispiel #5
0
        /// <summary>
        /// 下载单个文件
        /// </summary>
        /// <param name="savePath">保存路径</param>
        /// <param name="url">下载地址</param>
        /// <param name="isContinue">是否断点续传</param>
        /// <param name="isRetryAllways">失败后是否一直重试</param>
        /// <returns>小于0失败</returns>
        public int DownloadFile(string savePath, string url, bool isContinue = true)
        {
            UpdateLog.INFO_LOG(_TAG + "DownloadFile(string strFileName, string url, bool isContinue = true) : " +
                               savePath + "," +
                               url + "," +
                               isContinue);

            int  downloadRet = CodeDefine.RET_FAIL;
            long SPosition   = 0;

            //如果本地有下载文件,则判断是否断点续传
            FileStream FStream = null;

            try
            {
                ExistFileSize = 0;
                if (File.Exists(savePath) && isContinue)
                {
                    //定向文件写入位置
                    FStream   = File.Open(savePath, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
                    SPosition = FStream.Length;
                    FStream.Seek(SPosition, SeekOrigin.Current);
                    //已存在文件大小
                    ExistFileSize = (int)SPosition;
                }
                else
                {
                    FStream   = new FileStream(savePath, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);
                    SPosition = 0;
                }

                //开始下载
                downloadRet = HttpDownload(url, FStream, SPosition);
                if (FStream.CanWrite)
                {
                    FStream.Close();
                }
                Thread.Sleep(_SLEEP_TIME);
            }
            catch (System.Exception ex)
            {
                UpdateLog.ERROR_LOG(ex.Message);
                UpdateLog.EXCEPTION_LOG(ex);
            }
            finally
            {
                if (FStream != null && FStream.CanWrite)
                {
                    FStream.Close();
                }
            }

            return(downloadRet);
        }
Beispiel #6
0
 public static void CopyFile(string sourceFileName, string destFileName)
 {
     try
     {
         File.Copy(sourceFileName, destFileName, true);
     }
     catch (IOException copyError)
     {
         UpdateLog.ERROR_LOG(copyError.Message);
     }
 }
Beispiel #7
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));
        }
Beispiel #8
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);
        }
Beispiel #9
0
 public void StartTrans()
 {
     {
         _forceTrans = false;
         if (_transInstance != null)
         {
             _transInstance.StartUnzipByThread();
         }
         else
         {
             UpdateLog.ERROR_LOG("_transInstance 没有初始化");
         }
     }
 }
Beispiel #10
0
        private static void DownloadAction(MapFileData state)
        {
            MapFileData fileData = state;

            fileData.ErrorCode = CodeDefine.RET_INIT;

            string saveFilePath = fileData.SaveDir + "/" + fileData.Dir + fileData.Name;
            int    num          = DownloadMapData(fileData, saveFilePath);
            string str2         = MD5.MD5File(saveFilePath);
            bool   success      = (num >= CodeDefine.RET_SUCCESS) && fileData.Md5.Equals(str2);

            if (!success)
            {
                UpdateLog.ERROR_LOG("download fail: " + saveFilePath);
                //下载失败,删除已下载文件
                File.Delete(saveFilePath);
                //重置下载状态
                state.Downloading = false;
                //将失败data放回下载队列
                AddFailDataToPool(fileData);

                //如果是因为中止操作造成下载失败,则把文件加入到当前场景下载队列,继续下载
                if (num == CodeDefine.RET_SKIP_BY_ABORT)
                {
                    UpdateLog.ERROR_LOG("download fail because of stop action: " + saveFilePath);
                    //return;
                }
            }
            else
            {
                //累加下载大小
                TotalDownloadedSize += state.FileSize;
            }

            lock (m_downloadedLocker)
            {
                fileData.Downloaded = success;
                if (fileData.DownloadCallBack == null)
                {
                    return;
                }
            }

            if (_finishDownloadCallback != null)
            {
                _finishDownloadCallback(saveFilePath, success, state);
            }
        }
Beispiel #11
0
        /// <summary>
        /// 从xml内容解析
        /// </summary>
        /// <param name="xmlText"></param>
        /// <returns></returns>
        public int ParseFromText(string xmlText)
        {
            try
            {
                var rootNode = MonoXmlUtils.GetRootNodeFromString(xmlText);
                parse(rootNode);
            }
            catch (System.Exception ex)
            {
                UpdateLog.ERROR_LOG(ex.Message + "\n" + ex.StackTrace);
                UpdateLog.EXCEPTION_LOG(ex);
                return(CodeDefine.RET_FAIL);
            }

            return(CodeDefine.RET_SUCCESS);
        }
Beispiel #12
0
        /// <summary>
        /// 下载函数
        /// </summary>
        /// <param name="url">地址</param>
        /// <param name="outFile">输入路径</param>
        /// <param name="begin">起点</param>
        /// <param name="end">终点</param>
        /// <returns>小于0失败</returns>
        public int HttpDownload(string url, FileStream outFile, long begin = 0, long end = 0)
        {
            int num = CodeDefine.RET_INIT;

            _requestIns = null;
            try
            {
                DownloadUrl = url;
                _requestIns = createRequest(url);
                setRange(_requestIns, (int)begin, (int)end);
                requestData(_requestIns, outFile);
                num = CodeDefine.RET_SUCCESS;
            }
            catch (Exception exception)
            {
                UpdateLog.WARN_LOG("catch http instance exception :::" + exception.Message);
                if (!_isAbortOption)
                {
                    UpdateLog.ERROR_LOG(_TAG + exception.Message + "\n" + exception.StackTrace);
                    UpdateLog.EXCEPTION_LOG(exception);
                    num = CodeDefine.RET_FAIL_EXCEPTION_DOWNLOAD;
                }
                UpdateLog.ERROR_LOG("HttpDownload: " + outFile.Name);
            }
            finally
            {
                if ((outFile != null) && outFile.CanWrite)
                {
                    outFile.Close();
                }
                _requestIns = null;
                if (_isAbortOption)
                {
                    num = CodeDefine.RET_SKIP_BY_ABORT;
                }
            }
            _isAbortOption = false;
            if (MapFileData != null)
            {
                MapFileData.ErrorCode = num;
            }
            return(num);
        }
Beispiel #13
0
        private static int DownloadMapData(MapFileData fileData, string saveFilePath)
        {
            int code = CodeDefine.RET_INIT;

            try
            {
                lock (m_locker)
                {
                    if (!Directory.Exists(fileData.SaveDir + "/" + fileData.Dir))
                    {
                        Directory.CreateDirectory(fileData.SaveDir + "/" + fileData.Dir);
                    }
                }
                long begin      = fileData.Begin + 4 * 32 + fileData.DirLen + fileData.NameLen + fileData.Md5Len;
                long end        = fileData.End - 1;
                int  retryTimes = _RETRAY_TIMES;
                while ((retryTimes > 0) && (code <= CodeDefine.RET_INIT))
                {
                    retryTimes--;
                    if (fileData.Name.Contains("RemoteVersion.xml") || fileData.Name.ToLower().Contains("localversion.xml"))
                    {
                        return(CodeDefine.RET_SUCCESS);
                    }
                    code = DownloadUseBackCdn(fileData, fileData.ResUrl, saveFilePath, begin, end);
                    if (code == CodeDefine.RET_SKIP_BY_ABORT)
                    {
                        break;
                    }
                }
            }
            catch (Exception exception)
            {
                if (saveFilePath.Contains("ClassesResources.xml"))
                {
                    code = CodeDefine.RET_SUCCESS;
                }
                UpdateLog.ERROR_LOG(_TAG + "ThreadCallBack(object state) download fail: file= " + saveFilePath +
                                    "\n error" + exception.Message + "\n" + exception.StackTrace);
                UpdateLog.EXCEPTION_LOG(exception);
            }
            return(code);
        }
Beispiel #14
0
        //文件md5
        public static string MD5File(string filePath)
        {
            if (!File.Exists(filePath))
            {
                return("");
            }

//             MD5 md5 = new MD5CryptoServiceProvider();
//             byte[] data = System.Text.Encoding.Default.GetBytes(filePath);//将字符编码为一个字节序列
//             byte[] md5data = md5.ComputeHash(data);//计算data字节数组的哈希值
//             md5.Clear();
//             string str = "";
//             for (int i = 0; i < md5data.Length; i++)
//             {
//                 str += md5data[i].ToString("x2");
//             }
//             return str;

            try
            {
                FileStream file = new FileStream(filePath, FileMode.Open);
                System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
                byte[] retVal = md5.ComputeHash(file);
                file.Close();

                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < retVal.Length; i++)
                {
                    sb.Append(retVal[i].ToString("x2"));
                }
                return(sb.ToString());
            }
            catch (Exception ex)
            {
                UpdateLog.ERROR_LOG("calc md5 fail : " + ex.Message + "\n" + ex.StackTrace);
                UpdateLog.EXCEPTION_LOG(ex);
            }

            return("");
        }
Beispiel #15
0
        private int downloadMapFile()
        {
            UpdateLog.INFO_LOG("downloadMapFile +++");
            int num = 1;
            List <VersionModel> list = new List <VersionModel>();

            // if (this._currentData.VersionModelBaseList.Count > 0)
            {
                list.AddRange(this._currentData.VersionModelBaseList);
            }
            if (list.Count == 0)
            {
                num = 0;
            }
            for (int i = 0; i < list.Count; i++)
            {
                VersionModel model        = list[i];
                string       str          = model.Map_url.Replace(@"\", "/");
                string       str2         = str.Substring(str.LastIndexOf("/") + 1);
                string       localMapFile = Path.Combine(BaseFlow._storeDir, str2);
                if (this.checkNeedDownloadMapFile(localMapFile, model.Map_md5))
                {
                    string url  = model.Map_url;
                    int    num3 = this._fileDownload.DownloadUseBackCdn(localMapFile, url, this.ParseInt(model.Map_size), false);
                    if ((num3 >= 0) && this.checkNeedDownloadMapFile(localMapFile, model.Map_md5))
                    {
                        string str5 = MD5.MD5File(localMapFile);
                        UpdateLog.ERROR_LOG("Download map file error md5: " + localMapFile + " md5=" + str5 + "\n online md5: " + model.Map_url + " md5=" + model.Map_md5);
                        num3 = -6;
                    }
                    if (num3 <= -1)
                    {
                        return(num3);
                    }
                }
            }
            UpdateLog.INFO_LOG("downloadMapFile ---");
            return(num);
        }
Beispiel #16
0
        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="localVersion"></param>
        /// <returns></returns>
        public int save(LocalVersionXml localVersion)
        {
            UpdateLog.INFO_LOG(_TAG + "save()");
            int ret = CodeDefine.RET_SUCCESS;

            try
            {
                set(dom, "local_info/local_base_res_version", localVersion.BaseResVersion);
                set(dom, "local_info/local_patch_res_version", localVersion.PatchResVersion);
                set(dom, "local_info/hasCopy", localVersion.HasCopy);
                set(dom, "local_info/local_app_version", localVersion.LocalAppVersion);
                MonoXmlUtils.SaveXml(_localVersionXml, dom);
            }
            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);
        }
Beispiel #17
0
        /// <summary>
        /// 初始化后台更新
        /// </summary>
        internal void InitBackDownload(int halfCpuCoreCount = 4)
        {
            //初始化后台更新模块
            Download.BackDownload.InitPool(halfCpuCoreCount, convertMyActionCall(delegate(string arg1, bool arg2, object arg3)
            {
                MapFileData data = arg3 as MapFileData;
                if (!arg2)
                {
                    UpdateLog.ERROR_LOG("下载失败: " + arg1);
                }
                var func = data.DownloadCallBack;
                //需要设置为null,不然重复下载的文件会出问题
                data.DownloadCallBack = null;

                if (func != null)
                {
                    func(arg1, arg2, data.ArgObj);
                }

                data.Downloading = false;
                data.Downloaded  = arg2;
            }));
        }
Beispiel #18
0
        private void requestData(HttpWebRequest myRequest, FileStream outFile)
        {
            byte[]          btContent = new byte[_BUFFER];
            HttpWebResponse reponse   = null;
            Stream          myStream  = null;

            try
            {
                using (reponse = myRequest.GetResponse() as HttpWebResponse)
                {
                    using (myStream = reponse.GetResponseStream())
                    {
                        int intSize = 0;
                        int readLen = 0;
                        intSize = myStream.Read(btContent, 0, _BUFFER);
                        while (intSize > 0)
                        {
                            readLen += intSize;
                            //已下载
                            DownloadedSize = readLen;

                            lock (m_locker)
                            {
                                MutiDownloadedSize += intSize;
                                //中断下载
                                if (_isAbortOption)
                                {
                                    UpdateLog.WARN_LOG("abort download : " + Thread.CurrentThread.Name);
                                    break;
                                }
                            }

                            outFile.Write(btContent, 0, intSize);
                            if (!myStream.CanRead)
                            {
                                break;
                            }
                            intSize = myStream.Read(btContent, 0, _BUFFER);
                        }
                    }
                }
            }
            catch (System.Exception ex)
            {
                UpdateLog.ERROR_LOG(_TAG + ex.Message + "\n" + ex.StackTrace);
                if (reponse != null)
                {
                    UpdateLog.ERROR_LOG("Http status: " + reponse.StatusCode);
                }
            }
            finally
            {
                if (reponse != null)
                {
                    reponse.Close();
                }
                if (myStream != null)
                {
                    myStream.Close();
                }
                if (outFile != null)
                {
                    outFile.Flush();
                }
            }

            btContent = null;
        }
        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));
            }
        }
Beispiel #20
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);
        }
Beispiel #21
0
        public int parseMapFile(string mapFile, string resUrl, string saveDir)
        {
            _saveDir = saveDir;
            UpdateLog.INFO_LOG(_TAG + "parseMapFile(string mapFile, string resUrl):" + mapFile + "," + resUrl);

            int ret = CodeDefine.RET_SUCCESS;

            List <MapFileData> mapFileDataList = _mapFileDataList;

            FileStream mapFileStream = null;

            try
            {
                mapFileStream = new FileStream(mapFile, FileMode.Open);

                long filePosition = 0;
                long mapFileSize  = mapFileStream.Length;
                while (mapFileSize > 0 && filePosition != mapFileSize)
                {
                    if (filePosition >= mapFileSize)
                    {
                        UpdateLog.ERROR_LOG("解析出错了");
                        return(ret);
                    }
                    MapFileData mapFileData = new MapFileData();
                    mapFileData.Begin = parseInt(read(mapFileStream, 10, filePosition, out filePosition));

                    if (mapFileData.Begin == -1)
                    {
                        UpdateLog.WARN_LOG("解析map文件,出现异常,请检查: " + mapFile);
                        return(ret);
                    }

                    mapFileData.End      = parseInt(read(mapFileStream, 10, filePosition, out filePosition));
                    mapFileData.DirLen   = parseInt(read(mapFileStream, 10, filePosition, out filePosition));
                    mapFileData.NameLen  = parseInt(read(mapFileStream, 10, filePosition, out filePosition));
                    mapFileData.Md5Len   = parseInt(read(mapFileStream, 10, filePosition, out filePosition));
                    mapFileData.FileSize = parseInt(read(mapFileStream, 10, filePosition, out filePosition));
                    mapFileData.Dir      = read(mapFileStream, mapFileData.DirLen, filePosition, out filePosition);
                    mapFileData.Name     = read(mapFileStream, mapFileData.NameLen, filePosition, out filePosition);
                    mapFileData.Md5      = read(mapFileStream, mapFileData.Md5Len, filePosition, out filePosition);

                    mapFileData.ResUrl  = resUrl;
                    mapFileData.SaveDir = _saveDir;

                    UnityEngine.Debug.Log("mapFileData.Name :" + mapFileData.Name);
                    mapFileDataList.Add(mapFileData);
                }
            }
            catch (System.Exception ex)
            {
                ret = CodeDefine.RET_FAIL_PARSE_MAP_FILE;
                UpdateLog.ERROR_LOG(_TAG + ex.Message + "\n" + ex.StackTrace);
                UpdateLog.EXCEPTION_LOG(ex);
            }
            finally
            {
                if (mapFileStream != null)
                {
                    mapFileStream.Close();
                }
            }
            return(ret);
        }
Beispiel #22
0
 public void FinishWithError(int code)
 {
     UpdateLog.ERROR_LOG("FinishWithError : + " + code);
     LastFlowResult = code;
     Work();
 }
Beispiel #23
0
        /// <summary>
        /// 释放资源
        /// 文件结构 4x32 文件头 |32位记录路径长度|32位记录文件名|32位记录md5长度|32位记录文件大小|
        /// 然后根据这4个结构获取具体的路径、文件名、md5值、文件内容
        /// </summary>
        /// <returns></returns>
        public int UnzipRes()
        {
            UpdateLog.INFO_LOG(_TAG + "unzipRes()");

            int        ret           = CodeDefine.RET_SUCCESS;
            FileStream resFileStream = null;
            long       filePostion   = 0;
            long       fileSize      = 0;

            try
            {
                resFileStream = new FileStream(_resPath, FileMode.Open, FileAccess.Read, FileShare.Read);
                fileSize      = resFileStream.Length;

                List <ResourceFileData> fileDataList = new List <ResourceFileData>();

                //启动线程池
                // var threadPool = new HttpThreadPool<UnzipData>(4, ThreadFunc);
                while (fileSize > 0 && filePostion < fileSize)
                {
                    ResourceFileData fileData = new ResourceFileData();

                    //4x32长度的头
                    fileData.DirLen   = int.Parse(read(resFileStream, 32, filePostion, out filePostion));
                    fileData.NameLen  = int.Parse(read(resFileStream, 32, filePostion, out filePostion));
                    fileData.Md5Len   = int.Parse(read(resFileStream, 32, filePostion, out filePostion));
                    fileData.FileSize = long.Parse(read(resFileStream, 32, filePostion, out filePostion));

                    //读取内容
                    fileData.Dir  = read(resFileStream, fileData.DirLen, filePostion, out filePostion);
                    fileData.Name = read(resFileStream, fileData.NameLen, filePostion, out filePostion);
                    fileData.Md5  = read(resFileStream, fileData.Md5Len, filePostion, out filePostion);

                    //跳过localversion的释放
                    if (fileData.Name.ToLower().Equals("localversion.xml"))
                    {
                        resFileStream.Seek(fileData.FileSize, SeekOrigin.Current);
                    }
                    else
                    {
                        writeFile(resFileStream, fileData.FileSize, fileData.Dir, fileData.Name);

                        //resFileStream.Seek(fileData.FileSize, SeekOrigin.Current);
                        //UnzipData ud = new UnzipData(fileData, filePostion, fileSize);
                        //threadPool.addTask(ud);
                    }
                    filePostion += fileData.FileSize;
                }

                //等待所有文件下载完
                //threadPool.waitWhileWorking();
            }
            catch (System.Exception ex)
            {
                ret = CodeDefine.RET_FAIL_UNZIP_RES_FILE;
                UpdateLog.ERROR_LOG(_TAG + ex.Message + "\n" + ex.StackTrace);
                UpdateLog.EXCEPTION_LOG(ex);
            }
            finally
            {
                if (resFileStream != null)
                {
                    resFileStream.Close();
                }
            }
            return(ret);
        }
Beispiel #24
0
        private int downloadMapData(MapFileData fileData, string saveFilePath)
        {
            int ret = CodeDefine.RET_FAIL;

            try
            {
                lock (m_locker)
                {
                    if (!Directory.Exists(fileData.SaveDir + "/" + fileData.Dir))
                    {
                        Directory.CreateDirectory(fileData.SaveDir + "/" + fileData.Dir);
                    }
                }

                //计算下载点,在资源包中,每个文件都有4个32字节的数据头加上文件名、md5长度,要跳过
                long begin = fileData.Begin + 32 * 4 + fileData.DirLen + fileData.NameLen + fileData.Md5Len;
                //http的AddRange方法是闭包的,所以减一。([from, to])
                long end = fileData.End - 1;

                //每个文件有3次下载机会
                int i = _RETRAY_TIMES;
                while (i > 0)
                {
                    i--;
                    if (fileData.Name.Contains("RemoteVersion.xml") || fileData.Name.ToLower().Contains("localversion.xml"))
                    {
                        ret = CodeDefine.RET_SUCCESS;
                        return(ret);
                    }

                    if (Download.UseBackupCdn(fileData.ResUrl, Download.BackupCdn))
                    {
                        //使用台湾备份cdn地址
                        for (int cdnIndex = 0; cdnIndex < Download.BackupCdn.Length; ++cdnIndex)
                        {
                            string backupUrl = fileData.ResUrl.Replace(Download.BackupCdn[0], Download.BackupCdn[cdnIndex]);
                            using (FileStream outFile = new FileStream(saveFilePath, FileMode.Create))
                            {
                                ret = httpDownload(backupUrl, outFile, begin, end);
                                if (ret >= CodeDefine.RET_SUCCESS)
                                {
                                    break;
                                }

                                if (ret == CodeDefine.RET_SKIP_BY_ABORT)
                                {
                                    return(ret);
                                }
                            }
                        }

                        if (ret >= CodeDefine.RET_SUCCESS)
                        {
                            break;
                        }
                    }
                    else
                    {
                        using (FileStream outFile = new FileStream(saveFilePath, FileMode.Create))
                        {
                            //UpdateLog.INFO_LOG(_TAG + " download: " + saveFilePath);
                            ret = httpDownload(fileData.ResUrl, outFile, begin, end);
                            if (ret >= CodeDefine.RET_SUCCESS)
                            {
                                break;
                            }

                            if (ret == CodeDefine.RET_SKIP_BY_ABORT)
                            {
                                return(ret);
                            }

                            UpdateLog.WARN_LOG(_TAG + " try download i = " + i);
                            Thread.Sleep(_SLEEP_TIME);
                        }
                    }
                }
            }
            catch (System.Exception ex)
            {
                if (saveFilePath.Contains("ClassesResources.xml"))
                {
                    ret = CodeDefine.RET_SUCCESS;
                }
                UpdateLog.ERROR_LOG(_TAG + "ThreadCallBack(object state) download fail: file= " + saveFilePath + "\n error" + ex.Message + "\n" + ex.StackTrace);
                UpdateLog.EXCEPTION_LOG(ex);
            }

            return(ret);
        }
Beispiel #25
0
        //解析xml
        public int parseResouceVersionXml(string path)
        {
            UpdateLog.INFO_LOG(_TAG + "parseResouceVersionXml(string path):" + path);

            int ret = CodeDefine.RET_SUCCESS;

            try
            {
                var sp = MonoXmlUtils.LoadXmlEx(path);
                if (sp == null || sp.ToXml() == null)
                {
                    return(CodeDefine.RET_FAIL_PARSE_RES_XML_FILE);
                }

                var dom = sp.ToXml();

                //正式流程
                parse(dom, "ResourceVersion/VersionBase", NormalFollow.VersionModelBaseList);
                parse(dom, "ResourceVersion/VersionPatch", NormalFollow.VersionModelPatchList);
                NormalFollow.AppVersion = parse(dom, "ResourceVersion/CodeVersion_last/Version");
                NormalFollow.ClientUrl  = parse(dom, "ResourceVersion/CodeVersion_last/url");
                NormalFollow.AppSize    = parse(dom, "ResourceVersion/CodeVersion_last/size");
                NormalFollow.Language   = parse(dom, "ResourceVersion/loginSever/language");
                bool enable = true;
                if (!Boolean.TryParse(parse(dom, "ResourceVersion/ForceUpdate"), out enable))
                {
                    enable = true;
                }
                NormalFollow.EnableForceUpdate = enable;
                NormalFollow.PatchVersion      = GetMaxPatchVersion(NormalFollow.VersionModelPatchList);

                //测试流程
                parse(dom, "ResourceVersion/test_tag/VersionBase", TestFollow.VersionModelBaseList);
                parse(dom, "ResourceVersion/test_tag/VersionPatch", TestFollow.VersionModelPatchList);
                TestFollow.AppVersion = parse(dom, "ResourceVersion/test_tag/app_current_version");
                TestFollow.ClientUrl  = parse(dom, "ResourceVersion/test_tag/app_update_url");
                TestFollow.AppSize    = parse(dom, "ResourceVersion/test_tag/test_size");
                TestFollow.Language   = parse(dom, "ResourceVersion/test_tag/language");
                if (!Boolean.TryParse(parse(dom, "ResourceVersion/test_tag/ForceUpdate"), out enable))
                {
                    enable = true;
                }
                TestFollow.EnableForceUpdate = enable;
                TestFollow.PatchVersion      = GetMaxPatchVersion(TestFollow.VersionModelPatchList);

                //白名单 mac地址
                var macList = parseNodes(dom, "ResourceVersion/test_tag/legal_client_machine_list/legal_client_machine");
                for (int i = 0; macList != null && i < macList.Length; i++)
                {
                    if (macList[i] == null)
                    {
                        continue;
                    }
                    WhiteCode.Add(macList[i].Text);
                }

                //白名单 用户名
                var userList = parseNodes(dom, "ResourceVersion/test_tag/legal_client_user_list/legal_client_user");
                for (int i = 0; userList != null && i < userList.Length; i++)
                {
                    if (userList[i] == null)
                    {
                        continue;
                    }
                    WhiteUsers.Add(userList[i].Text);
                }

                //白名单 ip地址
                var ipList = parseNodes(dom, "ResourceVersion/test_tag/legal_client_ip_list/legal_client_ip");
                for (int i = 0; ipList != null && i < ipList.Length; i++)
                {
                    if (ipList[i] == null)
                    {
                        continue;
                    }
                    WhiteIp.Add(ipList[i].Text);
                }
            }
            catch (System.Exception ex)
            {
                ret = CodeDefine.RET_FAIL_PARSE_RES_XML_FILE;
                UpdateLog.ERROR_LOG(_TAG + ex.Message + "/n" + ex.StackTrace);
                UpdateLog.EXCEPTION_LOG(ex);
            }


            return(ret);
        }