Beispiel #1
0
        /// <summary>
        /// 构造函数.
        /// </summary>
        // public DefinesWindow() {
        //  if (false == this.Init (_jsonFileDir)) {
        //      UtilsLog.Error (this.ClassName, "DefinesWindow Failed!!!");
        //  }
        // }

        /// <summary>
        /// 窗口类不要写构造函数,初始化写在Awake里
        /// </summary>
        void Awake()
        {
            if (false == this.Init(_jsonFileDir))
            {
                UtilsLog.Error(this.ClassName, "Awake()::DefinesWindow Failed!!!");
            }
        }
        /// <summary>
        /// 取得文件的Md5码.
        /// </summary>
        /// <returns>文件的Md5码.</returns>
        /// <param name="iFilePath">文件路径.</param>
        public static string GetFileMD5(string iFilePath)
        {
            if (_md5 == null)
            {
                _md5 = new MD5CryptoServiceProvider();
            }

            if (false == File.Exists(iFilePath))
            {
                UtilsLog.Error("UploadList", "GetFileMD5()::The file is not exist!!!(File:{0})", iFilePath);
                return(null);
            }

            FileStream fs = new FileStream(iFilePath, FileMode.Open, FileAccess.Read, FileShare.Read);

            byte[] hash   = _md5.ComputeHash(fs);
            string strMD5 = System.BitConverter.ToString(hash);

            if (null != fs)
            {
                fs.Close();
                fs.Dispose();
            }

            strMD5 = strMD5.ToLower();
            strMD5 = strMD5.Replace("-", "");

            return(strMD5);
        }
        /// <summary>
        /// 下载失败回调函数.
        /// </summary>
        /// <param name="iDownloadInfo">下载信息.</param>
        /// <param name="iIsManifest">Manifest文件标志位.</param>
        /// <param name="iErrors">错误信息.</param>
        public void OnDownloadFail(DownloaderBase iDownloader, DownloadTargetInfo iDownloadInfo, bool iIsManifest, List <ErrorDetail> iErrors)
        {
            // 线程安全:添加错误信息至列表
            lock (_downloaderErrorLock) {
                string errsStr = null;
                foreach (ErrorDetail error in iErrors)
                {
                    if (string.IsNullOrEmpty(errsStr) == true)
                    {
                        errsStr = string.Format("Type:{0} State:{1} Detail:{2} Retries:{3}",
                                                error.Type.ToString(), error.State.ToString(), error.Detail, error.Retries.ToString());
                    }
                    else
                    {
                        errsStr = string.Format("{0} \n Type:{1} State:{2} Detail:{3} Retries:{4}",
                                                errsStr, error.Type.ToString(), error.State.ToString(), error.Detail, error.Retries.ToString());
                    }
                }

                UtilsLog.Error("OnDownloadFail", "Download Failed!!! {0} \n Detail:{1}",
                               iDownloadInfo.toString(), errsStr);

                this._errors.AddRange(iErrors);
                this._State = TRunState.Error;

                if (iDownloader != null)
                {
                    iDownloader.Dispose();
                    GC.Collect();
                }
            }
        }
Beispiel #4
0
        /// <summary>
        /// 添加已经创建目录.
        /// </summary>
        /// <param name="iServerId">服务器ID.</param>
        /// <param name="iDir">I dir.</param>
        public void AddCreatedDir(TServerID iServerId, string iDir)
        {
            // 线程安全锁
            lock (_serversDirsLock) {
                ServerDirInfo   targetServer = null;
                ServerDirInfo[] servers      = this.ServersDirs
                                               .Where(o => (iServerId == o.ID))
                                               .OrderBy(o => o.ID)
                                               .ToArray();
                if ((servers == null) || (servers.Length <= 0))
                {
                    targetServer    = new ServerDirInfo();
                    targetServer.ID = iServerId;
                    this.ServersDirs.Add(targetServer);
                }
                else
                {
                    if (servers.Length > 1)
                    {
                        UtilsLog.Error("AddCreatedDir", "There are multiple id exist!!![ID:{0}]", iServerId);
                    }
                    targetServer = servers [0];
                }

                string[] dirs = targetServer.Dirs.Where(o => (o.Equals(iDir) == true)).ToArray();
                if ((dirs == null) || (dirs.Length <= 0))
                {
                    targetServer.Dirs.Add(iDir);
                }
            }
        }
Beispiel #5
0
        static void ShowDefinesWindow()
        {
            //创建窗口
            DefinesWindow window = UtilsWindow.CreateWindow <DefinesWindow, DefinesConfInfo>(DefinesWindow.ConfInfo);

            if (null == window)
            {
                UtilsLog.Error("DefinesWindow", "ShowDefinesWindow -> Create Window Failed!!");
                return;
            }
            window.Show();
        }
