private async Task OnResponse(object arg1, Titanium.Web.Proxy.EventArguments.SessionEventArgs e) { Console.WriteLine(e.WebSession.Request.Url + " RES"); if (e.WebSession.Request.Method == "GET" || e.WebSession.Request.Method == "POST") { if (e.WebSession.Response.ResponseStatusCode == "200") { if (e.WebSession.Response.ContentType != null && e.WebSession.Response.ContentType.Trim().ToLower().Contains("text/html")) { /*byte[] bodyBytes = await e.GetResponseBody(); * await e.SetResponseBody(bodyBytes);*/ string body = await e.GetResponseBodyAsString(); await e.SetResponseBodyString(body + "<style>body { margin: 0 auto !important;-moz - transform: scaleX(-1) !important;-o - transform: scaleX(-1) !important;-webkit - transform: scaleX(-1);transform: scaleX(-1);filter: FlipH;" + "-ms - filter: \"FlipH\" !important;}</style>"); } if (e.WebSession.Response.ContentType != null && e.WebSession.Response.ContentType.Trim().ToLower().Contains("image")) { await e.SetResponseBody(new byte[] { }); } } } }
private void ProxyServer_BeforeRequest(object sender, Titanium.Web.Proxy.EventArguments.SessionEventArgs e) { var request = e.ProxySession.Request; string path = request.RequestUri.PathAndQuery; Utility.Configuration.ConfigurationData.ConfigConnection c = Utility.Configuration.Config.Connection; if (path.Contains("/kcsapi/")) { string body = e.GetRequestBodyAsString(); //保存 if (c.SaveReceivedData && c.SaveRequest) { Task.Run((Action)(() => { SaveRequest(path, body); })); } UIControl.BeginInvoke((Action)(() => { LoadRequest(path, body); })); } if (path.Contains(".mp3")) { Logger.Add(1, $"Requesting audio: {path}"); string[] substrings = path.Split('/'); switch (substrings[3]) { case "titlecall": DialogueTranslator.Add(DialogueType.Titlecall, substrings[4], substrings[5].Split('.')[0]); break; case "kc9999": DialogueTranslator.Add(DialogueType.NPC, "npc", substrings[4].Split('.')[0]); break; default: DialogueTranslator.Add(DialogueType.Shipgirl, substrings[3].Substring(2), substrings[4].Split('.')[0]); break; } if (request.RequestHeaders.Where(h => h.Name == "If-Modified-Since").Count() > 0) { if (cacheControl.ContainsKey(path)) { if (cacheControl[path].Item2 < DateTime.Now) { return; } else { e.NotModified(cacheControl[path].Item1); } } } } }
private void PostToServer(Titanium.Web.Proxy.EventArguments.SessionEventArgs e) { string oauth = OAuth; string url = e.ProxySession.Request.RequestUri.PathAndQuery; string request = e.GetRequestBodyAsString(); string response = e.GetResponseBodyAsString(); request = RequestRegex.Replace(request, ""); try { //* using (System.Net.WebClient wc = new System.Net.WebClient()) { wc.Headers["User-Agent"] = "ElectronicObserver/v" + SoftwareInformation.VersionEnglish; if (Proxy != null) { wc.Proxy = Proxy; } System.Collections.Specialized.NameValueCollection post = new System.Collections.Specialized.NameValueCollection(); post.Add("token", oauth); // agent key for 'ElectronicObserver' // https://github.com/about518/kanColleDbPost/issues/3#issuecomment-105534030 post.Add("agent", "L57Mi4hJeCYinbbBSH5K"); post.Add("url", url); post.Add("requestbody", request); post.Add("responsebody", response); wc.UploadValuesCompleted += (sender, ev) => { if (ev.Error != null) { // 結構頻繁に出るのでレポートは残さない方針で 申し訳ないです //Utility.ErrorReporter.SendErrorReport( e.Error, string.Format( "艦これ統計データベースへの {0} の送信に失敗しました。", url.Substring( url.IndexOf( "/api" ) + 1 ) ) ); Utility.Logger.Add(3, string.Format(LoggerRes.FailedDatabaseSend, url.Substring(url.IndexOf("/api") + 1), ev.Error.Message)); } else { Utility.Logger.Add(1, string.Format(LoggerRes.SentDatabase, url.Substring(url.IndexOf("/api") + 1))); } }; wc.UploadValuesAsync(new Uri("http://api.kancolle-db.net/2/"), post); } //*/ } catch (Exception ex) { Utility.ErrorReporter.SendErrorReport(ex, LoggerRes.ErrorDatabaseSending); } }
/// <summary> /// read the after-session, determinate whether it will send to kancolle-db.net /// </summary> public void ExecuteSession(Titanium.Web.Proxy.EventArguments.SessionEventArgs e) { if (string.IsNullOrEmpty(OAuth)) { return; } // find the url in dict. string url = e.ProxySession.Request.RequestUri.PathAndQuery; if (apis.Contains(url)) { PostToServer(e); } }
private void ProxyServer_BeforeResponse(object sender, Titanium.Web.Proxy.EventArguments.SessionEventArgs e) { string path = e.ProxySession.Request.RequestUri.PathAndQuery; if (path.Contains(".mp3")) { var cacheControlHeader = e.ProxySession.Response.ResponseHeaders.Where(h => h.Name == "Cache-Control").First(); var lastModifiedHeader = e.ProxySession.Response.ResponseHeaders.Where(h => h.Name == "Last-Modified").First(); Regex re = new Regex("([0-9]+)"); var match = re.Match(cacheControlHeader.Value); if (!string.IsNullOrWhiteSpace(match.Value)) { int seconds = int.Parse(match.Value); cacheControl.Add(path, new Tuple <DateTime, DateTime>(DateTime.Parse(lastModifiedHeader.Value), DateTime.Now.AddSeconds(seconds))); } cacheControlHeader.Value = "public, no-cache, max-age=0"; } }
private async Task OnRequest(object arg1, Titanium.Web.Proxy.EventArguments.SessionEventArgs e) { Console.WriteLine(e.WebSession.Request.Url + " REQ"); ////read request headers var requestHeaders = e.WebSession.Request.RequestHeaders; var method = e.WebSession.Request.Method.ToUpper(); if ((method == "POST" || method == "PUT" || method == "PATCH")) { //Get/Set request body bytes byte[] bodyBytes = await e.GetRequestBody(); await e.SetRequestBody(bodyBytes); //Get/Set request body as string /* * string bodyString = await e.GetRequestBodyAsString(); * await e.SetRequestBodyString(bodyString);*/ } //To cancel a request with a custom HTML content //Filter URL if (e.WebSession.Request.RequestUri.AbsoluteUri.Contains("tenrys.isgay")) { await e.Ok("<!DOCTYPE html>" + "<html><body><h1>" + "XAOTI CMAKES MEMES XDDD" + "</h1>" + "<p>FUCCC.</p>" + "</body>" + "</html>"); } //Redirect example if (e.WebSession.Request.RequestUri.AbsoluteUri.Contains("wikipedia.org")) { await e.Redirect("https://www.paypal.com"); } }
private void ProxyServer_BeforeRequest(object sender, Titanium.Web.Proxy.EventArguments.SessionEventArgs e) { var request = e.ProxySession.Request; string path = request.RequestUri.PathAndQuery; if (path.Contains(".mp3")) { string[] substrings = path.Split('/'); switch (substrings[3]) { case "titlecall": ToolViewModel.UpdateText(DialogueTranslator.Add(DialogueType.Titlecall, substrings[4], substrings[5].Split('.')[0])); break; case "kc9999": ToolViewModel.UpdateText(DialogueTranslator.Add(DialogueType.NPC, "npc", substrings[4].Split('.')[0])); break; default: ToolViewModel.UpdateText(DialogueTranslator.Add(DialogueType.Shipgirl, substrings[3].Substring(2), substrings[4].Split('.')[0])); break; } if (request.RequestHeaders.Where(h => h.Name == "If-Modified-Since").Count() > 0) { if (cacheControl.ContainsKey(path)) { if (cacheControl[path].Item2 < DateTime.Now) { return; } else { e.NotModified(cacheControl[path].Item1); } } } } }
private async Task Proxyserver_BeforeResponse(object sender, Titanium.Web.Proxy.EventArguments.SessionEventArgs e) { string reqeustURL = e.HttpClient.Request.Url; if (reqeustURL.Contains("filelist.xml")) { string basefirm = textBox1.Text, custfirm = textBox7.Text, preloadfirm = textBox4.Text; basefirm = basefirm.Substring(basefirm.IndexOf("TDS")); custfirm = custfirm.Substring(custfirm.IndexOf("TDS")); preloadfirm = preloadfirm.Substring(preloadfirm.IndexOf("TDS")); string tempurl = reqeustURL.Substring(reqeustURL.IndexOf("TDS")); if (_customData.LocalBase && tempurl.Contains(basefirm)) { string response = await e.GetResponseBodyAsString(); int where = response.IndexOf("package="); if (where == -1) { MessageBox.Show("Couldn't load base package name, please contact developer if error continues", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error); } else { where += 9; int finish = response.IndexOf('"', where); CopyFile(textBox2.Text, _customData.LocalBaseDir, response.Substring(where, finish - where), 0); } } else if (_customData.LocalCust && tempurl.Contains(custfirm)) { string response = await e.GetResponseBodyAsString(); int where = response.IndexOf("package="); if (where == -1) { MessageBox.Show("Couldn't load cust package name, please contact developer if error continues", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error); } else { where += 9; int finish = response.IndexOf('"', where); CopyFile(textBox6.Text, _customData.LocalCustDir, response.Substring(where, finish - where), 1); } } else if (_customData.LocalPreload && tempurl.Contains(preloadfirm)) { string response = await e.GetResponseBodyAsString(); int where = response.IndexOf("package="); if (where == -1) { MessageBox.Show("Couldn't load preload package name, please contact developer if error continues", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error); } else { where += 9; int finish = response.IndexOf('"', where); CopyFile(textBox5.Text, _customData.LocalPreloadDir, response.Substring(where, finish - where), 2); } } } }
private async Task Proxyserver_BeforeRequest(object sender, Titanium.Web.Proxy.EventArguments.SessionEventArgs e) { try { string reqeustURL = e.HttpClient.Request.Url; if (reqeustURL.Contains("query.hicloud.com") || reqeustURL.Contains("/TDS/data/files")) { this.Invoke(new Action(() => { textBox3.AppendText(e.HttpClient.Request.Url + Environment.NewLine); })); if (checkBox2.Checked) { string debug = e.HttpClient.Request.Url + " : " + Environment.NewLine; List <HttpHeader> clientheaders = e.HttpClient.Request.Headers.GetAllHeaders(); for (int i = 0, j = clientheaders.Count; i < j; i++) { debug += clientheaders[i].Name + ": " + clientheaders[i].Value + Environment.NewLine; } if (e.HttpClient.Request.HasBody) { debug += Environment.NewLine + await e.GetRequestBodyAsString(); } debug += Environment.NewLine + Environment.NewLine; File.AppendAllText("logs.txt", debug); } } if (reqeustURL.Contains("query.hicloud.com")) { if (reqeustURL.Contains("CheckNewVersion.aspx")) { Dictionary <string, HttpHeader> Headers = new Dictionary <string, HttpHeader>(); Headers.Add("Content-Type", new HttpHeader("Content-Type", "application/xml;charset=UTF-8")); e.Ok("<?xml version=\"1.0\" encoding=\"UTF-8\"?><root><status>1</status></root>", Headers, true); } else if (reqeustURL.Contains("CouplingReport.action")) { string resbody = await e.GetRequestBodyAsString(); int where = resbody.IndexOf("descinfo"); if (where != -1) { where += 13; int finish = resbody.IndexOf("\",", where); new Thread(() => { MessageBox.Show(resbody.Substring(where, finish - where), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); }).Start(); } } else if (reqeustURL.Contains("authorize.action")) { WebClient client = new WebClient(); client.Headers.Set(HttpRequestHeader.Accept, "*/*"); client.Headers.Set(HttpRequestHeader.ContentType, "application/json;charset=UTF-8"); string updata = await e.GetRequestBodyAsString(); string respons = client.UploadString("https://query.hicloud.com:443/sp_ard_common/v1/authorize.action", updata); Dictionary <string, HttpHeader> Headers = new Dictionary <string, HttpHeader>(); Headers.Add("Date", new HttpHeader("Date", client.ResponseHeaders[HttpResponseHeader.Date])); Headers.Add("Content-Type", new HttpHeader("Content-Type", "text/plain;charset=UTF-8")); Headers.Add("Server", new HttpHeader("Server", "elb")); Headers.Add("X-XSS-Protection", new HttpHeader("X-XSS-Protection", "1; mode=block")); Headers.Add("X-frame-options", new HttpHeader("X-frame-options", "SAMEORIGIN")); Headers.Add("X-Content-Type-Options", new HttpHeader("X-Content-Type-Options", "nosniff")); string manipulatedresponse = ManipulateData(respons); e.Ok(manipulatedresponse, Headers); } else if (e.HttpClient.Request.HasBody) { string bodydata = await e.GetRequestBodyAsString(); int whereisit = bodydata.IndexOf("PackageType"); if (whereisit != -1) { whereisit += 16; int finish = bodydata.IndexOf('"', whereisit); string pacakgetype = bodydata.Substring(whereisit, finish - whereisit); string opscheck = "full"; if (radioButton2.Checked) { opscheck = "hfull_switch"; } else if (radioButton3.Checked) { opscheck = "full_back"; } else if (radioButton4.Checked) { opscheck = "full_recovery"; } if (pacakgetype == opscheck) { string responsedata = Encoding.UTF8.GetString(Properties.Resources.responsedata).Replace("\r\n", ""); bool Iveabase = (GetURLVersion(textBox1.Text) != "Unknown"); if (Iveabase) { responsedata = responsedata.Replace("hasfullpackage", "0"); if (_customData.CustomBase) { responsedata = responsedata.Replace("WriteVerionID", _customData.CustomBaseID); } else { responsedata = responsedata.Replace("WriteVerionID", GetURLVersion(textBox1.Text)); } if (checkBox4.Checked) { responsedata = responsedata.Replace("pointbase", "1"); } else { responsedata = responsedata.Replace("pointbase", "0"); } responsedata = responsedata.Replace("basetype", textBox8.Text); responsedata = responsedata.Replace("VersionURL", textBox1.Text); responsedata = responsedata.Replace("Unknown1", textBox2.Text); } else { responsedata = responsedata.Replace("hasfullpackage", "1"); } if (checkBox1.Checked) { if (_customData.CustomPreload) { responsedata = responsedata.Replace("WiteVerionID", _customData.CustomPreloadID); } else { responsedata = responsedata.Replace("WiteVerionID", GetURLVersion(textBox4.Text)); } if (checkBox6.Checked) { if (Iveabase) { responsedata = responsedata.Replace("pointpreload", "2"); } else { responsedata = responsedata.Replace("pointpreload", "1"); } } else { responsedata = responsedata.Replace("pointpreload", "0"); } responsedata = responsedata.Replace("VrsionURL", textBox4.Text); responsedata = responsedata.Replace("Unknown2", textBox5.Text); responsedata = responsedata.Replace("hasreloadedpackage", "0"); } else { responsedata = responsedata.Replace("hasreloadedpackage", "1"); } if (checkBox3.Checked) { if (_customData.CustomCust) { responsedata = responsedata.Replace("WteVerionID", _customData.CustomCustID); } else { responsedata = responsedata.Replace("WteVerionID", GetURLVersion(textBox7.Text)); } if (checkBox5.Checked) { if (Iveabase) { responsedata = responsedata.Replace("pointcust", "2"); } else { responsedata = responsedata.Replace("pointcust", "1"); } } else { responsedata = responsedata.Replace("pointcust", "0"); } responsedata = responsedata.Replace("VrionURL", textBox7.Text); responsedata = responsedata.Replace("Unknown3", textBox6.Text); responsedata = responsedata.Replace("hascustpackage", "0"); } else { responsedata = responsedata.Replace("hascustpackage", "1"); } Dictionary <string, HttpHeader> Headers = new Dictionary <string, HttpHeader>(); Headers.Add("Content-Type", new HttpHeader("Content-Type", "application/json;charset=utf8")); e.Ok(responsedata, Headers, true); } else { string responsedata = Encoding.UTF8.GetString(Properties.Resources.emptyresponse).Replace("\r\n", ""); Dictionary <string, HttpHeader> Headers = new Dictionary <string, HttpHeader>(); Headers.Add("Content-Type", new HttpHeader("Content-Type", "application/json;charset=utf8")); e.Ok(responsedata, Headers, true); } } } } } catch (Exception ex) { this.Invoke(new Action(() => { textBox3.AppendText(ex.StackTrace + Environment.NewLine); })); MessageBox.Show(ex.Message, "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
private void ProxyServer_BeforeResponse(object sender, Titanium.Web.Proxy.EventArguments.SessionEventArgs e) { Utility.Configuration.ConfigurationData.ConfigConnection c = Utility.Configuration.Config.Connection; string path = e.ProxySession.Request.RequestUri.PathAndQuery; if (path.Contains(".mp3")) { var cacheControlHeader = e.ProxySession.Response.ResponseHeaders.Where(h => h.Name == "Cache-Control").First(); var lastModifiedHeader = e.ProxySession.Response.ResponseHeaders.Where(h => h.Name == "Last-Modified").First(); Regex re = new Regex("([0-9]+)"); var match = re.Match(cacheControlHeader.Value); if (!string.IsNullOrWhiteSpace(match.Value)) { int seconds = int.Parse(match.Value); cacheControl.Add(path, new Tuple <DateTime, DateTime>(DateTime.Parse(lastModifiedHeader.Value), DateTime.Now.AddSeconds(seconds))); } cacheControlHeader.Value = "public, no-cache, max-age=0"; } if (c.SaveReceivedData) { try { if (!Directory.Exists(c.SaveDataPath)) { Directory.CreateDirectory(c.SaveDataPath); } if (c.SaveResponse && path.Contains("/kcsapi/")) { // 非同期で書き出し処理するので取っておく // stringはイミュータブルなのでOK string body = e.GetResponseBodyAsString(); Task.Run((Action)(() => { SaveResponse(path, body); })); } else if (path.Contains("/kcs/") && ((c.SaveSWF && e.ResponseContentType == "application/x-shockwave-flash") || c.SaveOtherFile)) { string saveDataPath = c.SaveDataPath; // スレッド間の競合を避けるため取っておく string tpath = string.Format("{0}\\{1}", saveDataPath, path.Substring(path.IndexOf("/kcs/") + 5).Replace("/", "\\")); { int index = tpath.IndexOf("?"); if (index != -1) { if (Utility.Configuration.Config.Connection.ApplyVersion) { string over = tpath.Substring(index + 1); int vindex = over.LastIndexOf("VERSION=", StringComparison.CurrentCultureIgnoreCase); if (vindex != -1) { string version = over.Substring(vindex + 8).Replace('.', '_'); tpath = tpath.Insert(tpath.LastIndexOf('.', index), "_v" + version); index += version.Length + 2; } } tpath = tpath.Remove(index); } } // 非同期で書き出し処理するので取っておく byte[] responseCopy = e.GetResponseBody(); Task.Run((Action)(() => { try { lock (this) { // 同時に書き込みが走るとアレなのでロックしておく Directory.CreateDirectory(Path.GetDirectoryName(tpath)); //System.Diagnostics.Debug.WriteLine( oSession.fullUrl + " => " + tpath ); using (var sw = new System.IO.BinaryWriter(System.IO.File.OpenWrite(tpath))) { sw.Write(responseCopy); } } Utility.Logger.Add(1, string.Format(LoggerRes.SavedAPI, tpath.Remove(0, saveDataPath.Length + 1))); } catch (IOException ex) { //ファイルがロックされている; 頻繁に出るのでエラーレポートを残さない Utility.Logger.Add(3, LoggerRes.FailedSaveAPI + ex.Message); } })); } } catch (Exception ex) { Utility.ErrorReporter.SendErrorReport(ex, LoggerRes.FailedSaveAPI); } } if (path.Contains("/kcsapi/") && e.ResponseContentType == "text/plain") { // 非同期でGUIスレッドに渡すので取っておく // stringはイミュータブルなのでOK string body = e.GetResponseBodyAsString(); UIControl.BeginInvoke((Action)(() => { LoadResponse(path, body); })); // kancolle-db.netに送信する if (Utility.Configuration.Config.Connection.SendDataToKancolleDB) { Task.Run((Action)(() => DBSender.ExecuteSession(e))); } } if (ServerAddress == null && path.Contains("/kcsapi/")) { ServerAddress = e.ProxySession.Request.RequestUri.Host; } }