static void _AfterComplete(Session oSession)
        {
            if (!Settings.Current.CacheEnabled) return;
            if (!_Filter(oSession)) return;

            //服务器返回200,下载新的文件
            if (oSession.responseCode == 200)
            {
                string filepath = TaskRecord.GetAndRemove(oSession.fullUrl);

                //只有TaskRecord中有记录的文件才是验证的文件,才需要保存
                if (!string.IsNullOrEmpty(filepath))
                {
                    if (File.Exists(filepath))
                        File.Delete(filepath);

                    //保存下载文件并记录Modified-Time
                    try
                    {
                        oSession.SaveResponseBody(filepath);
                        //cache.RecordNewModifiedTime(oSession.fullUrl,
                        //	oSession.oResponse.headers["Last-Modified"]);
                        _SaveModifiedTime(filepath, oSession.oResponse.headers["Last-Modified"]);
                        //Debug.WriteLine("CACHR> 【下载文件】" + oSession.PathAndQuery);
                    }
                    catch (Exception ex)
                    {
                        Log.Exception(oSession, ex, "会话结束时,保存返回文件时发生异常");
                    }
                }
            }
        }
Example #2
0
 private void FiddlerApplication_BeforeResponse(Fiddler.Session oS)
 {
     if (oS.oFlags.ContainsKey("dax_id"))
     {
         oS.utilDecodeResponse();
         oS.SaveResponseBody(Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), "DaXCaps", oS.oFlags["dax_id"] + "_DaX_" + oS.RequestHeaders["Range"].Substring("bytes=".Length) + "_XaD_" + oS.SuggestedFilename));
         oS.ResponseBody = null;
         GC.Collect();
     }
 }
Example #3
0
        public bool OnResponse(Session session, Rule rule)
        {
            Uri uriOut;
            if (Uri.TryCreate(session.fullUrl, UriKind.RelativeOrAbsolute, out uriOut))
            {
                if (uriOut.HasFileExtension(this.Extensions))
                {
                    // TODO: Config this directory
                    var directory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), @"\Downloads\");
                    if (!Directory.Exists(directory))
                    {
                        Directory.CreateDirectory(directory);
                    }

                    session.SaveResponseBody(Path.Combine(directory, session.SuggestedFilename));
                }
            }

            return true;
        }
        internal void ProcessOnCompletion(ResourceSession rpResourceSession, Session rpSession)
        {
            if (rpSession.responseCode != 200 || rpResourceSession.State == NetworkSessionState.LoadedFromCache || rpResourceSession.CacheFilename == null ||
                Convert.ToInt32(rpSession.ResponseHeaders["Content-Length"]) != rpSession.ResponseBody.Length)
                return;

            try
            {
                lock (r_ThreadSyncObject)
                {
                    var rLastModified = rpSession.oResponse["Last-Modified"];
                    if (rLastModified.IsNullOrEmpty())
                        return;

                    var rDirectoryName = Path.GetDirectoryName(rpResourceSession.CacheFilename);
                    if (!Directory.Exists(rDirectoryName))
                        Directory.CreateDirectory(rDirectoryName);

                    var rFile = new FileInfo(rpResourceSession.CacheFilename);
                    if (rFile.Exists)
                        rFile.Delete();

                    rpSession.SaveResponseBody(rFile.FullName);

                    var rTimestamp = Convert.ToDateTime(rLastModified);
                    rFile.LastWriteTime = rTimestamp;

                    rpResourceSession.State = NetworkSessionState.Cached;

                    RecordCachedFile(rpResourceSession, rTimestamp, true);
                }
            }
            catch (Exception e)
            {
                Logger.Write(LoggingLevel.Error, string.Format(StringResources.Instance.Main.Log_Exception_Cache_FailedToSaveFile, e.Message));
            }
        }
        internal void ProcessOnCompletion(ResourceSession rpResourceSession, Session rpSession)
        {
            if (rpSession.responseCode != 200 || rpResourceSession.CacheFilename == null)
                return;

            try
            {
                var rDirectoryName = Path.GetDirectoryName(rpResourceSession.CacheFilename);
                if (!Directory.Exists(rDirectoryName))
                    Directory.CreateDirectory(rDirectoryName);

                var rFile = new FileInfo(rpResourceSession.CacheFilename);
                if (rFile.Exists)
                    rFile.Delete();

                rpSession.SaveResponseBody(rFile.FullName);
                rFile.LastWriteTime = Convert.ToDateTime(rpSession.oResponse["Last-Modified"]);

                rpResourceSession.State = NetworkSessionState.Cached;
            }
            catch (Exception e)
            {
                Logger.Write(LoggingLevel.Error, string.Format(StringResources.Instance.Main.Log_Exception_Cache_FailedToSaveFile, e.Message));
            }
        }