Beispiel #6
0
        /// <summary>
        /// 取得Bundle全路径名.
        /// </summary>
        /// <returns>Bundle全路径名.</returns>
        /// <param name="iBundleId">BundleId.</param>
        /// <param name="iFileType">文件类型.</param>
        public string GetBundleFullPath(
            string iBundleId, TUploadFileType iFileType = TUploadFileType.Bundle)
        {
            DownloadTargetInfo targetInfo = null;

            if (isTargetExist(iBundleId, iFileType, out targetInfo) == false)
            {
                UtilsLog.Error("GetBundleFullPath", "This bundles is not exist!!!({BundleId:{0} FileType:{1})",
                               iBundleId, iFileType);
                return(null);
            }
            if (targetInfo == null)
            {
                return(null);
            }
            string fileName = UploadList.GetLocalBundleFileName(iBundleId, targetInfo.FileType);

            if (string.IsNullOrEmpty(fileName) == true)
            {
                return(null);
            }

            string fileFullPath = null;

            switch (targetInfo.BundleType)
            {
            case TBundleType.Normal:
            {
                fileFullPath = string.Format("{0}/{1}",
                                             ServersConf.BundlesDirOfNormal,
                                             fileName);
            }
            break;

            case TBundleType.Scene:
            {
                fileFullPath = string.Format("{0}/{1}",
                                             ServersConf.BundlesDirOfScenes,
                                             fileName);
            }
            break;

            default:
            {
                fileFullPath = string.Format("{0}/{1}",
                                             ServersConf.BundlesDir,
                                             fileName);
            }
            break;
            }
            return(fileFullPath);
        }
Beispiel #7
0
        /// <summary>
        /// 登出.
        /// </summary>
        public void Logout()
        {
            if (TPlatformType.None == BuildInfo.GetInstance().PlatformType)
            {
                UtilsLog.Error("AndroidLibs", "Logout():The platformType is none in buildinfo.asset file!!!");
                return;
            }

            AndroidJavaClass  jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
            AndroidJavaObject jo = jc.GetStatic <AndroidJavaObject>("currentActivity");

            jo.Call("UToA_Logout");
        }
Beispiel #8
0
        /// <summary>
        /// 上传失败委托.
        /// </summary>
        /// <param name="iUploader">上传器.</param>
        /// <param name="iTargetInfo">上传目标信息.</param>
        /// <param name="iRetries">剩余重试次数.</param>
        /// <param name="iError">错误信息.</param>
        public void OnUploadFailed(Uploader iUploader, UploadItem iTargetInfo, int iRetries, List <ErrorDetail> iErrors)
        {
            lock (_errorLock) {
                UtilsLog.Error("OnUploadFailed", "{0} State:{1} Retries:{2} Detail:{3}",
                               iTargetInfo.toString(), this._State, iRetries, iErrors.ToString());

                this._errors.AddRange(iErrors);
                this._State = TRunState.Error;

                if (iUploader != null)
                {
                    iUploader.Dispose();
                    GC.Collect();
                }
            }
        }
 /// <summary>
 /// 检测下载用的目录.
 /// </summary>
 /// <param name="iDir">检测目录.</param>
 private void CheckDownloadDirs(string iDir)
 {
     if (string.IsNullOrEmpty(iDir) == true)
     {
         return;
     }
     if (false == Directory.Exists(iDir))
     {
         Directory.CreateDirectory(iDir);
         UtilsLog.Info("CheckDownloadDirs", " Create Dir:{0}", iDir);
         if (false == Directory.Exists(iDir))
         {
             UtilsLog.Error("CheckDownloadDirs", " Create Dir Failed!! Dir:{0}", iDir);
         }
     }
 }
        /// <summary>
        /// 开始下载.
        /// </summary>
        private IEnumerator DownloadFiles()
        {
            TDownloadWay downloadWay = ServersConf.GetInstance().DownloadWay;

            while (this.DownloadQueue.Count > 0)
            {
                // 下载器个数控制
                if (this.DownloaderCount >= this.DownloaderMaxCount)
                {
                    yield return(new WaitForSeconds(1.0f));
                }

                // 下载出错则停止
                if (TRunState.OK != this._State)
                {
                    UtilsLog.Error("DownloadFiles", "Download Failed!!! State:{0}", this._State.ToString());
                    // 取消现有下载线程
                    isCanceled = true;
                    yield break;
                }

                DownloaderBase downloader = this.DownloadQueue.Dequeue();
                if (downloader == null)
                {
                    continue;
                }
                // Bundle文件
                if (TDownloadWay.WWW == downloadWay)
                {
                    yield return(downloader.AsynDownLoadTarget());
                }
                else
                {
                    downloader.ThreadDownLoadTarget();
                }
                yield return(new WaitForEndOfFrame());

                // 下载出错则停止
                if (TRunState.OK != this._State)
                {
                    UtilsLog.Error("DownloadFiles", "Download Failed!!! State:{0}", this._State.ToString());
                    // 取消现有下载线程
                    isCanceled = true;
                    yield break;
                }
            }
        }
