示例#1
0
        private byte[] CheckPack(byte[] data)
        {
            if (data.Length < 4 || !BitConverter.ToInt32(data, 0).Equals(flagHeader))
            {
                return(null);
            }
            byte[] countArr = new byte[8];
            byte[] md5Arr   = new byte[32];

            for (int i = 4; i < 12; i++)
            {
                countArr[i - 4] = data[i];
                data[i]         = 0;
            }

            for (int i = 36; i < 68; i++)
            {
                md5Arr[i - 36] = data[i];
                data[i]        = 0;
            }

            byte[] finalData = new byte[BitConverter.ToInt32(countArr, 0)];

            Array.Copy(data, finalData, finalData.Length);

            string md5Check = MD5Code.GetMD5HashFromByte(data);
            string md5Req   = Encoding.UTF8.GetString(md5Arr);

            if (!string.Compare(md5Check, md5Req).Equals(0))
            {
                return(null);
            }

            return(finalData);
        }
示例#2
0
        private bool CheckRegisnFile()
        {
            if (!File.Exists(regisnTextPath))
            {
                return(false);
            }

            string[] code = File.ReadAllLines(regisnTextPath);

            if (code.Length < 3)
            {
                return(false);
            }
            string regisnCode = code[1];

            string md5 = MD5Code.GetMD5HashFromByte(Encoding.UTF8.GetBytes(mCode + regisnCode));

            if (!string.Compare(md5, code[2]).Equals(0))
            {
                return(false);
            }
            this.id         = code[0];
            this.regisnCode = regisnCode;
            return(true);
        }
示例#3
0
        public static void _BuildFileVersionList()
        {
#if UNITY_IOS
            string file_name = "FileVersionList_ios.json";
#else
            string file_name = "FileVersionList.json";
#endif

            try
            {
                File.Delete(file_name);
            }
            catch (Exception e)
            {
            }
            var             files = Directory.GetFiles("AssetBundles", "*", System.IO.SearchOption.AllDirectories);
            FileVersionList list  = new FileVersionList();
            foreach (var p in files)
            {
                FileVersion v = new FileVersion();
                v.file = p.Replace("\\", "/");
                v.md5  = MD5Code.GetMD5HashFromFile(p);
                FileInfo info = new FileInfo(v.file);
                v.size = (int)info.Length;
                list.files.Add(v);
            }
            var json = UnityEngine.JsonUtility.ToJson(list);
            File.WriteAllText(file_name, json);
        }
示例#4
0
        public static void _BuildFSFirm()
        {
            try
            {
                Directory.Delete("Assets/StreamingAssets");
            }
            catch (Exception e) { }
            try
            {
                Directory.CreateDirectory("Assets/StreamingAssets");
            }
            catch (Exception e) { }


            var files = Directory.GetFiles("AssetBundles", "*", System.IO.SearchOption.AllDirectories);

            FileVersionList fsfirm_list = new FileVersionList();

            foreach (var pp in files)
            {
                string p = pp.Replace("\\", "/");
                if (Patches.Patcher.ForceCheckMD5(p))
                {
                    FileVersion v = new FileVersion();
                    v.file = p;
                    v.size = (int)(new FileInfo(p)).Length;
                    v.md5  = MD5Code.GetMD5HashFromFile(p);

                    fsfirm_list.files.Add(v);

                    //engine 文件不需要打进去
                    if (p.Contains("/engine/"))
                    {
                        continue;
                    }

                    string target = "Assets/StreamingAssets/" + p;
                    int    found  = target.LastIndexOf("/");
                    if (found != target.Length)
                    {
                        if (!Directory.Exists(target.Substring(0, found)))
                        {
                            Directory.CreateDirectory(target.Substring(0, found));
                        }
                    }
                    File.Copy(p, target, true);
                }
            }
            try
            {
                File.Delete(DevConfig.FSFirmVersionListFileName);
            }
            catch (Exception e) { }

            File.WriteAllText("Assets/Resources/" + DevConfig.FSFirmVersionListFileName, JsonUtility.ToJson(fsfirm_list));

            AssetDatabase.Refresh();
        }
示例#5
0
        private void SetRegisignFile2Local(string id)
        {
            if (File.Exists(regisnTextPath))
            {
                File.Delete(regisnTextPath);
            }
            string[] code = new string[3];
            code[0] = id;
            code[1] = this.regisnCode;
            code[2] = MD5Code.GetMD5HashFromByte(Encoding.UTF8.GetBytes(this.mCode + this.regisnCode));

            File.WriteAllLines(regisnTextPath, code);
        }