Example #6
0
        private void FiddlerApplicationOnBeforeResponse(Session oSession)
        {
            var name = oSession.id.ToString();
            name = name.PadLeft(5, '0');

            // Handle Wimp Normal and High
            if (oSession.host.Contains("wimpmusic.com") && oSession.oResponse.headers.ExistsAndContains("Content-Type", "audio/mp4"))
            {
                SetStatusLabel("Downloading AAC...");
                oSession.SaveResponseBody(TargetDirectory + name + ".m4a");
                SetProgress(0);
                SetStatusLabel("Download completed...");

                if (Autoskip.Checked)
                {
                    System.Diagnostics.Process process = new System.Diagnostics.Process();
                    process.StartInfo.FileName = @"C:\Program Files (x86)\Wimp\wimp.exe";
                    process.StartInfo.Arguments = "next";
                    process.StartInfo.UseShellExecute = false;
                    process.StartInfo.CreateNoWindow = true;
                    process.StartInfo.RedirectStandardError = true;
                    process.StartInfo.RedirectStandardOutput = true;
                    process.Start();
                }
            }

            // Handle Wimp HiFi
            if (oSession.host.Contains("wimpmusic.com") && oSession.oResponse.headers.ExistsAndContains("Content-Type", "audio/flac") && oSession.oResponse.headers.Exists("Content-Range"))
            {
                //bytes 204801-614401/44464923
                var range = oSession.oResponse.headers.First(x => x.Name == "Content-Range").Value;
                var rangeStr = range.Split('-').Last().Split('/');
                var offset = int.Parse(range.Split(' ')[1].Split('-')[0]);
                var chunkEnd = int.Parse(rangeStr[0]);
                var totalSize = int.Parse(rangeStr[1]);

                // If its a first package. Prepare memory stream.
                if (offset == 0)
                {
                    SetStatusLabel("Downloading FLAC...");
                    SetProgress(0);
                    FlacBuffer = new MemoryStream(new byte[totalSize]);
                    FlacWriter = new BinaryWriter(FlacBuffer);
                }

                // Add chunk to memorystream. Do nothing if we dont have a stream initialized.
                if (FlacBuffer != null)
                {
                    SetProgress((int)Math.Floor((double)chunkEnd / (double)totalSize * 100.0));
                    FlacWriter.Write(oSession.responseBodyBytes);
                }

                // When download is complete; dump memory stream to file.
                if (FlacBuffer != null && chunkEnd == (totalSize - 1))
                {
                    FlacWriter.Flush();
                    FlacBuffer.Flush();

                    if (!Directory.Exists(TargetDirectory))
                    {
                        Directory.CreateDirectory(TargetDirectory);
                    }

                    using (FileStream file = new FileStream(TargetDirectory + name + ".flac", FileMode.Create, System.IO.FileAccess.Write))
                    {
                        byte[] bytes = FlacBuffer.ToArray();
                        file.Write(bytes, 0, bytes.Length);
                    }

                    SetProgress(0);
                    SetStatusLabel("Download completed...");

                    if (Autoskip.Checked)
                    {
                        System.Diagnostics.Process process = new System.Diagnostics.Process();
                        process.StartInfo.FileName = @"C:\Program Files (x86)\Wimp\wimp.exe";
                        process.StartInfo.Arguments = "next";
                        process.StartInfo.UseShellExecute = false;
                        process.StartInfo.CreateNoWindow = true;
                        process.StartInfo.RedirectStandardError = true;
                        process.StartInfo.RedirectStandardOutput = true;
                        process.Start();
                    }
                }
            }
        }