Beispiel #11
0
        /// <summary>
        /// 下载完毕拷贝文件.
        /// </summary>
        public void CopyTargetWhenDownloadCompleted()
        {
            string copyFrom = null;
            string copyTo   = null;

            switch (this.BundleType)
            {
            case TBundleType.Scene:
            {
                copyFrom = ServersConf.DownloadDirOfScenes;
                copyTo   = ServersConf.BundlesDirOfScenes;
            }
            break;

            case TBundleType.Normal:
            {
                copyFrom = ServersConf.DownloadDirOfNormal;
                copyTo   = ServersConf.BundlesDirOfNormal;
            }
            break;

            default:
            {
                copyFrom = ServersConf.DownloadDir;
                copyTo   = ServersConf.BundlesDir;
            }
            break;
            }
            string fileName = UploadList.GetLocalBundleFileName(this.ID, this.FileType);

            copyFrom = string.Format("{0}/{1}", copyFrom, fileName);
            copyTo   = string.Format("{0}/{1}", copyTo, fileName);

            if (true == File.Exists(copyFrom))
            {
                File.Copy(copyFrom, copyTo, true);
                UtilsLog.Info("CopyTargetWhenDownloadCompleted", "Copy File:{0} -> {1}",
                              copyFrom, copyTo);
            }
            if (false == File.Exists(copyTo))
            {
                UtilsLog.Error("CopyTargetWhenDownloadCompleted", "Failed!! FileName:{0} -> {1}", copyFrom, copyTo);
            }
            File.Delete(copyFrom);
            UtilsLog.Info("CopyTargetWhenDownloadCompleted", "Delete File -> {0}",
                          copyFrom);
        }
Beispiel #12
0
        /// <summary>
        /// 上传.
        /// </summary>
        private IEnumerator UploadFiles(TUploadWay iUploadWay = TUploadWay.Default)
        {
            UploadServerInfo server = ServersConf.GetInstance().GetUploadServerInfo();

            if (server == null)
            {
                yield return(null);
            }
            while (this.UploadQueue.Count > 0)
            {
                if (this.UploaderCount >= this.UploaderMaxCount)
                {
                    yield return(new WaitForSeconds(1.0f));
                }

                // 上传出错则停止
                if (TRunState.OK != this._State)
                {
                    UtilsLog.Error("UploadFiles", "Failed!!! State:{0} Detail:{1}",
                                   this._State.ToString(), this._errors.ToString());
                    // 取消现有上传线程
                    isCanceled = true;
                    break;
                }

                Uploader uploader = this.UploadQueue.Dequeue();
                if (uploader == null)
                {
                    continue;
                }
                yield return(uploader.UploadFile());

                yield return(new WaitForEndOfFrame());

                // 上传出错则停止
                if (TRunState.OK != this._State)
                {
                    UtilsLog.Error("UploadFiles", "Failed!!! State:{0} Detail:{1}",
                                   this._State.ToString(), this._errors.ToString());
                    // 取消现有上传线程
                    isCanceled = true;
                    break;
                }
            }

            yield return(null);
        }
Beispiel #13
0
        /// <summary>
        /// 创建Downloader.
        /// </summary>
        /// <param name="iTargetInfo">下载目标.</param>
        /// <param name="iOnStart">开始委托回调.</param>
        /// <param name="iOnSuccessed">成功委托回调.</param>
        /// <param name="iOnFailed">失败委托回调.</param>
        /// <param name="iRetries">重下载次数.</param>
        /// <param name="iTimeOut">超时时间(单位:秒).</param>
        public static WWWDownloader Create(
            DownloadTargetInfo iTargetInfo, OnStart iOnStart,
            OnSuccessed iOnSuccessed, OnFailed iOnFailed)
        {
            WWWDownloader downloader = new WWWDownloader();

            if (downloader != null)
            {
                // 初始化
                downloader.Init(iTargetInfo, iOnStart, iOnSuccessed, iOnFailed);
                return(downloader);
            }
            else
            {
                UtilsLog.Error("Create", "Downloader Create failed!!");
                return(null);
            }
        }
Beispiel #14
0
        /// <summary>
        /// 创建Downloader(Http).
        /// </summary>
        /// <param name="iDownloadUrl">下载Url.</param>
        /// <param name="iOnStart">开始事件委托.</param>
        /// <param name="iOnSuccessed">成功事件委托.</param>
        /// <param name="iOnFailed">失败事件委托.</param>
        /// <param name="iType">下载对象类型.</param>
        public static HttpDownloader Create(
            string iDownloadUrl, OnStart iOnStart,
            OnSuccessedByUrl iOnSuccessed, OnFailedByUrl iOnFailed,
            TargetType iType = TargetType.Bundle)
        {
            HttpDownloader downloader = new HttpDownloader();

            if (downloader != null)
            {
                downloader.Init(iDownloadUrl, iOnStart, iOnSuccessed, iOnFailed, iType);
                return(downloader);
            }
            else
            {
                UtilsLog.Error("Create", "Downloader Create failed!!");
                return(null);
            }
        }