示例#6
0
 public static void EncryptFile(string filePath)
 {
     if (File.Exists(filePath))
     {
         FileStream   stream = null;
         StreamReader reader = null;
         BinaryWriter writer = null;
         try
         {
             FileInfo info = new FileInfo(filePath);
             stream = new FileStream(filePath, FileMode.Open);
             string source = "";
             reader = new StreamReader(stream);
             source = reader.ReadToEnd();
             reader.Close();
             stream.Close();
             File.Delete(filePath);
             string str2 = "";
             str2   = source;//new
             str2   = MD5Code.Encode(source);
             stream = File.Open(filePath, FileMode.CreateNew);
             stream.Seek(0L, SeekOrigin.Begin);
             writer = new BinaryWriter(stream);
             writer.Write(BinaryInsertNum);
             writer.Write(UnityEngine.Random.Range(0, 100));
             writer.Write(UnityEngine.Random.Range(0x10, 0x4e));
             writer.Write(str2);
         }
         catch (Exception exception)
         {
             Debug.Log("EncryptFile --- " + exception.Message);
         }
         finally
         {
             if (reader != null)
             {
                 reader.Close();
             }
             if (stream != null)
             {
                 stream.Close();
             }
         }
     }
 }
示例#7
0
        /// <summary>
        /// 处理激活
        /// </summary>
        /// <param name="id">用户登录id</param>
        /// <param name="code">激活码</param>
        /// <returns></returns>
        public ActionResult Activation(string id, string code)
        {
            try
            {
                var users = (from m in _db.Users
                             where m.username == id
                             select m);

                if (users.Count() != 1)
                {
                    TempData["ErrorMessage"] = "Failed to Active";
                    return(RedirectToAction("Main", "Main"));
                }
                else if (MD5Code.verifyMd5Hash(users.First().username, code) && users.First().ustate == 0)
                {
                    users.First().ustate = 1;
                    _db.ApplyCurrentValues <Users>(users.First().EntityKey.EntitySetName, users.First());
                    _db.SaveChanges();
                    TempData["SuccessMessage"] = "Active Successful";
                    return(RedirectToAction("Main", "Main"));
                }
                else if (MD5Code.verifyMd5Hash(users.First().username, code) && users.First().ustate != 0)
                {
                    TempData["WarningMessage"] = "You have already been actived. Keep an eye on your emails.";
                    return(RedirectToAction("Main", "Main"));
                }
                else
                {
                    TempData["ErrorMessage"] = "Time out. Sign up again, please.";
                    return(RedirectToAction("Main", "Main"));
                }
            }
            catch (Exception ex)
            {
                TempData["ErrorMessage"] = "Failed to Active" + ex.Message;
                return(RedirectToAction("Main", "Main"));
            }
            // TempData["ErrorMessage"] = "Failed to Active";
            // return RedirectToAction("Main", "Main");
        }
示例#8
0
        private void SetReqHeader(UdpRequestBase req)
        {
            if (!req.Id.Equals(0xffffffff))
            {
                return;
            }
            req.Id = Interlocked.Add(ref reqId, 1);
            req.SetIndex(0);
            req.WriteInt32(flagHeader);
            req.WriteInt64(req.Id);
            req.SetIndex(20);//跳过包长度
            req.WriteInt32(req.ClientId);
            req.WriteInt32(req.ProtocolId);
            req.TimeTick = System.DateTime.Now.Ticks;
            req.WriteInt64(req.TimeTick);
            string md5 = MD5Code.GetMD5HashFromByte(req.getMemData());

            byte[] checkData = Encoding.UTF8.GetBytes(md5);
            req.SetIndex(36);
            req.SetMd5Header(checkData);
            req.SetIndex(12);
            req.Count += 8;//加上自己
            req.WriteInt64(req.Count);
        }
示例#9
0
        public ActionResult Register(Users userToCreate)
        {
            if (!ModelState.IsValid)
            {
                return(View());
            }

            try
            {
                var users = (from m in _db.Users
                             where m.username == userToCreate.username
                             select m);

                if (users.Count() != 0)
                {
                    TempData["ErrorMessage"] = "User name exists! ";
                    return(View());
                }
                if (userToCreate.upasswd != Request.Form["ConfirmPassword"])
                {
                    TempData["ErrorMessage"] = "Registration failed! Your passwords must match, please re-enter and try again.";
                    return(View());
                }

                try
                {
                    string content = System.IO.File.ReadAllText(Server.MapPath("~/NewMemberEmail.txt"));
                    content = content.Replace("[Name]", userToCreate.username);
                    content = content.Replace("[LINK]", "<a href='http://" + Request.Url.Host + ":" + Request.Url.Port + "/User/Activation-" + Server.UrlEncode(userToCreate.username) + "-" + MD5Code.getMd5Hash(userToCreate.username) + "'>^_^Active^_^</a>");
                    content = content.Replace("[UserName]", userToCreate.username);
                    content = content.Replace("[Pwd]", userToCreate.upasswd);

                    if (!SendMail.send(userToCreate.uemail, content, Server, "Active"))
                    {
                        TempData["ErrorMessage"] = "Sorry. The format of your email address can't be recognized.";
                        return(View());
                    }
                    ;
                }
                catch (Exception ex)
                {
                    TempData["ErrorMessage"] = "Registration failed! Check your email again please." + ex.Message;
                    return(View());
                }

                try
                {
                    string key = userToCreate.username;
                    while (key.Length < 8)
                    {
                        key = key + key;
                    }
                    userToCreate.upasswd = DESCode.EncryptDES(userToCreate.upasswd, key);
                    _db.AddToUsers(userToCreate);
                    _db.SaveChanges();
                    TempData["SuccessMessage"] = "Registration succeeds! Your can log in using the new username and password.";
                }
                catch (Exception ex)
                {
                    TempData["ErrorMessage"] = "The databse is unreachable. Try again later." + ex.Message;
                    return(View());
                }

                return(RedirectToAction("Main"));
            }
            catch (Exception exception)
            {
                TempData["ErrorMessage"] = "Registration has failed because: " + exception.Message;
                return(View());
            }
        }
