namespace ChatRoomServer.Www.Areas.Web.Controllers { using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web; using System.Web.Caching; using System.Web.Mvc; using ChatRoomServer.Www.Areas.Web.Models; using ChatRoomServer.Www.Models; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; [AllowAnonymous] public class Cn12306Controller : Controller { static string[] _invalidIpStart = new[] { "0.", "127.", "192." }; static bool _enabled = true; static bool IsValidIp(string ip) { if (ip.IsNullOrEmpty()) return false; if (_invalidIpStart.Any(s => ip.StartsWith(s))) return false; if (!System.Text.RegularExpressions.Regex.IsMatch(ip, @"^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$")) return false; return true; } public ActionResult IpService(string id) { var resultCacheKey1 = "cn12306servercache1"; var resultCacheKey2 = "cn12306servercache2"; if (id == "toggleenabled") { _enabled = !_enabled; return Json(new { success = _enabled, message = "ok" }, JsonRequestBehavior.AllowGet); } if (!_enabled) return Json(new { success = _enabled, message = "server maintenance" }, JsonRequestBehavior.AllowGet); if (id == "count") { return JsonCamel(new { Serve = MvcApplication.HostResolveCache.ServeCount, Update = MvcApplication.HostResolveCache.UpdateCount }); } if (id == "get") { var data = System.Web.HttpRuntime.Cache[resultCacheKey1] as string; if (data == null) { data = Newtonsoft.Json.JsonConvert.SerializeObject(MvcApplication.HostResolveCache.HostMap.GetValue("dynamic.12306.cn").Values.ToArray(), new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }); System.Web.HttpRuntime.Cache.Add(resultCacheKey1, data, null, System.Web.Caching.Cache.NoAbsoluteExpiration, new TimeSpan(0, 0, 20, 0), CacheItemPriority.Normal, null); } MvcApplication.HostResolveCache.ServeCount++; return Content(data, "application/json"); } if (id == "getall") { return Json2(new string[0]); } if (id == "getlist") { var data = System.Web.HttpRuntime.Cache[resultCacheKey2] as string; if (data == null) { data = Newtonsoft.Json.JsonConvert.SerializeObject(MvcApplication.HostResolveCache.HostMap.Values.SelectMany(s => s.Values).ToArray(), new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }); System.Web.HttpRuntime.Cache.Add(resultCacheKey2, data, null, System.Web.Caching.Cache.NoAbsoluteExpiration, new TimeSpan(0, 0, 20, 0), CacheItemPriority.Normal, null); } MvcApplication.HostResolveCache.ServeCount++; return Content(data, "application/json"); } if (id == "update") { var content = Request.Form["data"]; var report = Newtonsoft.Json.JsonConvert.DeserializeObject(content); var host = "dynamic.12306.cn"; var ips = MvcApplication.HostResolveCache.HostMap.GetValue(host, _ => new Dictionary()); report.ForEach(s => { if (!IsValidIp(s.Ip)) return; var ip = s.Ip; if (!ips.ContainsKey(ip) && s.AverageSpeed <= 0) return; var m = ips.GetValue(ip, _ => new HostResolve() { Ip = _, AddTime = DateTime.Now, Host = host }); if (s.AverageSpeed == -1) m.FailedCount++; else if (s.AverageSpeed == -2) m.BrokenCount++; else if (s.AverageSpeed > 0) { m.ValidCount++; if (s.AverageSpeed > 0) { m.AverageSpeed = (int)((m.AverageSpeed * 1.0 * m.SpeedCount + s.AverageSpeed) / (m.SpeedCount + 1)); m.SpeedCount++; } } var datacache = Newtonsoft.Json.JsonConvert.SerializeObject(ips.Values.ToArray(), new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }); System.Web.HttpRuntime.Cache.Add(resultCacheKey1, datacache, null, System.Web.Caching.Cache.NoAbsoluteExpiration, new TimeSpan(0, 0, 20, 0), CacheItemPriority.Normal, null); }); MvcApplication.HostResolveCache.UpdateCount++; return Content("update success, thanks."); } if (id == "update2") { var keyes = new[] { "dynamic.12306.cn", "kyfw.12306.cn"//, //"www.12306.cn" }; foreach (var host in keyes) { var data = Request.Form[host]; if (data.IsNullOrEmpty()) continue; var report = Newtonsoft.Json.JsonConvert.DeserializeObject(data); if (report == null) continue; var ips = MvcApplication.HostResolveCache.HostMap.GetValue(host, h => new Dictionary()); foreach (var s in report) { if (!IsValidIp(s.Ip)) continue; var ip = s.Ip; if (!ips.ContainsKey(ip) && s.AverageSpeed <= 0) continue; var m = ips.GetValue(ip, _ => new HostResolve() { Ip = _, AddTime = DateTime.Now, Host = host }); if (s.AverageSpeed == -1) m.FailedCount++; else if (s.AverageSpeed == -2) m.BrokenCount++; else if (s.AverageSpeed > 0) { m.ValidCount++; if (s.AverageSpeed > 0) { m.AverageSpeed = (int)((m.AverageSpeed * 1.0 * m.SpeedCount + s.AverageSpeed) / (m.SpeedCount + 1)); m.SpeedCount++; } } } } System.Web.HttpRuntime.Cache.Remove(resultCacheKey2); MvcApplication.HostResolveCache.UpdateCount++; return Content("succeed."); } //if (id == "log") //{ // var ctx = new DbContext(); // var keyes = new[] { "dynamic.12306.cn", "kyfw.12306.cn", "www.12306.cn" }; // foreach (var key in keyes) // { // var ip = Request.Form[key]; // if (!IsValidIp(ip)) // continue; // if (ctx.HostResolve.Any(s => s.Host == key && s.Ip == ip)) // continue; // ctx.HostResolve.Add(new HostResolve() // { // Host = key, // Ip = ip, // AddTime = DateTime.Now // }); // } // ctx.SaveChanges(); // return Content("update success, thanks."); //} if (id == "refreshcache") { var target = new[] { resultCacheKey1, resultCacheKey2 }; foreach (var key in target) { try { HttpRuntime.Cache.Remove(key); } catch (Exception) { } } } if (id == "raw") { return Json(MvcApplication.HostResolveCache); } return null; } /// /// 生成并返回一个Json结果 /// /// 数据 /// 结果类型 /// JSONP回调函数名 /// 内容编码 /// 返回一个ActionResult结果 protected ActionResult Json2(object data, string contentType = null, string jsCallback = null, Encoding encoding = null) { return new Json2Result { ContentEncoding = encoding, ContentType = contentType, Data = data, CallbackJsFunction = jsCallback }; } /// /// 生成并返回一个Json结果 /// /// 数据 /// 结果类型 /// JSONP回调函数名 /// 内容编码 /// 返回一个ActionResult结果 protected ActionResult JsonCamel(object data, string contentType = null, string jsCallback = null, Encoding encoding = null, bool indent = false) { return new Json2Result { ContentEncoding = encoding, ContentType = contentType, Data = data, CallbackJsFunction = jsCallback, Indent = indent, UseCamelName = true }; } } }