Beispiel #15
0
        /// <summary>
        /// 登陆.
        /// </summary>
        /// <param name="iTarget">登陆对象.</param>
        /// <param name="iOnLoginCompleted">登陆完成.</param>
        public void Login(
            GameObject iTarget,
            Action <string> iOnLoginCompleted)
        {
            if (TPlatformType.None == BuildInfo.GetInstance().PlatformType)
            {
                UtilsLog.Error("AndroidLibs", "Login():The platformType is none in buildinfo.asset file!!!");
                return;
            }
            if (null == iTarget)
            {
                return;
            }

            AndroidJavaClass  jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
            AndroidJavaObject jo = jc.GetStatic <AndroidJavaObject>("currentActivity");

            jo.Call("UToA_Login", iTarget.name, iOnLoginCompleted.Method.Name);
        }
        /// <summary>
        /// 加载数据
        /// </summary>
        /// <returns></returns>
        public static UIComponentData LoadData(string uiPrefabName)
        {
            var prefab = DataLoader.Load<GameObject>(uiPrefabName);
            if (prefab == null)
            {
				UtilsLog.Error("UIComponentData", "LoadData()::Prefab Load Failed!!!(Path:{0})", uiPrefabName);
                return null;
            }
            var prefabComponent = prefab.GetComponent<UIComponentBase>();
            if (prefabComponent == null)
            {
				UtilsLog.Error("UIComponentData", "LoadData()::Prefab do not exist UIComponentBase !!!(Path:{0})", uiPrefabName);
                return null;
            }
            if (prefabComponent.Data.Prefab == null)
            {
                prefabComponent.Data.Prefab = prefabComponent;
            }
            return prefabComponent.Data;
        }
Beispiel #17
0
        private void Log(string message, TLogType iType = TLogType.kInfo)
        {
            System.Console.WriteLine(message);
            if (BuildParameters.IsBuildInCI == false)
            {
                switch (iType)
                {
                case TLogType.kInfo:
                {
                    UtilsLog.Info("ConsoleBuildLogger",
                                  message);
                }
                break;

                case TLogType.kWarning:
                {
                    UtilsLog.Warning("ConsoleBuildLogger",
                                     message);
                }
                break;

                case TLogType.kError:
                {
                    UtilsLog.Error("ConsoleBuildLogger",
                                   message);
                }
                break;

                case TLogType.kException:
                {
                    UtilsLog.Exception("ConsoleBuildLogger",
                                       message);
                }
                break;

                default:
                    break;
                }
            }
        }
Beispiel #18
0
        /// <summary>
        /// 添加非资源信息.
        /// </summary>
        /// <param name="iUnResourePath">非资源路径.</param>
        public BundleUnResource AddUnResource(string iUnResourcePath)
        {
            BundleUnResource bur = null;

            // 不存在存在
            if (this.isUnResoureExist(iUnResourcePath, out bur) == false)
            {
                bur = new BundleUnResource();
                this.UnResources.Add(bur);
            }
            if (bur != null)
            {
                bur.Path = iUnResourcePath;
                UtilsAsset.SetAssetDirty(this);
            }
            else
            {
                UtilsLog.Error("AddUnResource", "Failed!!!(Path:{0})",
                               iUnResourcePath);
            }
            return(bur);
        }
Beispiel #19
0
        /// <summary>
        /// 打开控制台输出流(重定向输出流).
        /// </summary>
        /// <param name="iBuildLogFile">编译打包日志文件路径.</param>
        /// <param name="iBuildTime">打包时间(YYYYMMDDHHMMSS).</param>
        private static void OpenConsoleStream(string iBuildLogFile)
        {
#if UNITY_EDITOR
            if (string.IsNullOrEmpty(iBuildLogFile) == true)
            {
                UtilsLog.Error("OpenConsoleStream",
                               "The path of build log file is null");
                return;
            }

            // 已经打开
            if (isFileOpen == true)
            {
                return;
            }

            try
            {
                ostrm  = new FileStream(iBuildLogFile, FileMode.Append, FileAccess.Write);
                writer = new StreamWriter(ostrm);

                writer.AutoFlush = true;
                // 重定向标准输出流
                Console.SetOut(writer);

                // 重定向标准错误流
                Console.SetError(writer);

                isFileOpen = true;
            }
            catch (Exception e)
            {
                Console.WriteLine(string.Format("Cannot open {0} for writing", iBuildLogFile));
                Console.WriteLine(e.Message);
                return;
            }
            Console.SetOut(writer);
#endif
        }
Beispiel #20
0
        /// <summary>
        /// 登陆.
        /// </summary>
        /// <param name="iTarget">登陆对象.</param>
        /// <param name="iOnLoginCompleted">登陆完成.</param>
        public void GetPlayerInfo(
            GameObject iTarget,
            Action <string> iOnGetPlayerInfoCompleted = null)
        {
            if (TPlatformType.None == BuildInfo.GetInstance().PlatformType)
            {
                UtilsLog.Error("AndroidLibs", "GetPlayerInfo():The platformType is none in buildinfo.asset file!!!");
                return;
            }

            if (false == Application.isMobilePlatform)
            {
                return;
            }

            AndroidJavaClass  jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
            AndroidJavaObject jo = jc.GetStatic <AndroidJavaObject>("currentActivity");

            jo.Call("UToA_GetPlayerInfo",
                    iTarget.name,
                    iOnGetPlayerInfoCompleted.Method.Name);
        }