示例#10
0
        public static string UploadPatch(string local_file, string target)
        {
            string error_pre = "FTP Upload local_file=" + local_file + "  error:";

            string error     = "";
            string local_md5 = "";

            try
            {
                local_md5 = MD5Code.GetMD5HashFromFile(local_file);
                if (string.IsNullOrEmpty(local_md5))
                {
                    return("local md5 error");
                }
                var    ins    = File.ReadAllLines("ftp_config.txt");
                string SERVER = ins[0];
                string NAME   = ins[1];
                string PWD    = ins[2];

                FileInfo f = new FileInfo(local_file);


                var           uri    = new Uri(SERVER + "/" + target);
                FtpWebRequest reqFtp = (FtpWebRequest)FtpWebRequest.Create(uri);
                reqFtp.UseBinary   = true;
                reqFtp.Credentials = new NetworkCredential(NAME, PWD);
                reqFtp.KeepAlive   = false;
                //   reqFtp.EnableSsl = true;
                reqFtp.Method        = WebRequestMethods.Ftp.UploadFile;
                reqFtp.ContentLength = f.Length;

                int        buffLength = 2048;
                byte[]     buff       = new byte[buffLength];
                int        contentLen;
                FileStream fs = f.OpenRead();

                Stream strm = reqFtp.GetRequestStream();
                contentLen = fs.Read(buff, 0, buffLength);
                while (contentLen != 0)
                {
                    strm.Write(buff, 0, contentLen);
                    contentLen = fs.Read(buff, 0, buffLength);
                }
                strm.Close();
                fs.Close();

                //反向下载 并且检查 文件MD5是否正确
                // Get the object used to communicate with the server.
                WebClient request = new WebClient();

                // This example assumes the FTP site uses anonymous logon.
                request.Credentials = new NetworkCredential(NAME, PWD);
                try
                {
                    byte[] newFileData   = request.DownloadData(uri.ToString());
                    string fileString    = System.Text.Encoding.UTF8.GetString(newFileData);
                    string tmp_file_name = "tmp_ftp_md5_file.zip";
                    EditorUtils.Utils.TryDeleteFile(tmp_file_name);
                    var x = File.Create(tmp_file_name);
                    x.Write(newFileData, 0, newFileData.Length);
                    x.Flush();
                    x.Close();

                    string remote_md5 = MD5Code.GetMD5HashFromFile(tmp_file_name);

                    if (remote_md5 != local_md5)
                    {
                        return(error_pre + "remote md5 error re-try-upload-operation local=" + local_md5 + "  remote=" + remote_md5);
                    }
                }
                catch (WebException e)
                {
                    return(error_pre + e.ToString());
                }
                error = "ok";
            }
            catch (Exception e)
            {
                error = error_pre + " error " + e.Message;
            }
            return(error);
        }
示例#11
0
    public static bool loadConfig <T>(string fileName, ref T result, CallBack_Void_S onUpdateCallback, bool isDefault = false) where T : new()
    {
        fileName = CheckReplaceFile(fileName);
        if (onUpdateCallback != null)
        {
            if (!updateCallbacks.ContainsKey(fileName))
            {
                updateCallbacks.Add(fileName, null);
            }
            updateCallbacks[fileName] = onUpdateCallback;
        }
        bool   flag  = false;
        bool   flag2 = false;
        string path  = PathConfig.getFilePath(ConfigType.XML, fileName, true);

        if (File.Exists(path) && !isDefault)
        {
            flag = FileTool.OpenSerializedInfo <T>(path, ref result);
            if (!flag)
            {
                Debug.Log(fileName + " 更新配置文件损坏");
                flag2 = true;
                File.Delete(path);
            }
        }
        if ((((T)result) == null) || !flag)
        {
            TextAsset asset = Resources.Load("data/" + fileName, typeof(TextAsset)) as TextAsset;
            if ((asset == null) || string.IsNullOrEmpty(asset.text))
            {
                return(flag2);
            }
            string       text  = asset.text;
            MemoryStream input = new MemoryStream();
            input.Write(asset.bytes, 0, asset.bytes.Length);
            input.Seek(0L, SeekOrigin.Begin);
            BinaryReader reader = new BinaryReader(input, Encoding.UTF8);
            try
            {
                string str3 = "";
                if (reader.ReadInt32() == 5)
                {
                    int num = reader.ReadInt32();
                    num  = reader.ReadInt32();
                    str3 = MD5Code.Decode(reader.ReadString());
                    Debug.LogWarning(fileName + " 文件启用加密");
                }
                else
                {
                    Debug.LogWarning(fileName + " 文件没有加密");
                }
                if (!string.IsNullOrEmpty(str3))
                {
                    text = str3;
                }
            }
            catch (Exception exception)
            {
                Debug.LogError(fileName + " 解析出错 : " + exception.Message);
            }
            finally
            {
                if (reader != null)
                {
                    reader.Close();
                }
            }
            FileTool.OpenSerializedInfoByContent <T>(text, ref result);
        }
        return(flag2);
    }