Example #7
0
        private void FiddlerApplication_BeforeResponse(Session oSession) {

            if (oSession.PathAndQuery.StartsWith("/kcs/")) {
                string filePath = Utility.Config.Instance.CacheFolder + oSession.getFilePath();

                if (oSession.responseCode == 304) {

                    // code 304, 文件沒有修改, 使用本地文件
                    if (!string.IsNullOrEmpty(filePath) && File.Exists(filePath)) {

                        oSession.bBufferResponse = true;
                        oSession.ResponseBody = File.ReadAllBytes(filePath);
                        oSession.oResponse.headers.HTTPResponseCode = 200;
                        oSession.oResponse.headers.HTTPResponseStatus = "200 OK";
                        oSession.oResponse.headers["Last-Modified"] = oSession.oRequest.headers["If-Modified-Since"];
                        oSession.oResponse.headers["Accept-Ranges"] = "bytes";
                        oSession.oResponse.headers.Remove("If-Modified-Since");
                        oSession.oRequest.headers.Remove("If-Modified-Since");
                        if (filePath.EndsWith(".swf"))
                            oSession.oResponse.headers["Content-Type"] = "application/x-shockwave-flash";

                        Utility.Logger.Add("Response > [304, 返回本地]" + filePath);
                    }
                } else if (oSession.responseCode == 200) {

                    // code 200, 更新緩存紀錄 
                    Cache.UpdataCache(oSession.PathAndQuery);

                    if (File.Exists(filePath)) {
                        string resBody = oSession.GetResponseBodyAsString();
                        string cacheBody = File.ReadAllText(filePath);

                        // 比對緩存 
                        if (resBody.Equals(cacheBody)) {

                            Utility.Logger.Add("Response > [200, 檔案相同]" + filePath);
                        } else {

                            if (Utility.Config.Instance.AutoBackupCache) {
                                // 保存舊緩存 
                                int index = filePath.LastIndexOf('.');
                                if (index > 0) {
                                    string iPath = filePath.Substring(0, index);
                                    string iType = filePath.Substring(index);   // .swf

                                    DateTime dateNow = DateTime.Now;
                                    string dateTime = (dateNow.Year % 100).ToString() + dateNow.Month.ToString("00") + dateNow.Day.ToString("00");
                                    string newFilePath = iPath + "_" + dateTime + iType;

                                    File.Move(filePath, newFilePath);
                                }
                            }
                            
                        try {
                            oSession.SaveResponseBody(filePath);
                        } catch (Exception ex) {
                            DateTime dateNow = DateTime.Now;
                            string dateTime = dateNow.Year.ToString() + dateNow.Month.ToString("00") + dateNow.Day.ToString("00") + "_" +
                                dateNow.Hour.ToString("00") + dateNow.Minute.ToString("00") + dateNow.Second.ToString("00");

                            Utility.Logger.CmdLog("dateTime: ");
                            Utility.Logger.CmdLog(ex.ToString());
                        }

                            Utility.Logger.Add("Response > [200, 更新緩存]" + filePath);
                        }
                        // code 200, 更新時間 
                        GMTHelper._SaveModifiedTime(filePath, oSession.oResponse.headers["Last-Modified"]);

                    } else {
                        // 儲存快取並設置時間 
                        try {
                            oSession.SaveResponseBody(filePath);
                        } catch (Exception ex) {
                            DateTime dateNow = DateTime.Now;
                            string dateTime = dateNow.Year.ToString() + dateNow.Month.ToString("00") + dateNow.Day.ToString("00") + "_" +
                                dateNow.Hour.ToString("00") + dateNow.Minute.ToString("00") + dateNow.Second.ToString("00");

                            Utility.Logger.CmdLog("dateTime: ");
                            Utility.Logger.CmdLog(ex.ToString());
                        }
                        GMTHelper._SaveModifiedTime(filePath, oSession.oResponse.headers["Last-Modified"]);
                        Utility.Logger.Add("Response > [200, 建立緩存]" + filePath);
                    }
                }

                // 魔改 
                if (filePath.Contains(@"kcs\resources\swf\ships\")) {

                    string fileName = filePath.getFileName();
                    if (CosManager.Instance.IsPaired(fileName)) {
                        Utility.Logger.Add("IsPaired > " + fileName);
                        //filePath = filePath.Replace(fileName, CosManager.Instance.GetPair(fileName));
                        filePath = Utility.Config.Instance.CostumeFolder + @"\" + CosManager.Instance.GetPair(fileName) + ".swf";
                        oSession.ResponseBody = File.ReadAllBytes(filePath);
                    }
                }


            } else if (oSession.PathAndQuery.StartsWith("/kcsapi/")) {

                string url = oSession.PathAndQuery;
                string body = oSession.GetResponseBodyAsString();

                Utility.Logger.Add("Response > " + url);

                try {
                    // 非同期で書き出し処理するので取っておく
                    // stringはイミュータブルなのでOK
                    Task.Run((Action)(() => { SaveResponse(url, body); }));
                } catch (Exception ex) {
                    Utility.ErrorReporter.SendErrorReport(ex, "通信内容保存失败。");
                }

                // api修改 
                if (oSession.bBufferResponse) {
                    Utility.Logger.Add("Response > LoadDynamicJson( " + url + " )");
                    string newbody = LoadDynamicJson(url, body);
                    if (newbody != null) {
                            oSession.utilSetResponseBody(newbody);
                    }
                }

            }
        }