Beispiel #21
0
        /// <summary>
        /// 上传上传列表列表信息.
        /// </summary>
        /// <param name="iServerInfo">服务器信息.</param>
        private string UploadUploadListFile(UploadServerInfo iServerInfo)
        {
            // 导出Json文件,保存至(Resources/Conf)
            string inputFilePath = UploadList.GetInstance().ExportToJsonFile();

            UtilsLog.Info("UploadUploadListFile", "ExportToJsonFile(Path:{0})", inputFilePath);

            // 打包信息URL
            string uploadUrl = ServersConf.GetUploadListBaseUrl(iServerInfo);

            if (File.Exists(inputFilePath) == true)
            {
                int    lastIndex = inputFilePath.LastIndexOf("/");
                string fileName  = inputFilePath.Substring(lastIndex + 1);
                uploadUrl = string.Format("{0}/{1}", uploadUrl, fileName);

                // 上传Bundles列表信息文件
                this._State = UpLoadFileToFtpServer(
                    uploadUrl, inputFilePath, iServerInfo.AccountId, iServerInfo.Pwd);

                if (TRunState.OK != this._State)
                {
                    UtilsLog.Error("UploadUploadListFile", "Upload Failed!!! \n {0} -> {1}", inputFilePath, uploadUrl);
                    return(null);
                }
                else
                {
                    this._uploadState = string.Format("[Upload] {0}", fileName);
                    return(inputFilePath);
                }
            }
            else
            {
                UtilsLog.Error("UploadUploadListFile", "Upload Failed!!! \n Upload file is not exist!!!(Path:{0})", inputFilePath);
                return(null);
            }
        }
Beispiel #22
0
        /// <summary>
        /// 备份文件.
        /// </summary>
        /// <param name="iBackupFilePath">备份文件路径.</param>
        /// <param name="iSubDir">备份文件子目录.</param>
        private bool BackupFile(string iBackupFilePath, string iSubDir = null)
        {
            // 上传文件列表
            if ((string.IsNullOrEmpty(iBackupFilePath) == false) &&
                (File.Exists(iBackupFilePath) == true))
            {
                // 移到备份目录
                string backupDir = this.GetBundleBackDir(UploadList.GetInstance().AppVersion, iSubDir);

                int    lastIndex          = iBackupFilePath.LastIndexOf("/");
                string fileName           = iBackupFilePath.Substring(lastIndex + 1);
                string backUpFileFullPath = string.Format("{0}/{1}", backupDir, fileName);

                UtilsLog.Info("BackupFile", "Successed. {0} -> {1}", iBackupFilePath, backUpFileFullPath);
                File.Copy(iBackupFilePath, backUpFileFullPath, true);
                if (File.Exists(backUpFileFullPath) == false)
                {
                    UtilsLog.Error("BackupFile", "Failed!!! {0} -> {1}", iBackupFilePath, backUpFileFullPath);
                    return(false);
                }
                this._uploadState = string.Format("[BackUp] -> {0}", fileName);
            }
            return(true);
        }
Beispiel #23
0
        /// <summary>
        /// 获取下载文件的总大小
        /// </summary>
        /// <returns>下载文件的总大小.</returns>
        /// <param name="iDownloadUrl">下载地址.</param>
        /// <param name="iFileSize">文件大小.</param>
        protected TRunState GetFileDataSize(string iDownloadUrl, ref long iFileSize)
        {
            TRunState ret = TRunState.OK;

            if (null != this._target)
            {
                iFileSize = Convert.ToInt64(this._target.DataSize);
            }
            else
            {
                HttpWebResponse response = null;
                HttpWebRequest  request  = null;
                try {
                    Uri _url = new Uri(iDownloadUrl);
                    request = WebRequest.Create(_url) as HttpWebRequest;
                    if (null == request)
                    {
                        UtilsLog.Error("DownloaderBase", "GetFileDataSize:HttpWebRequest Create Failed!!!");
                    }
                    if (TRunState.OK == ret)
                    {
                        request.Timeout          = this.TimeOut;
                        request.ReadWriteTimeout = this.TimeOut;
                        request.Method           = "HEAD";
                        request.ContentType      = "application/octet-stream";
                        request.KeepAlive        = false;

                        response = request.GetResponse() as HttpWebResponse;
                        if (response.StatusCode != HttpStatusCode.OK)
                        {
                            ErrorDetail error = new ErrorDetail();
                            error.Type   = TErrorType.HttpError;
                            error.State  = TRunState.GetFileSizeFromServerFailed;
                            error.Detail = string.Format("GetFileDataSize Failed!!(File:{0} StatusCode:{1})",
                                                         iDownloadUrl, response.StatusCode.ToString());
                            error.Retries = this.Retries;
                            iFileSize     = -1;

                            response.Close();
                            response = null;
                            return(TRunState.GetFileSizeFromServerFailed);
                        }
                        else
                        {
                            iFileSize = response.ContentLength;
                        }
                    }
                } catch (Exception exp) {
                    UtilsLog.Exception("DownloaderBase", "GetFileDataSize Type:{0} Message:{1} StackTrace:{2}",
                                       exp.GetType().ToString(), exp.Message, exp.StackTrace);

                    ErrorDetail error = new ErrorDetail();
                    error.Type   = TErrorType.HttpException;
                    error.State  = TRunState.Exception;
                    error.Detail = string.Format("GetFileDataSize Failed!!(File:{0} exp:{1})",
                                                 iDownloadUrl, exp.Message);
                    error.Retries = this.Retries;
                    iFileSize     = -1;

                    ret = TRunState.Exception;

                    if (null != request)
                    {
                        request.Abort();
                    }
                } finally {
                    if (null != response)
                    {
                        try
                        {
                            response.Close();
                            response = null;
                        }
                        catch {
                            request.Abort();
                        }
                    }
                }

                if (0 < iFileSize)
                {
                    UtilsLog.Info("DownloaderBase", "GetFileDataSize Size:{0} ({1})",
                                  iFileSize.ToString(), iDownloadUrl);
                }
            }

            return(ret);
        }