示例#12
0
        public static void _BuildZip_Android()
        {
            string path_pre_name = "VersionFiles/AssetBundles/Android/";

            string path = EditorUtils.Utils.GetCurrentWorkingPath() + "/VersionFiles/AssetBundles/Android/AssetBundles_diff";

            //需要构建的版本号

            string v = File.ReadAllText("VersionFiles/VERSION.txt");


            string out_zip_full_name = "android_" + v + ".zip"; // "VersionFiles/" + v + "/android_" + v + ".zip";

            using (ZipFile zip = ZipFile.Create(out_zip_full_name))
            {
                zip.BeginUpdate();
                zip.AddDirectory("AssetBundles");
                try
                {
                    Directory.Delete("AssetBundles_diff", true);
                }
                catch (Exception e)
                {
                }
                //这样绕一下处理diff是因为 lua/lua这个文件 在 原路径下 打包zip会出错(ziplib的BUG)
                EditorUtils.Utils.CopyDir("VersionFiles/AssetBundles/Android/AssetBundles_diff", "AssetBundles_diff");

                foreach (var d in Directory.GetDirectories("AssetBundles_diff"))
                {
                    zip.AddDirectory(d.Replace("AssetBundles_diff", "AssetBundles"));
                }
                foreach (var p in Directory.GetFiles("AssetBundles_diff", "*", SearchOption.AllDirectories))
                {
                    zip.Add(p, p.Replace("AssetBundles_diff", "AssetBundles"));
                }
                zip.CommitUpdate();
                Directory.Delete("AssetBundles_diff", true);
            }
            if (File.Exists("VersionFiles/" + v + "/android_" + v + ".zip"))
            {
                File.Delete("VersionFiles/" + v + "/android_" + v + ".zip");
            }
            if (Directory.Exists("VersionFiles/" + v) == false)
            {
                Directory.CreateDirectory("VersionFiles/" + v);
            }

            File.Move(out_zip_full_name, "VersionFiles/" + v + "/android_" + v + ".zip");
            File.Delete(out_zip_full_name);

            out_zip_full_name = "VersionFiles/" + v + "/android_" + v + ".zip";

            string md5  = MD5Code.GetMD5HashFromFile(out_zip_full_name);
            int    size = 0;

            using (var zip = File.OpenRead(out_zip_full_name))
            {
                size = (int)zip.Length;
            }
            Patches.Version this_version = new Patches.Version();
            Debug.Log("Patch Zip:will build version = " + v);
            this_version.Parse(v);
            this_version.MD5      = md5;
            this_version.FileSize = size;

            //  Debug.LogError(LitJson.JsonMapper.ToJson(this_version));


            {
                var ss = File.CreateText("VersionFiles/" + v + "/android_" + v + ".json");


                ss.Write(LitJson.JsonMapper.ToJson(this_version));
                ss.Flush();
                ss.Close();
            }

            //resfresh all
            {
                //      Debug.LogError(pat);
                var patches = Directory.GetDirectories("VersionFiles", this_version.MainVersion + ".*.*", SearchOption.AllDirectories);
                List <Patches.Version> _patch_vs = new System.Collections.Generic.List <Patches.Version>();
                foreach (var pp in patches)
                {
                    var             p  = Path.GetFileName(pp);
                    Patches.Version vv = new Patches.Version();
                    vv.Parse(p);
                    _patch_vs.Add(vv);
                }
                _patch_vs.Sort();
                VersionList _VL = new VersionList();

                foreach (var p in _patch_vs)
                {
                    string ver    = p.MainVersion.ToString() + "." + p.SubVersion.ToString() + "." + p.PatchVersion.ToString() + "/android_" + p.MainVersion.ToString() + "." + p.SubVersion.ToString() + "." + p.PatchVersion.ToString() + ".json";
                    var    this_v = File.ReadAllText("VersionFiles/" + ver);
                    Debug.LogError(ver);

                    _VL.versions.Add(LitJson.JsonMapper.ToObject <Patches.Version>(this_v));
                }

                {
                    var ss = File.CreateText("VersionFiles/FULL_VERSIONS.json");

                    ss.Write(LitJson.JsonMapper.ToJson(_VL));
                    ss.Flush();
                    ss.Close();
                }
            }
            Debug.Log("Patch Zip:build android done ");
        }