Beispiel #24
0
        /// <summary>
        /// 下载文件(Http).
        /// </summary>
        /// <returns>运行状态.</returns>
        /// <param name="iParentUrl">下载父Url.</param>
        /// <param name="iFileName">下载文件名.</param>
        protected TRunState DownloadFileByHttp(string iParentUrl, string iFileName)
        {
            HttpWebRequest  request  = null;
            HttpWebResponse response = null;
            FileStream      fs       = null;
            Stream          stream   = null;
            string          filePath = null;
            TRunState       stateTmp = TRunState.OK;

            try {
                // 取得下载文件名
                string downloadUrl = string.Format("{0}/{1}", iParentUrl, iFileName);
                filePath = string.Format("{0}/{1}", this.DownloadDir, iFileName);

                // 使用流操作文件
                fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write);
                // 获取文件现在的长度
                long fileLength = fs.Length;
                // 获取下载文件的总长度
                long totalLength = -1;

                stateTmp = this.GetFileDataSize(downloadUrl, ref totalLength);
                if (TRunState.OK == stateTmp)
                {
                    // 下载被打断或者取消
                    if (DownloadManager.isCanceled == true)
                    {
                        stateTmp = TRunState.Canceled;
                    }
                }

                // 断点续传
                if (TRunState.OK == stateTmp)
                {
                    // 如果没下载完
                    if (fileLength < totalLength)
                    {
                        // 断点续传核心,设置本地文件流的起始位置
                        fs.Seek(fileLength, SeekOrigin.Begin);

                        Uri _url = new Uri(downloadUrl);
                        request = WebRequest.Create(_url) as HttpWebRequest;
                        if (null == request)
                        {
                            UtilsLog.Error("DownloaderBase", "DownloadFileByHttp:HttpWebRequest Create Failed!!!");
                        }
                        request.Timeout          = this.TimeOut;
                        request.ReadWriteTimeout = this.TimeOut;
                        request.ContentType      = "application/octet-stream";
                        request.KeepAlive        = false;

                        // 断点续传核心,设置远程访问文件流的起始位置
                        request.AddRange((int)fileLength);
                        response = request.GetResponse() as HttpWebResponse;
                        if (response == null)
                        {
                            ErrorDetail error = new ErrorDetail();
                            error.Type   = TErrorType.HttpError;
                            error.State  = this.State;
                            error.Detail = string.Format("The HttpWebRequest is null or created failed(Url:{0})",
                                                         downloadUrl);
                            error.Retries = this.Retries;
                            this._errors.Add(error);

                            stateTmp = TRunState.Error;
                        }
                        else
                        {
                            if ((HttpStatusCode.OK != response.StatusCode) &&
                                (HttpStatusCode.PartialContent != response.StatusCode))
                            {
                                ErrorDetail error = new ErrorDetail();
                                error.Type   = TErrorType.HttpError;
                                error.State  = TRunState.Error;
                                error.Detail = string.Format("HttpStatusCode:{0} Detail:{1}",
                                                             response.StatusCode, response.StatusDescription);
                                error.Retries = this.Retries;
                                this._errors.Add(error);

                                stateTmp = TRunState.Error;
                                response.Close();
                                response = null;
                            }
                        }

                        // 下载被打断或者取消
                        if (TRunState.OK == stateTmp)
                        {
                            // 下载被打断或者取消
                            if (DownloadManager.isCanceled == true)
                            {
                                stateTmp = TRunState.Canceled;
                            }
                        }

                        if ((TRunState.OK == stateTmp) && (null != response))
                        {
                            stream = response.GetResponseStream();

                            // 初始化下载缓存大小
                            byte[] buffer = new byte[_downloadBufferSize];

                            // 使用流读取内容到buffer中
                            // 注意方法返回值代表读取的实际长度
                            int length = stream.Read(buffer, 0, buffer.Length);
                            while (length > 0)
                            {
                                // 下载被打断
                                if (DownloadManager.isCanceled == true)
                                {
                                    stateTmp = TRunState.Canceled;
                                    break;
                                }

                                // 将缓存内容再写入本地文件中
                                fs.Write(buffer, 0, length);
                                fs.Flush();

                                // 计算进度
                                fileLength += length;
                                progress    = (float)fileLength / (float)totalLength;
                                progress    = (progress >= 1.0f) ? 1.0f : progress;

                                // 继续读取,直至读取完毕
                                length = stream.Read(buffer, 0, buffer.Length);
                            }
                        }
                        else
                        {
                            progress = 1.0f;
                        }
                    }
                }
            } catch (Exception exp) {
                ErrorDetail error = new ErrorDetail();
                error.Type   = TErrorType.SysException;
                error.State  = TRunState.Exception;
                error.Detail = string.Format("Type:{0} Msg:{1} StackTrace:{2}",
                                             exp.GetType().ToString(), exp.Message, exp.StackTrace);
                error.Retries = this.Retries;
                this._errors.Add(error);

                stateTmp = TRunState.Exception;

                if (null != request)
                {
                    request.Abort();
                }
            } finally {
                if (null != response)
                {
                    try
                    {
                        response.Close();
                        response = null;
                    }
                    catch {
                        request.Abort();
                    }
                }

                // 关闭&释放文件对象
                if (fs != null)
                {
                    fs.Close();
                    fs.Dispose();
                    fs = null;

                    UtilsLog.Info("DownloaderBase", "DownloadFileByHttp:File Close -> File:{0}", iFileName);
                }
                if (stream != null)
                {
                    stream.Close();
                    stream.Dispose();
                    stream = null;

                    UtilsLog.Info("DownloaderBase", "DownloadFileByHttp:Stream Close -> File:{0}", iFileName);
                }

                if ((TRunState.OK == this.State) &&
                    (this._target != null))
                {
                    // 检测文件
                    if (false == this.CheckFileByCheckMode(this._target, filePath))
                    {
                        // 删除文件
                        if (File.Exists(filePath) == true)
                        {
                            File.Delete(filePath);
                        }

                        stateTmp = TRunState.Error;

                        ErrorDetail error = new ErrorDetail();
                        error.Type    = TErrorType.FileCheckFailed;
                        error.State   = stateTmp;
                        error.Detail  = string.Format("File Check Failed!!!");
                        error.Retries = this.Retries;
                        this._errors.Add(error);

                        UtilsLog.Error("DownloaderBase", "DownloadFileByHttp:File Check -> NG (File:{0} Retries:{1})", iFileName, this.Retries);
                    }
                    else
                    {
                        UtilsLog.Info("DownloaderBase", "DownloadFileByHttp:File Check -> OK (File:{0} Retries:{1})", iFileName, this.Retries);
                    }
                }
            }
            return(stateTmp);
        }