示例#13
0
        public static void _BuildZip()
        {
            //需要构建的版本号

            string v = File.ReadAllText("VersionFiles/VERSION.txt");


            string out_zip_full_name = "android_" + v + ".zip"; // "VersionFiles/" + v + "/android_" + v + ".zip";

            using (ZipFile zip = ZipFile.Create(out_zip_full_name))
            {
                zip.BeginUpdate();

                zip.AddDirectory("AssetBundles");

                foreach (var d in Directory.GetDirectories("AssetBundles"))
                {
                    zip.AddDirectory(d);
                }
                foreach (var p in Directory.GetFiles("AssetBundles", "*", SearchOption.AllDirectories))
                {
                    zip.Add(p);
                    //  Debug.LogError(p);
                }

                zip.CommitUpdate();
            }
            if (File.Exists("VersionFiles/" + v + "/android_" + v + ".zip"))
            {
                File.Delete("VersionFiles/" + v + "/android_" + v + ".zip");
            }
            if (Directory.Exists("VersionFiles/" + v) == false)
            {
                Directory.CreateDirectory("VersionFiles/" + v);
            }

            File.Move(out_zip_full_name, "VersionFiles/" + v + "/android_" + v + ".zip");
            File.Delete(out_zip_full_name);

            out_zip_full_name = "VersionFiles/" + v + "/android_" + v + ".zip";

            string md5  = MD5Code.GetMD5HashFromFile(out_zip_full_name);
            int    size = 0;

            using (var zip = File.OpenRead(out_zip_full_name))
            {
                size = (int)zip.Length;
            }
            Patches.Version this_version = new Patches.Version();
            Debug.LogError(v);
            this_version.Parse(v);
            this_version.MD5      = md5;
            this_version.FileSize = size;
            Debug.LogError(LitJson.JsonMapper.ToJson(this_version));

            {
                var ss = File.CreateText("VersionFiles/" + v + "/android_" + v + ".json");
                ss.Write(LitJson.JsonMapper.ToJson(this_version));
                ss.Flush();
                ss.Close();
            }

            //resfresh all
            {
                string pat = this_version.MainVersion.ToString() + "." + this_version.SubVersion.ToString() + ".";
                //      Debug.LogError(pat);
                var        patches   = Directory.GetDirectories("VersionFiles", this_version.MainVersion + "." + this_version.SubVersion + ".*", SearchOption.AllDirectories);
                List <int> _patch_vs = new System.Collections.Generic.List <int>();
                foreach (var pp in patches)
                {
                    var             p  = Path.GetFileName(pp);
                    Patches.Version vv = new Patches.Version();
                    Debug.LogError(pp + "     " + p);
                    vv.Parse(p);
                    _patch_vs.Add(vv.PatchVersion);
                }
                _patch_vs.Sort();
                VersionList _VL = new VersionList();

                foreach (var p in _patch_vs)
                {
                    string ver = this_version.MainVersion.ToString() + "." + this_version.SubVersion.ToString() + "." + p.ToString() + "/android_" + this_version.MainVersion.ToString() + "." + this_version.SubVersion.ToString() + "." + p.ToString() + ".json";

                    var this_v = File.ReadAllText("VersionFiles/" + ver);
                    Debug.LogError(ver);

                    Patches.Version x = new Patches.Version();

                    _VL.versions.Add(LitJson.JsonMapper.ToObject <Patches.Version>(this_v));
                }

                {
                    var ss = File.CreateText("VersionFiles/FULL_VERSIONS.json");

                    ss.Write(LitJson.JsonMapper.ToJson(_VL));
                    ss.Flush();
                    ss.Close();
                }
            }
        }