Beispiel #25
0
        /// <summary>
        /// 下载文件(Http).
        /// </summary>
        /// <returns>运行状态.</returns>
        /// <param name="iParentUrl">下载父Url.</param>
        /// <param name="iFileName">下载文件名.</param>
        protected IEnumerator DownloadFileByWWW(string iParentUrl, string iFileName)
        {
            // 下载被打断
            if (DownloadManager.isCanceled == true)
            {
                this.State = TRunState.Canceled;
            }

            WWW www = null;

            if (TRunState.OK == this.State)
            {
                string downloadUrl = string.Format("{0}/{1}", iParentUrl, iFileName);

                www = new WWW(downloadUrl);
                // 设置下载权限
                www.threadPriority = UnityEngine.ThreadPriority.Normal;

                yield return(www);

                if (www.error != null)
                {
                    this.State = TRunState.Error;

                    ErrorDetail error = new ErrorDetail();
                    error.Type    = TErrorType.WWWError;
                    error.State   = this.State;
                    error.Detail  = www.error;
                    error.Retries = this.Retries;
                }
            }
            yield return(new WaitForEndOfFrame());

            // 下载被打断
            if (DownloadManager.isCanceled == true)
            {
                this.State = TRunState.Canceled;
            }

            if ((www != null) && (TRunState.OK == this.State))
            {
                string filePath = null;
                try {
                    // 字节
                    byte[] bytes = www.bytes;

                    string   fileName      = Path.GetFileNameWithoutExtension(www.url.Replace("%20", " "));
                    string   fileExtension = Path.GetExtension(www.url);
                    string[] strUrl        = fileExtension.Split('?');
                    filePath = string.Format("{0}/{1}{2}",
                                             this.DownloadDir, fileName, strUrl [0]);
                    filePath = filePath.Replace("%20", " ");
                    if (File.Exists(filePath) == true)
                    {
                        File.Delete(filePath);
                    }

                    // 生成并写入文件
                    File.WriteAllBytes(filePath, bytes);
#if UNITY_IOS
                    UnityEngine.iOS.Device.SetNoBackupFlag(filePath);
#endif
                }  catch (Exception exp) {
                    this.State = TRunState.Exception;
                    ErrorDetail error = new ErrorDetail();
                    error.Type   = TErrorType.SysException;
                    error.State  = this.State;
                    error.Detail = string.Format("System Exception Type:{0} Detail:{0}",
                                                 exp.GetType().ToString(), exp.Message);
                    error.Retries = this.Retries;
                    this._errors.Add(error);
                } finally {
                    if ((TRunState.OK == this.State) &&
                        (this._target != null))
                    {
                        // 检测文件
                        if (false == this.CheckFileByCheckMode(this._target, filePath))
                        {
                            // 删除文件
                            if (File.Exists(filePath) == true)
                            {
                                File.Delete(filePath);
                            }

                            this.State = TRunState.Error;
                            ErrorDetail error = new ErrorDetail();
                            error.Type    = TErrorType.FileCheckFailed;
                            error.State   = this.State;
                            error.Detail  = string.Format("File Check Failed!!!");
                            error.Retries = this.Retries;
                            this._errors.Add(error);

                            UtilsLog.Error("DownloadFileByWWW", "File Check -> NG (File:{0} Retries:{1})", iFileName, this.Retries);
                        }
                        else
                        {
                            UtilsLog.Info("DownloadFileByWWW", "File Check -> OK (File:{0} Retries:{1})", iFileName, this.Retries);
                        }
                    }
                }
            }
            yield return(new WaitForEndOfFrame());
        }
        /// <summary>
        /// 下载检测.
        /// </summary>
        /// <returns>The check.</returns>
        /// <param name="iDownloadPreCheck">下载预检查.</param>
        private IEnumerator DownloadCheck(bool iDownloadPreCheck)
        {
            // 下载开始
            this.isStarted = true;

            if (false == iDownloadPreCheck)
            {
                // 检测下载文件夹
                // 下载根目录
                this.CheckDownloadDirs(ServersConf.DownloadRootDir);
                yield return(new WaitForEndOfFrame());

                // 下载目录
                this.CheckDownloadDirs(ServersConf.DownloadDir);
                yield return(new WaitForEndOfFrame());

                // 下载目录(Normal)
                this.CheckDownloadDirs(ServersConf.DownloadDirOfNormal);
                yield return(new WaitForEndOfFrame());

                // 下载目录(Scenes)
                this.CheckDownloadDirs(ServersConf.DownloadDirOfScenes);
                yield return(new WaitForEndOfFrame());

                // Bundles目录
                this.CheckDownloadDirs(ServersConf.BundlesDir);
                yield return(new WaitForEndOfFrame());

                // Bundles目录(Normal)
                this.CheckDownloadDirs(ServersConf.BundlesDirOfNormal);
                yield return(new WaitForEndOfFrame());

                // Bundles目录(Scene)
                this.CheckDownloadDirs(ServersConf.BundlesDirOfScenes);
                yield return(new WaitForEndOfFrame());

                // 解压缩目录
                this.CheckDownloadDirs(ServersConf.DecompressedDir);
                yield return(new WaitForEndOfFrame());

                // 解压缩目录(Normal)
                this.CheckDownloadDirs(ServersConf.DecompressedDirOfNormal);
                yield return(new WaitForEndOfFrame());

                // 解压缩目录(Scenes)
                this.CheckDownloadDirs(ServersConf.DecompressedDirOfScenes);
                yield return(new WaitForEndOfFrame());
            }

            // 下载Bundle包依赖文件
            if (false == iDownloadPreCheck)
            {
                yield return(DownloadBundlesMap());

                yield return(new WaitForEndOfFrame());
            }

            if (TRunState.OK == this._State)
            {
                // 检测下载用上传列表
                if (false == iDownloadPreCheck)
                {
                    yield return(DownloadUploadlist());

                    yield return(new WaitForEndOfFrame());
                }
            }
            else
            {
                UtilsLog.Error("DownloadCheck", "Failed:State:{0}", this._State);
            }

            if ((false == iDownloadPreCheck) && (TRunState.OK == this._State))
            {
                // 更新下载文件
                UploadList.GetInstance().UpdateFromUploadlistFile();
                yield return(new WaitForEndOfFrame());

                // 更新下载列表
                UploadList.GetInstance().UpdateLocalInfoForDownload();
                yield return(new WaitForEndOfFrame());
            }

            if (TRunState.OK == this._State)
            {
                // 需要下载时
                if (DownloadList.GetInstance().isDownloadNecessary == true)
                {
                    // 下载前确认提示
                    this.DownloadPreConfirmNotification(
                        DownloadList.GetInstance().GetTotalCount(),
                        DownloadList.GetInstance().GetTotalDatasize());
                }
                else
                {
                    this.isStarted    = false;
                    this._isCompleted = false;

                    UtilsLog.Info("DownloadCheck", "There is no download target or all already be downloaded!");
                    this.DownloadCompleteNotification(false);
                }
            }

            yield return(null);
        }