示例#14
0
        async public Task <bool> DownloadAsync()
        {
            var ts = DateTime.Now - this.lastCheckTime;

            if (ts.TotalSeconds < this.intervalSeconds)
            {
                return(false);
            }

            bool   isChanged = false;
            string oldMD5    = this.MD5;

            this.checkCounter++;
            this.lastCheckTime = DateTime.Now;
            Stopwatch sw    = Stopwatch.StartNew();
            Exception error = null;

            using (var httpClient = new HttpClient())
            {
                try
                {
                    HttpResponseMessage respone = await httpClient.GetAsync(DownloadUri);

                    respone.EnsureSuccessStatusCode();
                    HttpContent         httpContent     = respone.Content;
                    HttpContentHeaders  contentHeaders  = httpContent.Headers;
                    HttpResponseHeaders responseHeaders = respone.Headers;

                    if (this.contentLength != contentHeaders.ContentLength)
                    {
                        isChanged = true;
                    }
                    else if (contentLastModified != ToDateTime(contentHeaders.LastModified))
                    {
                        isChanged = true;
                    }
                    this.contentLength       = contentHeaders.ContentLength;
                    this.contentLastModified = ToDateTime(contentHeaders.LastModified);
                    this.contentType         = contentHeaders.ContentType;

                    using (MemoryStream ms = new MemoryStream())
                    {
                        if (IsNeedCheckMD5)
                        {
                            await httpContent.CopyToAsync(ms);

                            string newMD5 = MD5Code.StreamMD5(ms);
                            if (this.md5 != newMD5)
                            {
                                this.md5  = newMD5;
                                isChanged = true;
                            }
                        }//IsNeedCheckMD5

                        if (isChanged)
                        {
                            this.lastChangeTime = DateTime.Now;
                            changeCounter++;

                            if (ms.Length > 0) //已经下载过
                            {
                                if (IsNeedCheck_PT_SS)
                                {
                                    this.pt_ss = Search_PT_SS(ms);

                                    /**
                                     * if (this.pt_ss != ptss)
                                     * {
                                     *
                                     *  this.pt_ss = ptss;
                                     * }
                                     * **/
                                }//IsNeedCheck_PT_SS
                                ms.Position = 0;
                                using (FileStream fs = File.Create(tempFileName))
                                {
                                    ms.Position = 0;
                                    ms.WriteTo(fs);
                                }
                            }    //(ms.Length > 0)
                            else //
                            {
                                using (FileStream fs = File.Create(tempFileName))
                                {
                                    await httpContent.CopyToAsync(fs);
                                }
                                //long len = await transfer.DownloadAsync(new Uri(this.Uri), this.SaveFileName, httpClient);
                            }
                        }//(isChanged)

                        errorCounter = 0;
                    }// using (MemoryStream ms
                }
                catch (Exception ex)
                {
                    error = ex;

                    errorCounter++;
                    if (errorCounter > 20)
                    {
                        errorCounter = 20;
                    }
                    errorMsg           = ex.Message;
                    this.lastCheckTime = DateTime.Now.AddSeconds(errorCounter * 60); //推迟下次请求时间
                    //loger.Error(System.Reflection.MethodBase.GetCurrentMethod().Name, ex);
                }
                //NotifyResult(transfer, downloadNotify, isChanged, error); //update by hua
                //this.NotifyResultAsync(transfer, downloadNotify, isChanged, error);
                if (isChanged)
                {
                    foreach (var dsf in SaveFiles.Values)
                    {
                        await dsf.FromAsync(this.tempFileName);
                    }
                }
                sw.Stop();
                this.procDuration = (long)sw.Elapsed.TotalMilliseconds;

                return(isChanged);
            }//using httpclient
        }
示例#15
0
 public static string DecryptFile(string filePath)
 {
     if (File.Exists(filePath))
     {
         FileStream   input   = null;
         StreamReader reader  = null;
         BinaryReader reader2 = null;
         try
         {
             FileInfo info = new FileInfo(filePath);
             input   = new FileStream(filePath, FileMode.Open);
             reader2 = new BinaryReader(input, Encoding.UTF8);
             bool   flag   = false;
             string source = "";
             try
             {
                 if (reader2.ReadInt32() == BinaryInsertNum)
                 {
                     flag = true;
                     reader2.ReadInt32();
                     reader2.ReadInt32();
                     source = reader2.ReadString();
                     source = MD5Code.Decode(source);
                 }
             }
             catch (Exception exception)
             {
                 Debug.LogError(filePath + "_____DecryptFile Error : " + exception.Message);
             }
             finally
             {
                 if (reader2 != null)
                 {
                     reader2.Close();
                 }
                 if (input != null)
                 {
                     input.Close();
                 }
             }
             if (!flag)
             {
                 input  = new FileStream(filePath, FileMode.Open);
                 reader = new StreamReader(input);
                 source = reader.ReadToEnd();
             }
             return(source);
         }
         catch
         {
         }
         finally
         {
             if (reader != null)
             {
                 reader.Close();
             }
             if (reader2 != null)
             {
                 reader2.Close();
             }
             if (input != null)
             {
                 input.Close();
             }
         }
     }
     return("");
 }
    private void ThreadFunc(object _param_call)
    {
        CurrentSize = 0;
        TotalSize   = 0;
        DownloadParam _param = _param_call as DownloadParam;

        if (_param == null)
        {
            IsThreadRunning = false;
            _Status         = Status.Error;
            return;
        }
        Debug.LogWarning("start to download " + _param.url);
        if (_param.IsRedirect)
        {
            //重定向的话 不处理 失败 重试次数
            _param.IsRedirect = false;
        }
        else
        {
            //重新下载 或者 分批下载 都会重试计次
            ++try_times;
        }
        if (try_times > 10)
        {
            //fatal error or net error
            _Status = Status.Error;
            return;
        }
        try
        {
            _Status = Status.Verifying;
            if (File.Exists(_param.path_to_save + "/" + _param.file_name))
            {
                //文件存在的话 检查一下 是否成功  不成功的话 才开始下载
                _Status = Status.Verifying;
                if (string.IsNullOrEmpty(_param.md5) == false && _param.md5 == MD5Code.GetMD5HashFromFile(_param.path_to_save + "/" + _param.file_name))
                {
                    //ok
                    _Status = Status.OK;
                    this.DownloadOK();
                    return;
                }
                else
                {
                    //md5 verify error 需要处理下载 (or断点下载) 下载完成后 才 再次校验
                }
            }
        }
        catch (Exception e)
        {
        }
        _Status = Status.Checking;

        if (_param.enable_break_point == false)
        {
            //无需断点下载 尝试暴力删除文件
            try
            {
                Directory.Delete(_param.path_to_save, true);
            }
            catch (Exception e)
            {
                Debug.LogWarning(e.Message);
            }
        }
        if (Directory.Exists(_param.path_to_save) == false)
        {
            try
            {
                Directory.CreateDirectory(_param.path_to_save);
            }
            catch (Exception e)
            {
                Debug.LogWarning(e.Message);
            }
        }
        //先打开文件
        Stream file = null;

        using (file = (File.Exists(_param.path_to_save + "/" + _param.file_name)) ? File.OpenWrite(_param.path_to_save + "/" + _param.file_name) : file = File.Create(_param.path_to_save + "/" + _param.file_name))
        {
            /*  try
             * {
             *    if (File.Exists(_param.path_to_save + "/" + _param.file_name))
             *    {
             *        file = File.OpenWrite(_param.path_to_save + "/" + _param.file_name);
             *    }
             *    else
             *    {
             *        file = File.Create(_param.path_to_save + "/" + _param.file_name);
             *    }
             * }
             * catch (Exception e)
             * {
             *    Debug.LogWarning(e.Message);
             * }*/
            try
            {
                long current_size = file.Length;
                if (current_size > 0)
                {
                    file.Seek(current_size, SeekOrigin.Begin);
                }
                HttpWebRequest request = null;

                //如果是发送HTTPS请求
                if (_param.url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
                {
                    ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                    request = (HttpWebRequest)WebRequest.Create(_param.url);
                }
                else
                {
                    request = (HttpWebRequest)WebRequest.Create(_param.url);
                }
                request.ProtocolVersion = new System.Version(1, 1);
                if (current_size > 0)
                {
                    request.AddRange((int)current_size);
                    CurrentSize = (int)current_size;
                }
                HttpWebResponse response = null;
                request.Timeout          = 10000;
                request.ReadWriteTimeout = 10000;
                request.Method           = "GET";
                request.KeepAlive        = false;
                response = (HttpWebResponse)request.GetResponse();

                var HttpRetCode = response.StatusCode;
                Debug.Log("InstallDownloader http " + HttpRetCode);


                if (HttpRetCode == HttpStatusCode.Redirect)
                {
                    //重定向
                    _param.url = response.Headers["Location"].Trim();
                    response.Close();
                    response = null;
                    request.Abort();
                    request = null;
                    try
                    {
                        file.Close();
                    }
                    catch (Exception e)
                    {
                        Debug.LogWarning(e.Message);
                    }
                    Debug.Log("Redirect " + _param.url);
                    _param.IsRedirect = true;
                    ThreadFunc(_param);
                    return;
                }
                else if (HttpRetCode == HttpStatusCode.GatewayTimeout || HttpRetCode == HttpStatusCode.RequestTimeout)
                {
                    //net error
                    response.Close();
                    response = null;
                    request.Abort();
                    request = null;
                    try
                    {
                        file.Close();
                    }
                    catch (Exception e)
                    {
                        Debug.LogWarning(e.Message);
                    }
                    Debug.Log("timeout");

                    return;
                }
                else if (HttpRetCode == HttpStatusCode.OK || HttpRetCode == HttpStatusCode.Created || HttpRetCode == HttpStatusCode.Accepted || HttpRetCode == HttpStatusCode.NonAuthoritativeInformation || HttpRetCode == HttpStatusCode.NoContent || HttpRetCode == HttpStatusCode.ResetContent || HttpRetCode == HttpStatusCode.PartialContent)
                {
                    if (HttpRetCode != HttpStatusCode.PartialContent)
                    {
                        //如果不是断点下载 或者服务器不支持 那么需要 重新下载完整文件
                        try
                        {
                            file.Close();
                            file = null;
                        }
                        catch (Exception e)
                        {
                        }
                        try
                        {
                            Directory.Delete(_param.path_to_save, true);
                        }
                        catch (Exception e)
                        {
                        }
                        try
                        {
                            Directory.CreateDirectory(_param.path_to_save);
                        }
                        catch (Exception e)
                        {
                        }
                        file = File.Create(_param.path_to_save + "/" + _param.file_name);
                    }
                }
                else
                {
                    //req error
                    response.Close();
                    response = null;
                    request.Abort();
                    request = null;
                    try
                    {
                        file.Close();
                    }
                    catch (Exception e)
                    {
                        Debug.LogWarning(e.Message);
                    }
                    try
                    {
                        File.Delete(_param.path_to_save + "/" + _param.file_name);
                    }
                    catch (Exception e) { }
                    Debug.LogWarning("error");
                    return;
                }

                //web 请求处理完成了 开始处理 接受数据了
                long total_len = response.ContentLength;

                TotalSize = (int)total_len + (int)current_size;
                if (current_size < TotalSize)
                {
                    if (current_size > 0)
                    {
                        //   request.AddRange((int)current_size);
                        CurrentSize = (int)current_size;
                    }
                    Stream web             = request.GetResponse().GetResponseStream();
                    byte[] _cache          = new byte[10240]; // 10kb
                    int    down_size       = 0;
                    int    read_size       = web.Read(_cache, 0, 10240);
                    int    total_read_size = 0;
                    _Status = Status.Downloading;
                    while (read_size > 0)
                    {
                        _Status = Status.Downloading;
                        file.Write(_cache, 0, read_size);
                        total_read_size += read_size;

                        down_size   += read_size;
                        CurrentSize += read_size;
                        //    Debug.LogError("download ing " + CurrentSize + "         " + TotalSize);
                        file.Flush();
                        read_size = web.Read(_cache, 0, 10240);
                    }
                    file.Close();
                    file = null;
                    web.Close();
                    web = null;
                    response.Close();
                    response = null;
                    request.Abort();
                    request = null;


                    if (current_size + down_size < TotalSize)
                    {
                        //下载文件 长度不够 需要重新下载
                        Debug.LogWarning("file is smaller will re-try");
                        ThreadFunc(_param);
                        return;
                    }
                    else if (current_size + down_size > TotalSize)
                    {
                        //下载的长度 超过了 实际长度 文件已经损坏 重新下载把
                        try
                        {
                            Directory.Delete(_param.path_to_save, true);
                        }
                        catch (Exception e)
                        {
                            Debug.LogWarning(e.Message);
                        }
                        Debug.LogWarning("file is bigger will delete and re-download");

                        ThreadFunc(_param);
                        return;
                    }
                    else
                    {
                        //下载文件成功 开始校验MD5
                        _Status = Status.Verifying;
                        string download_md5 = MD5Code.GetMD5HashFromFile(_param.path_to_save + "/" + _param.file_name);
                        if (string.IsNullOrEmpty(_param.md5) == false && _param.md5 == download_md5)
                        {
                            //ok
                        }
                        else
                        {
                            if (_param.md5 != null)
                            {
                                Debug.LogWarning("excepted md5=" + _param.md5 + "  file=" + download_md5);
                            }
                            //md5 verify error 尝试重新下载
                            try
                            {
                                file.Close();
                                file = null;
                                response.Close();
                                response = null;
                                request.Abort();
                                request = null;
                            }
                            catch (Exception e)
                            {
                            }
                            try
                            {
                                Directory.Delete(_param.path_to_save, true);
                            }
                            catch (Exception e)
                            {
                                Debug.LogWarning(e.Message);
                            }
                            ThreadFunc(_param);
                            return;
                        }
                        _Status = Status.OK;
                    }
                }
                else if (current_size == total_len)
                {//当前文件和 服务器文件大小一样 默认为 下载完成 需要校验MD5
                    try
                    {
                        file.Close();
                        file = null;
                        response.Close();
                        response = null;
                        request.Abort();
                        request = null;
                    }
                    catch (Exception e)
                    {
                    }
                    Debug.LogWarning("file is  req just done");
                    _Status = Status.Verifying;

                    var download_md5 = MD5Code.GetMD5HashFromFile(_param.path_to_save + "/" + _param.file_name);
                    if (string.IsNullOrEmpty(_param.md5) == false && _param.md5 == download_md5)
                    {
                        //ok
                    }
                    else
                    {
                        if (_param.md5 != null)
                        {
                            Debug.LogWarning("1excepted md5=" + _param.md5 + "  file=" + download_md5);
                        }
                        //md5 verify error 尝试重新下载
                        try
                        {
                            file.Close();
                            file = null;
                            response.Close();
                            response = null;
                            request.Abort();
                            request = null;
                        }
                        catch (Exception e)
                        {
                        }
                        try
                        {
                            Directory.Delete(_param.path_to_save, true);
                        }
                        catch (Exception e)
                        {
                            Debug.LogWarning(e.Message);
                        }
                        ThreadFunc(_param);
                        return;
                    }
                    _Status = Status.OK;
                }
                else
                {
                    //当前文件超过了 大小 需要重新下载
                    try
                    {
                        Directory.Delete(_param.path_to_save, true);
                    }
                    catch (Exception e)
                    {
                        Debug.LogWarning(e.Message);
                    }
                    Debug.LogWarning("file is bigger will delete and re-download  2");

                    try
                    {
                        file.Close();
                        file = null;
                        response.Close();
                        response = null;
                        request.Abort();
                        request = null;
                    }
                    catch (Exception e)
                    {
                    }

                    ThreadFunc(_param);
                    return;
                }
                //走到了这里 都当作文件下载成功 并且校验成功 可以开始安装了
                _Status = Status.OK;
                this.DownloadOK();
            }
            catch (Exception ee)
            {
                //整个下载流程出了异常错误
                Debug.LogWarning(ee.Message);
                _Status = Status.Checking;
                try
                {
                    if (file != null)
                    {
                        file.Close();
                        file = null;
                    }
                }
                catch (Exception e)
                {
                    Debug.LogWarning(e.Message);
                }
                try
                {
                    File.Delete(_param.path_to_save + "/" + _param.file_name);
                }
                catch (Exception e) { }
                ThreadFunc(_param);
                return;
            }
        }
    }