public async Task <dynamic> Handle(dynamic session, dynamic message) { if (message.head.what == "helper-create-guid") { int count = int.Parse(message.body.count.ToString()); var ans = Helper.BuildMessage("helper-guid"); ans.body.guids = new List <Guid>(); for (int i = 0; i < count; i++) { ans.body.guids.Add(Guid.NewGuid()); } return(ans); } if (message.head.what == "helper-create-md5") { string text = message.body.text; var ans = Helper.BuildMessage("helper-create-md5"); ans.body.md5 = AuthHandler.GetHashString(text); return(ans); } var nullAns = Helper.BuildMessage("helper-undefined"); return(nullAns); }
public async Task <dynamic> Handle(dynamic session, dynamic message) { string what = message.head.what; if (what == "task-list") { var objs = StructureGraph.Instance.GetTasks(Guid.Parse(session.user.id)); var ans = Helper.BuildMessage(what); ans.body.objs = objs; return(ans); } if (what == "task-get") { var id = Guid.Parse((string)message.body.id); var userId = Guid.Parse(session.user.id); // var m = StructureGraph.Instance.GetTaskById(id, userId); // var ans = Helper.BuildMessage(what); ans.body.obj = m; return(ans); } return(Helper.BuildMessage(what)); }
public async Task <dynamic> Handle(dynamic session, dynamic message) { string what = message.head.what; if (what == "log-subscribe") { var array = message.body.ids; //session.logSubscriber = array; var ids = new List <Guid>(); var tubeIds = new List <dynamic>(); foreach (var id in array) { Guid gid = Guid.Parse(id.ToString()); ids.Add(gid); var neighbours = Data.StructureGraph.Instance.GetTubeNeighbourIds(gid).Distinct().ToList(); dynamic foo = new ExpandoObject(); foo.tubeId = id; foo.neighbours = neighbours; tubeIds.Add(foo); } //allIds.AddRange(ids); //log.Debug(string.Format("подписка для сессии {0}, [{1}]", session.id, string.Join(",", allIds))); session.logSubscriber = tubeIds; Data.CacheRepository.Instance.SaveSession(session, Guid.Parse(session.userId.ToString())); var answer = Helper.BuildMessage(what); return(answer); } if (what == "log-unsubscribe") { //var bag = session.bag as IDictionary<string, object>; //if (!bag.ContainsKey(LOG_KEY)) //{ // bag.Add(LOG_KEY, new List<Guid>()); //} //var answer = Helper.BuildMessage(what); //foreach (Guid id in message.body.ids) //{ // (bag[LOG_KEY] as List<Guid>).Remove(id); //} //return answer; } return(Helper.BuildMessage(what)); }
public async Task <dynamic> Handle(dynamic session, dynamic message) { string what = message.head.what; Guid userId = Guid.Parse(session.userId); if (what == "users-get-rights") { var answer = Helper.BuildMessage(what); //загрузка дерева с правами Guid targetId = Guid.Parse(message.body.targetId.ToString()); //1 get tree+relations? answer.body.groups = StructureGraph.Instance.GetGroups(userId); answer.body.rights = StructureGraph.Instance.GetRightRelations(userId, targetId); return(answer); } if (what == "users-get") { var answer = Helper.BuildMessage(what); //загрузка дерева с правами answer.body.groups = StructureGraph.Instance.GetGroups(userId); return(answer); } if (what == "users-password") { var answer = Helper.BuildMessage(what); answer.body.success = false; if ((string)message.body.password == "X7]JSAm5pxKoiLMzMOr0C$5K") { answer.body.success = true; } return(answer); } if (what == "users-by-login-password") // просто проверка логина и пароля { string login = message.body.login; string passwordHash = message.body.password; var user = StructureGraph.Instance.GetUser(login, passwordHash); if (user == null) { var ans = Helper.BuildMessage("users-error"); ans.body.message = "неверный логин или пароль"; ans.body.success = false; return(ans); } var localUserId = Guid.Parse((string)user.id); var ansSuccess = Helper.BuildMessage("users-success"); ansSuccess.body.user = localUserId; ansSuccess.body.success = true; return(ansSuccess); } return(Helper.BuildMessage(what)); }
public async Task <dynamic> Handle(dynamic session, dynamic message) { string what = message.head.what; if (what == "subscribe-event") { } return(Helper.BuildMessage(what)); }
public async Task <dynamic> Handle(dynamic session, dynamic message) { string what = message.head.what; Guid userId = Guid.Parse(session.userId.ToString()); if (what == "cache-clear") { Guid id = Guid.Parse(message.body.id.ToString()); dynamic cache = new ExpandoObject(); Data.CacheRepository.Instance.SaveCache(id, cache); } return(Helper.BuildMessage(what)); }
public async Task <dynamic> Handle(dynamic session, dynamic message) { string what = message.head.what; Guid userId = Guid.Parse(session.userId.ToString()); if (what == "modems-get-all") { var answer = Helper.BuildMessage(what); answer.body.modems = new List <dynamic>(); var modems = StructureGraph.Instance.GetNodesByType("Modem", userId); foreach (var modem in modems.OrderBy(x => (string)x.port, new Comparer())) { answer.body.modems.Add(modem); } return(answer); } //if (what == "modems-of-pool") //{ // var answer = Helper.BuildMessage(what); // answer.body.modems = new JArray(); // Guid poolId = message.body.poolId; // var entities = Cache.Instance.GetEntities((Guid)session.User.id); // foreach (var modem in entities.OfType<GsmModem>().Where(m => m.CsdPortId == poolId)) // { // answer.body.modems.Add(modem.ToJSONDynamic()); // } // return answer; //} //if (what == "modems-save") //{ // var modems = new List<GsmModem>(); // foreach (var modem in message.body.modems) // { // modems.Add((GsmModem)EntityExtensions.ToEntity(modem)); // } // Cache.Instance.SaveEntities(modems, session.User); //} return(Helper.BuildMessage(what)); }
public async Task <dynamic> Handle(dynamic session, dynamic message) { string what = message.head.what; if (what == "maquette-list") { var objs = StructureGraph.Instance.GetMaquettes(Guid.Parse(session.user.id)); var ans = Helper.BuildMessage(what); ans.body.maquettes = objs; return(ans); } if (what == "maquette-get") { var id = Guid.Parse((string)message.body.id); var userId = Guid.Parse(session.user.id); // var m = StructureGraph.Instance.GetMaquetteById(id, userId); // var ans = Helper.BuildMessage(what); ans.body.maquette = m; return(ans); } if (what == "maquette-send") { var maquetteId = Guid.Parse((string)message.body.id); var userId = Guid.Parse(session.user.id); var days = new List <DateTime>(); foreach (var day in message.body.days) { days.Add(day); } var sent = Send(maquetteId, days, userId); var ans = Helper.BuildMessage(what); ans.body.sent = sent.data; ans.body.error = sent.error; ans.body.success = sent.success; return(ans); } return(Helper.BuildMessage(what)); }
//public List<dynamic> Send1(Guid mailerId, DateTime start, DateTime end, Guid userId, dynamic session, string period) //{ // if (period != "Daily" && period != "Monthly") return null; // неизвестный период // var mailer = StructureGraph.Instance.GetMailerById(mailerId, userId); // if (mailer == null) return null; // var dmailer = mailer as IDictionary<string, object>; // if (!dmailer.ContainsKey("kind") || mailer.kind == "disabled") return null; //запрет отправки // var startNumber = dmailer.ContainsKey("lastNumber") ? (int)mailer.lastNumber : 1; // var number = startNumber++; // var nullAllowed = dmailer.ContainsKey("nullAllowed") ? (bool)mailer.nullAllowed : false; // var mailerName = dmailer.ContainsKey("name") ? mailer.name : "<рассылка без названия>"; // var mailerReports = dmailer.ContainsKey("report" + period) ? dmailer["report" + period].ToString() : ""; // if (mailerReports == "") return null; //нет отчётов с соответствующим периодом // // // var targetIdList = new List<Guid>(); // var targetNameList = new List<string>(); // if (dmailer.ContainsKey("Tube") && mailer.Tube != null) // { // foreach (var tube in mailer.Tube) // { // targetIdList.Add(Guid.Parse((string)tube.id)); // var dtube = tube as IDictionary<string, object>; // targetNameList.Add(dtube.ContainsKey("name") ? tube.name : "?"); // } // } // var smtpHost = ConfigurationManager.AppSettings["senderServer"]; //mailer.senderServer; // var smtpPort = ConfigurationManager.AppSettings["senderPort"]; //mailer.senderPort; // var mailLogin = ConfigurationManager.AppSettings["sender"]; //mailer.sender; // var mailPass = ConfigurationManager.AppSettings["senderPassword"]; //mailer.senderPassword; // if (!dmailer.ContainsKey("receiver") || mailer.receiver == "") return null; // var mailTo = mailer.receiver; // var mailerData = new List<dynamic>(); // // // //var Subject = string.Format("{0}_{1:yyyyMMdd}_{2}", maquette.Sender.Inn, maquette.DateTime.DayAsDateTime, maquette.Number); // var reportNames = ""; // MailMessage mail = new MailMessage(); // mail.From = new MailAddress(mailLogin); // mail.To.Add(mailTo); // var resultIsNull = false; // if (!dmailer.ContainsKey("Report") || mailer.Report == null || mailer.Report.Length == 0) return null; // foreach (var report in mailer.Report) // { // if (!mailerReports.Contains((string)report.id)) continue; // // // reportNames += (reportNames == "" ? "" : ", ") + report.name; // var reportId = Guid.Parse((string)report.id); // var result = ReportHandler.Instance.Build(reportId, targetIdList, start, end, userId, session); // var reportContent = result.render; // if (result.build.nullCount != 0) // { // resultIsNull |= true; // } // var bytes = Html2PdfConvertor.Instance.Convert(reportContent);//var bytes = Encoding.UTF8.GetBytes(reportContent); // MemoryStream stream = new MemoryStream(bytes); // Attachment attachment = new Attachment(stream, string.Format("{0} - {1}.pdf", mailerName, report.name)); // mail.Attachments.Add(attachment); // } // if (mail.Attachments.Count == 0) return null; // if (!nullAllowed && resultIsNull) return null; // var tubeCount = string.Format("{0} точ{1} учёта", targetIdList.Count, targetIdList.Count == 1 ? "ка" : (targetIdList.Count < 5 ? "ки" : "ек")); // mail.Subject = string.Format("{2}{0} ({1})", mailerName, tubeCount, period == "Monthly" ? "[МЕСЯЦ] " : ""); // mail.Body = string.Format("Рассылка \"{0}\" ({1})\r\nОтчёт{3}: {2}", mailerName, tubeCount, reportNames, mailer.Report.Length > 1 ? "ы" : "");//, string.Join("\r\n", targetNameList)); // // // SmtpClient SmtpServer = new SmtpClient(smtpHost); // SmtpServer.Port = 587; // SmtpServer.Credentials = new System.Net.NetworkCredential(mailLogin, mailPass); // SmtpServer.EnableSsl = true; // try // { // SmtpServer.Send(mail); // dynamic mData = new ExpandoObject(); // mData.id = Guid.NewGuid().ToString(); // mData.date = start; // mData.objectId = mailerId.ToString(); // mData.type = DataRecordTypes.MailerType + period; // mData.i1 = number; // mData.i2 = resultIsNull ? 1 : 0; // mData.s1 = reportNames; // mData.s2 = mail.Subject;// string.Join("\r\n", targetNameList); // mData.s3 = mailTo; // mData.dt1 = DateTime.Now; // mData.dt2 = end; // mailerData.Add(mData); // } // catch (Exception ex) // { // log.ErrorFormat("Ошибка при отправке писем {0}", ex); // } // var records = new List<DataRecord>(); // foreach (var raw in mailerData) // { // records.Add(EntityExtensions.ToRecord(raw)); // } // if (records.Count > 0) // { // RecordAcceptor.Instance.Save(records); // } // mailer.lastNumber = startNumber; // //StructureGraph.Instance.UpdNode(mailerId, "Mailer", mailer, userId); // return mailerData; //} public async Task <dynamic> Handle(dynamic session, dynamic message) { string what = message.head.what; if (what == "mailer-list") { var objs = StructureGraph.Instance.GetMailers(Guid.Parse(session.user.id)); var ans = Helper.BuildMessage(what); ans.body.mailers = objs; return(ans); } if (what == "mailer-get") { var mailerId = Guid.Parse((string)message.body.id); var userId = Guid.Parse(session.user.id); // var mailer = StructureGraph.Instance.GetMailerById(mailerId, userId); // var ans = Helper.BuildMessage(what); ans.body.mailer = mailer; return(ans); } if (what == "mailer-send") { var mailerId = Guid.Parse((string)message.body.id); var userId = Guid.Parse(session.user.id); var date = (DateTime)message.body.date; //var start = (DateTime)message.body.start; //var end = (DateTime)message.body.end; //var period = message.body.period.ToString(); var sent = Send(mailerId, date, userId, session); //var sent = Send(mailerId, start, end, userId, session, period); var ans = Helper.BuildMessage(what); ans.body.sent = sent.data; ans.body.error = sent.error; ans.body.success = sent.success; return(ans); } return(Helper.BuildMessage(what)); }
public async Task <dynamic> Handle(dynamic session, dynamic message) { var bag = session as IDictionary <string, object>; if (bag.ContainsKey(SignalRConnection.SIGNAL_CONNECTION_ID)) { bag[SignalRConnection.SIGNAL_CONNECTION_ID] = message.body.connectionId; } else { bag.Add(SignalRConnection.SIGNAL_CONNECTION_ID, message.body.connectionId); } Data.CacheRepository.Instance.SaveSession(session, Guid.Parse((string)session.userId)); log.Debug(string.Format("подписка на события {0}", message.body.connectionId)); var answer = Helper.BuildMessage("signal-binded"); return(answer); }
public async Task <dynamic> Handle(dynamic session, dynamic message) { string what = message.head.what; Guid sessionId = Guid.Parse(session.userId); if (what == "driver-list") { var drivers = StructureGraph.Instance.GetDrivers(Guid.Parse(session.userId)); var ans = Helper.BuildMessage(what); ans.body.drivers = drivers; return(ans); } if (what == "drivers-save") { if (false) { var ans = Helper.BuildMessage("access-denied"); ans.body.message = "не хватает прав"; return(ans); } foreach (var driver in message.body.drivers) { dynamic msg = Helper.BuildMessage("driver-update"); msg.body.action = "update"; msg.body.driver = driver; ClientsNotifier.Instance.NotifyAll(msg); StructureGraph.Instance.SaveDriver(driver, Guid.Parse(session.userId)); } } if (what == "drivers-create") { string name = message.body.name; dynamic msg = Helper.BuildMessage("driver-create"); msg.body.action = "create"; ClientsNotifier.Instance.NotifyAll(msg); StructureGraph.Instance.CreateDriver(name, Guid.Parse(session.userId)); } return(Helper.BuildMessage(what)); }
public async Task <dynamic> Handle(dynamic session, dynamic message) { string what = message.head.what; Guid sessionId = Guid.Parse(session.userId); if (what == "folders-get") { var tree = StructureGraph.Instance.GetHierarchy("Folder", "contains", Guid.Parse(session.userId)); var answer = Helper.BuildMessage(what); answer.body.root = tree; return(answer); } if (what == "folders-get-2") { var tree = StructureGraph.Instance.GetFolders(sessionId); var answer = Helper.BuildMessage(what); answer.body.root = tree; return(answer); } if (what == "folders-by-tubes") { var tubeIds = new List <Guid>(); foreach (var tid in message.body.tubeIds) { tubeIds.Add(Guid.Parse(tid.ToString())); } dynamic res = StructureGraph.Instance.GetFoldersTubes(tubeIds.ToArray(), Guid.Parse(session.userId)); var answer = Helper.BuildMessage(what); answer.body.folders = res; return(answer); } return(Helper.BuildMessage(what)); }
public async Task <dynamic> Handle(dynamic session, dynamic message) { string what = message.head.what; Guid userId = Guid.Parse(session.userId.ToString()); if (false && !session.IsSuperUser) { var ans = Helper.BuildMessage(what); ans.body.message = "недостаточно прав"; return(ans); } if (what == "managment-get-sessions") { var ans = Helper.BuildMessage(what); ans.body.sessions = new List <dynamic>(); return(ans); } if (what == "managment-pollserver-reset") { var serverName = message.body.serverName; var sessions = CacheRepository.Instance.GetSessions(); foreach (var sess in sessions) { var dsession = sess as IDictionary <string, object>; if (!dsession.ContainsKey(SignalRConnection.SIGNAL_CONNECTION_ID)) { continue; } var connectionId = dsession[SignalRConnection.SIGNAL_CONNECTION_ID].ToString(); SignalRConnection.RaiseEvent(message, connectionId); } var ans = Helper.BuildMessage(what); ans.body.message = string.Format("перезагрузка сервера {0} уведомлено {1} клиентов", serverName, sessions.Count()); return(ans); } if (what == "managment-service-operation") { var ans = Helper.BuildMessage(what); ans.body.message = "недостаточно прав"; if ((message is IDictionary <string, object>) && (message as IDictionary <string, object>).ContainsKey("body") && (message.body is IDictionary <string, object>)) { IDictionary <string, object> dbody = message.body as IDictionary <string, object>; string password = ConfigurationManager.AppSettings["servicePassword"]; string operationName = null; string operationAction = null; string successMessage = null; if (dbody.ContainsKey("operation") && (message.body.operation is string) && (message.body.operation != null) && (message.body.operation != "")) { operationName = message.body.operation; operationAction = ConfigurationManager.AppSettings["operation_" + operationName]; successMessage = ConfigurationManager.AppSettings["message_" + operationName]; if (operationAction == null) { ans.body.message = "не найдена соответствующая операция в конфигурационном файле"; } else if (successMessage == null || successMessage == "") { successMessage = string.Format("выполняется сервисная операция: {0}", ans.body.operation); } } else { operationName = "serviceOperation"; operationAction = ConfigurationManager.AppSettings["serviceOperation"]; successMessage = "производится рестарт сервера"; } if (password != null && operationAction != null && operationAction != "" && dbody.ContainsKey("password") && (message.body.password is string) && (password == message.body.password)) { ans.body.message = successMessage; Process.Start(operationAction); //Process myProcess = new Process(); //myProcess.StartInfo.FileName = "cmd.exe"; //myProcess.StartInfo.Arguments = string.Format(@"/C cd {0} & {1}", Environment.CurrentDirectory, operation); //myProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; //myProcess.StartInfo.CreateNoWindow = true; //myProcess.Start(); } } return(ans); } if (what == "managment-rebuild-cache") { var diagnos = ""; var sw = new Stopwatch(); //параметры sw.Start(); var parameters = StructureGraph.Instance.GetAllParameters(userId); foreach (var par in parameters) { CacheRepository.Instance.SaveParameter(par.tubeId, par); } sw.Stop(); diagnos += string.Format("параметры перестроены за {0} мс;", sw.ElapsedMilliseconds); var result = new List <dynamic>(); sw.Restart(); var ids = StructureGraph.Instance.GetRowIds("", new Guid[] { }, userId); var rows = new List <dynamic>(); const int step = 100; for (var offset = 0; offset < ids.Count(); offset += step) { rows.AddRange(StructureGraph.Instance.GetRows(ids.Skip(offset).Take(step), userId)); } foreach (var row in rows) { var id = Guid.Parse(row.id.ToString()); CacheRepository.Instance.Set("row", id, row); //CacheRepository.Instance.SetLocal("row", id, row); } sw.Stop(); diagnos += string.Format("строки перестроены за {0} мс;", sw.ElapsedMilliseconds); var ans = Helper.BuildMessage(what); ans.body.message = diagnos; return(ans); } if (what == "managment-kill-com") { string port = message.body.port; var sessions = CacheRepository.Instance.GetSessions(); foreach (var sess in sessions) { var dsession = sess as IDictionary <string, object>; if (!dsession.ContainsKey(SignalRConnection.SIGNAL_CONNECTION_ID)) { continue; } var connectionId = dsession[SignalRConnection.SIGNAL_CONNECTION_ID].ToString(); SignalRConnection.RaiseEvent(message, connectionId); } var ans = Helper.BuildMessage(what); ans.body.message = string.Format("убийство ком порта {0}", port); return(ans); } if (what == "managment-ping") { var ans = Helper.BuildMessage("managment-pong"); if ((message as IDictionary <string, object>).ContainsKey("body") && (message.body is IDictionary <string, object>) && (message.body as IDictionary <string, object>).ContainsKey("message") && (message.body.message is string) && (message.body.message != "")) { log.Info(string.Format("сообщение пинг: {0}", message.body.message)); } return(ans); } if (what == "managment-test") { string[] objectIds = new string[] { "15739db6-d683-45fa-92ff-7d6ff37ae2a1" }; dynamic test = new ExpandoObject(); test.head = new ExpandoObject(); test.head.what = "poll"; test.body = new ExpandoObject(); test.body.objectIds = objectIds; test.body.auto = false; test.body.arg = new ExpandoObject(); test.body.arg.cmd = ""; test.body.arg.components = "Current:3;"; test.body.arg.logLevel = "1"; test.body.arg.onlyHoles = false; var sessions = CacheRepository.Instance.GetSessions(); foreach (var sess in sessions) { if (sess.id == session.id) { continue; } var bag = sess as IDictionary <string, object>; if (!bag.ContainsKey(SignalRConnection.SIGNAL_CONNECTION_ID)) { continue; } var connectionId = bag[SignalRConnection.SIGNAL_CONNECTION_ID].ToString(); SignalRConnection.RaiseEvent(test, connectionId); } } return(Helper.BuildMessage(what)); }
public async Task <dynamic> Handle(dynamic session, dynamic message) { string what = message.head.what; if (what == "auth-by-login") { //return System.Threading.Tasks.Task.Run<dynamic>(() => //{ string login = message.body.login; #if ORENBURG string password = message.body.password; var passwordHash = GetHashString(password); #else string passwordHash = message.body.password; #endif var user = StructureGraph.Instance.GetUser(login, passwordHash); if (user == null) { var ans = Helper.BuildMessage("auth-error"); ans.body.message = "неверный логин или пароль"; return(ans); } var userId = Guid.Parse((string)user.id); dynamic newSession = new ExpandoObject(); //Session.Create(findedUser); newSession.id = Guid.NewGuid(); newSession.bag = new ExpandoObject(); newSession.user = user; Data.CacheRepository.Instance.SaveSession(newSession, userId); /* * //рабочий код 19.02.2019 изменен из-за redis * var findedUser = StructureGraph.Instance.GetUser(login, passwordHash); * if (findedUser == null) * { * var ans = Helper.BuildMessage("auth-error"); * ans.body.message = "неверный логин или пароль"; * return ans; * } * * var userId = Guid.Parse((string)findedUser.id); * var user = StructureGraph.Instance.GetNodeById(userId, userId); * * dynamic newSession = new ExpandoObject(); //Session.Create(findedUser); * newSession.id = Guid.NewGuid(); * newSession.bag = new ExpandoObject(); * newSession.user = user; * * Data.CacheRepository.Instance.SaveSession(newSession, userId); * * newSession = Data.CacheRepository.Instance.GetSession(newSession.id); * //SessionManager.Instance.AddSession(newSession); */ var ansSuccess = Helper.BuildMessage("auth-success"); ansSuccess.body.user = newSession.user; //ansSuccess.body.user.roles = new string[] { "Admin", "User" }; ansSuccess.body.sessionId = newSession.id; return(ansSuccess); //}); } if (what == "auth-by-login1") // просто проверка логина и пароля { string login = message.body.login; string passwordHash = message.body.password; var user = StructureGraph.Instance.GetUser(login, passwordHash); if (user == null) { var ans = Helper.BuildMessage("auth-error"); ans.body.message = "неверный логин или пароль"; return(ans); } var userId = Guid.Parse((string)user.id); var ansSuccess = Helper.BuildMessage("auth-success"); ansSuccess.body.user = userId; return(ansSuccess); } if (what == "auth-by-session") { //return System.Threading.Tasks.Task.Run<dynamic>(() => // { Guid sessionId; if (message.body.sessionId.GetType() == typeof(Guid)) { sessionId = message.body.sessionId; } else { sessionId = Guid.Parse(message.body.sessionId); } var newSession = Data.CacheRepository.Instance.GetSession(sessionId); //var newSession = Session.TryCreate(sessionId); if (newSession == null) { var ans = Helper.BuildMessage("auth-error"); ans.body.message = "указанная сессия не найдена"; return(ans); } //SessionManager.Instance.AddSession(newSession); var ansSuccess = Helper.BuildMessage("auth-success"); ansSuccess.body.user = newSession.user; ansSuccess.body.sessionId = newSession.id; return(ansSuccess); //}); } if (what == "auth-close-session") { Guid sessionId = Guid.Parse((string)message.body.sessionId); StructureGraph.Instance.CloseSession(sessionId); var ans = Helper.BuildMessage("auth-session-closed"); return(ans); } return(null); }
public async Task <dynamic> Handle(dynamic session, dynamic message) { string what = message.head.what; var userId = Guid.Parse(session.userId.ToString()); if (what == "parse-matrix-terminal-config-from-string") { var answer = Helper.BuildMessage(what); var dicBody = message.body as IDictionary <string, object>; if (dicBody.ContainsKey("strConfig")) { List <dynamic> listProfile = new List <dynamic>(); List <string> listApnName = new List <string>(); string strConfig = message.body.strConfig.ToString(); var bytesConfig = strConfig.Split('-').Select(x => byte.Parse(x, NumberStyles.HexNumber)).ToArray(); MatrixTerminalConfig conf = StructsHelper.Instance.setBytesFromConfig <MatrixTerminalConfig>(bytesConfig, new MatrixTerminalConfig()); answer.body.config = conf; foreach (var profile in conf.profile) { dynamic profileTmp = new ExpandoObject(); string ipPort = StructsHelper.Instance.ParseStringFromBytes(profile.ip_port); profileTmp.ip = (ipPort.Contains(':'))? ipPort.Split(':')[0]: ipPort; profileTmp.port = (ipPort.Contains(':')) ? ipPort.Split(':')[1] : ""; listProfile.Add(profileTmp); } foreach (var apnName in conf.apnName) { listApnName.Add(StructsHelper.Instance.ParseStringFromBytes(apnName.APN)); } answer.body.profiles = listProfile; answer.body.APNs = listApnName; } return(answer); } if (what == "parse-matrix-terminal-get-string-from-config") { var answer = Helper.BuildMessage(what); var config = message.body.config; var profiles = message.body.profiles; var APNs = message.body.APNs; var dicBody = message.body as IDictionary <string, object>; if (dicBody.ContainsKey("strConfig")) { List <dynamic> listProfile = new List <dynamic>(); List <string> listApnName = new List <string>(); string strConfig = message.body.strConfig.ToString(); var bytesConfig = strConfig.Split('-').Select(x => byte.Parse(x, NumberStyles.HexNumber)).ToArray(); MatrixTerminalConfig conf = StructsHelper.Instance.setBytesFromConfig <MatrixTerminalConfig>(bytesConfig, new MatrixTerminalConfig()); for (int i = 0; i < conf.profile.Length; i++) { conf.profile[i].ip_port = StructsHelper.Instance.Parse24BytesFromString(profiles[i].ip + ":" + profiles[i].port); } byte[] tmpBytes = StructsHelper.Instance.getBytes <MatrixTerminalConfig>(conf); string strConf = BitConverter.ToString(tmpBytes); answer.body.strConfig = strConf; } return(answer); } return(Helper.BuildMessage(what)); }
public async Task <dynamic> Handle(dynamic session, dynamic message) { var userId = Guid.Parse(session.userId.ToString()); string what = message.head.what; if (what == "parameters-save") { var tubeId = Guid.Parse(message.body.tubeId.ToString()); foreach (var parameter in message.body.parameters) { Guid pid = Guid.Parse(parameter.id.ToString()); StructureGraph.Instance.UpdNode(pid, "Parameter", parameter, userId); StructureGraph.Instance.AddOrUpdRelation(tubeId, pid, "parameter", new ExpandoObject(), userId); CacheRepository.Instance.SaveParameter(tubeId, parameter); } //Data.NodeBackgroundProccessor.Instance.AddTokens(tokens); var ans = Helper.BuildMessage(what); return(ans); } if (what == "parameters-save-tags") { var tubeId = Guid.Parse(message.body.tubeId.ToString()); CacheRepository.Instance.SetTags(tubeId, message.body.tags); var ans = Helper.BuildMessage(what); return(ans); } if (what == "parameters-delete") { //var tokens = new List<dynamic>(); //foreach (var id in message.body.ids) //{ // dynamic token = new ExpandoObject(); // token.action = "delete"; // token.start = new ExpandoObject(); // token.start.id = Guid.Parse((string)id); // token.start.type = "Parameter"; // token.userId = userId; // tokens.Add(token); // //Data.StructureGraph.Instance.DeleteNode(Guid.Parse((string)id), Guid.Parse((string)session.User.id)); //} ////Data.NodeBackgroundProccessor.Instance.AddTokens(tokens); var ans = Helper.BuildMessage(what); return(ans); } if (what == "parameters-get") { Guid tubeId = Guid.Parse(message.body.tubeId.ToString()); dynamic answer = Helper.BuildMessage(what); var parameters = StructureGraph.Instance.GetParameters(tubeId, userId); answer.body.parameters = parameters; return(answer); } if (what == "parameters-get-2") { Guid tubeId = Guid.Parse(message.body.tubeId.ToString()); dynamic answer = Helper.BuildMessage(what); var tags = StructureGraph.Instance.GetTags(tubeId, userId); var parameters = StructureGraph.Instance.GetParameters(tubeId, userId); answer.body.parameters = parameters; answer.body.tags = tags; return(answer); } if (what == "parameters-get-2") { Guid tubeId = Guid.Parse(message.body.tubeId.ToString()); dynamic answer = Helper.BuildMessage(what); var tags = StructureGraph.Instance.GetTags(tubeId, userId); var parameters = StructureGraph.Instance.GetParameters(tubeId, userId); answer.body.parameters = parameters; answer.body.tags = tags; return(answer); } if (what == "parameters-get-3") { dynamic answer = Helper.BuildMessage(what); var tubes = new List <dynamic>(); foreach (string tubeId in message.body.tubeIds) { dynamic tube = new ExpandoObject(); Guid id = Guid.Parse(tubeId.ToString()); var parameters = StructureGraph.Instance.GetParameters(id, userId); tube.tubeId = id; tube.parameters = parameters; tubes.Add(tube); } answer.body.tubes = tubes; return(answer); } if (what == "parameters-recalc") { Guid tubeId = Guid.Parse(message.body.tubeId.ToString()); var all = new List <DataRecord>(); try { //Hour { var date = Data.Cache.Instance.GetLastDate("Hour", tubeId); if (date == DateTime.MinValue) { all.AddRange(Data.Cache.Instance.GetRecords(DateTime.Now.AddHours(-24), DateTime.Now.AddHours(8), "Hour", new Guid[] { tubeId })); } else { all.AddRange(Data.Cache.Instance.GetRecords(date.AddHours(-3), date.AddHours(+1), "Hour", new Guid[] { tubeId })); } } //Day { var date = Data.Cache.Instance.GetLastDate("Day", tubeId); if (date == DateTime.MinValue) { all.AddRange(Data.Cache.Instance.GetRecords(DateTime.Now.AddDays(-7), DateTime.Now.AddDays(1), "Day", new Guid[] { tubeId })); } else { all.AddRange(Data.Cache.Instance.GetRecords(date.AddDays(-3), date.AddDays(+1), "Day", new Guid[] { tubeId })); } } //Current { var date = Data.Cache.Instance.GetLastDate("Current", tubeId); all.AddRange(Data.Cache.Instance.GetRecords(date, date, "Current", new Guid[] { tubeId })); } var s1 = all.Select(r => r.S1).Distinct(); var oldParameters = StructureGraph.Instance.GetParameters(tubeId, userId); foreach (var oldParameter in oldParameters) { StructureGraph.Instance.DeleteNode(Guid.Parse(oldParameter.id.ToString()), userId); } CacheRepository.Instance.DelParameters(tubeId); foreach (var s in s1) { dynamic parameter = new ExpandoObject(); parameter.id = Guid.NewGuid(); parameter.name = s; parameter.type = "Parameter"; StructureGraph.Instance.AddNode(parameter.id, "Parameter", parameter, userId); StructureGraph.Instance.AddOrUpdRelation(tubeId, parameter.id, "parameter", new ExpandoObject(), userId); CacheRepository.Instance.SaveParameter(tubeId, parameter); } } catch (Exception ex) { return(Helper.BuildMessage(what)); } } if (what == "parameters-recalc-driver") { Guid tubeId = Guid.Parse(message.body.tubeId.ToString()); try { dynamic dev = StructureGraph.Instance.GetTubeDevice(tubeId, userId); var ddev = dev as IDictionary <string, object>; if (ddev.ContainsKey("tags")) { //получение сведений var serializer = new JavaScriptSerializer(); var tags = new List <dynamic>(); foreach (var strTag in dev.tags) { var tag = serializer.Deserialize(strTag, typeof(object)) as Dictionary <string, object>; dynamic parameter = new ExpandoObject(); parameter.id = Guid.NewGuid(); parameter.name = tag["name"]; parameter.parameter = tag["parameter"]; parameter.calc = tag["calc"]; parameter.dataType = tag["dataType"]; parameter.type = "Tag"; tags.Add(parameter); } //удаление старых тегов //var oldParameters = StructureGraph.Instance.GetParameters(tubeId, userId); //foreach (var oldParameter in oldParameters) //{ // StructureGraph.Instance.DeleteNode(Guid.Parse(oldParameter.id.ToString()), userId); //} //CacheRepository.Instance.DelParameters(tubeId); var oldTags = StructureGraph.Instance.GetTags(tubeId, userId); foreach (var oldTag in oldTags) { StructureGraph.Instance.DeleteNode(Guid.Parse(oldTag.id.ToString()), userId); } ////установка параметров //foreach (var s in tags.Select(r => r.parameter).Distinct()) //{ // if (s == "") continue; // dynamic parameter = new ExpandoObject(); // parameter.id = Guid.NewGuid(); // parameter.name = s; // parameter.type = "Parameter"; // StructureGraph.Instance.AddNode(parameter.id, "Parameter", parameter, userId); // StructureGraph.Instance.AddOrUpdRelation(tubeId, parameter.id, "parameter", new ExpandoObject(), userId); // CacheRepository.Instance.SaveParameter(tubeId, parameter); //} //установка тегов foreach (var t in tags) { StructureGraph.Instance.AddNode(t.id, "Tag", t, userId); StructureGraph.Instance.AddOrUpdRelation(tubeId, t.id, "tag", new ExpandoObject(), userId); } CacheRepository.Instance.SetTags(tubeId, tags); } } catch (Exception ex) { return(Helper.BuildMessage(what)); } } return(Helper.BuildMessage(what)); }
public async Task <dynamic> Handle(dynamic session, dynamic message) { string what = message.head.what; var userId = Guid.Parse(session.userId.ToString()); if (what == "node-states") { foreach (var state in message.body.states) { Guid nodeId = Guid.Parse(state.nodeId.ToString()); var cache = Data.CacheRepository.Instance.GetCache(nodeId); if (cache == null) { cache = new ExpandoObject(); } cache.State = state; Data.CacheRepository.Instance.SaveCache(nodeId, cache); Data.RowsCache.Instance.UpdateState(state, nodeId, userId); Carantine.Instance.Push(nodeId, (int)state.code); } } if (what == "node-get-astronomTimer") { var answer = Helper.BuildMessage(what); Guid id = Guid.Parse(message.body.objectId.ToString()); dynamic tube = StructureGraph.Instance.GetTube(id, userId); var dtube = tube as IDictionary <string, object>; if (dtube.ContainsKey("coordinates")) { answer.body.coordinates = (string)tube.coordinates; } if (dtube.ContainsKey("afterBeforeSunSetRise")) { answer.body.afterBeforeSunSetRise = (string)tube.afterBeforeSunSetRise; } if (dtube.ContainsKey("utc")) { answer.body.utc = (string)tube.utc; } return(answer); } if (what == "node-update-astronomTimer") { string coordinates = (string)message.body.coordinates; string utc = (string)message.body.utc; string afterBeforeSunSetRise = (string)message.body.afterBeforeSunSetRise; Guid objectId = Guid.Parse((string)message.body.objectId); StructureGraph.Instance.UpdateLightControlsAstronTimersValues(coordinates, utc, afterBeforeSunSetRise, objectId); var ans = Helper.BuildMessage(what); return(ans); } if (what == "node-controller-data") { dynamic control = (dynamic)message.body.control; var dcontrol = control as IDictionary <string, object>; Guid objectId = Guid.Parse((string)message.body.objectId); //для освещения if (dcontrol.ContainsKey("controllerData")) { string controllerData = (string)control.controllerData; Data.RowsCache.Instance.UpdateControllerData(controllerData, objectId, userId); Carantine.Instance.Push(objectId); } if (dcontrol.ContainsKey("lightV2Config")) { string strConfig = (string)control.lightV2Config; StructureGraph.Instance.UpdateControlConfig(strConfig, objectId); //strConfig var ans = Helper.BuildMessage(what); return(ans); } if (dcontrol.ContainsKey("controllerConfig")) { string strConfig = (string)control.controllerConfig; StructureGraph.Instance.UpdateControlConfig(strConfig, objectId); //strConfig var ans = Helper.BuildMessage(what); return(ans); } } if (what == "node-config") { } if (what == "node-events") { int events = Convert.ToInt32(message.body.events); Guid objectId = Guid.Parse((string)message.body.objectId); Data.RowsCache.Instance.UpdateEvents(events, objectId, userId); Carantine.Instance.Push(objectId); } if (what == "node-watertower") { float max = Convert.ToSingle(message.body.max); float min = Convert.ToSingle(message.body.min); int controlMode = Convert.ToInt32(message.body.controlMode); Guid objectId = Guid.Parse((string)message.body.objectId); StructureGraph.Instance.UpdateWaterTowenParametr(min, max, controlMode, objectId); List <dynamic> rules = new List <dynamic>(); var connections = StructureGraph.Instance.GetNeightbours(objectId, userId); foreach (var connection in connections) { dynamic ruleConnection = new ExpandoObject(); ruleConnection.action = "upd"; ruleConnection.target = "node"; ruleConnection.content = new ExpandoObject(); ruleConnection.content.id = connection.id; ruleConnection.content.body = connection; ruleConnection.content.type = (string)connection.type; rules.Add(ruleConnection); } var area = StructureGraph.Instance.GetArea(objectId, userId); dynamic ruleArea = new ExpandoObject(); ruleArea.action = "upd"; ruleArea.target = "node"; ruleArea.content = new ExpandoObject(); ruleArea.content.id = area.id; ruleArea.content.body = area; ruleArea.content.type = "Area"; rules.Add(ruleArea); var tube = StructureGraph.Instance.GetTube(objectId, userId); dynamic ruleTube = new ExpandoObject(); ruleTube.action = "upd"; ruleTube.target = "node"; ruleTube.content = new ExpandoObject(); ruleTube.content.id = tube.id; ruleTube.content.body = tube; ruleTube.content.type = "Tube"; rules.Add(ruleTube); var sessions = CacheRepository.Instance.GetSessions(); sessions.AsParallel().ForAll(s => { var ds = s as IDictionary <string, object>; if (ds == null || !ds.ContainsKey(SignalRConnection.SIGNAL_CONNECTION_ID) || ds[SignalRConnection.SIGNAL_CONNECTION_ID] == null) { return; } Guid uId = Guid.Parse(s.userId.ToString()); dynamic msg = Helper.BuildMessage("changes"); msg.body.rules = new List <dynamic>(); foreach (var rule in rules) { dynamic content = rule.content; Guid id = Guid.Empty; id = Guid.Parse(content.id.ToString()); if (id != Guid.Empty && StructureGraph.Instance.CanSee(id, uId)) { msg.body.rules.Add(rule); } } if (msg.body.rules.Count > 0) { var connectionId = ds[SignalRConnection.SIGNAL_CONNECTION_ID].ToString(); SignalRConnection.RaiseEvent(msg, connectionId); } }); return(Helper.BuildMessage(what)); } if (what == "node-get-light-control-config") { var answer = Helper.BuildMessage(what); string[] lightControlMetod = new string[4]; int[] lightBeforeSunRise = new int[4]; int[,] afterSunSetAndBeforeSunRise = new int[4, 2]; dynamic[,] lightSheduleOn = new dynamic[4, 2]; dynamic[,] lightSheduleOff = new dynamic[4, 2]; DateTime dt1970 = new DateTime(1970, 1, 1, 0, 0, 0); DateTime dt1970With1sec = new DateTime(1970, 1, 1, 0, 0, 1); Guid id = Guid.Parse(message.body.objectId.ToString()); dynamic tube = StructureGraph.Instance.GetTube(id, userId); var dtube = tube as IDictionary <string, object>; if (dtube.ContainsKey("strConfig")) { string strConfig = (string)tube.strConfig; var bytesConfig = strConfig.Split('-').Select(x => byte.Parse(x, NumberStyles.HexNumber)).ToArray(); LightConfig conf = StructsHelper.Instance.setBytesFromConfig <LightConfig>(bytesConfig, new LightConfig()); //Celestial cel = Celestial.CalculateCelestialTimes(Convert.ToInt32(conf.u32lat)+0, Convert.ToInt32(conf.u32lon), new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day)); //DateTime sunRiseUTC = cel.SunRise.Value; //DateTime sunSetUTC = cel.SunSet.Value; //DateTime lightAstronomOn = sunRiseUTC.AddHours(Convert.ToInt32(conf.u8timeDiff)); //DateTime lightAstronomOff = sunSetUTC.AddHours(Convert.ToInt32(conf.u8timeDiff)); lightControlMetod[0] = (conf.ligthtChannels1.u8ControlMode == 0xFF) ? "" : Convert.ToString(conf.ligthtChannels1.u8ControlMode); lightControlMetod[1] = (conf.ligthtChannels2.u8ControlMode == 0xFF) ? "" : Convert.ToString(conf.ligthtChannels2.u8ControlMode); lightControlMetod[2] = (conf.ligthtChannels3.u8ControlMode == 0xFF) ? "" : Convert.ToString(conf.ligthtChannels3.u8ControlMode); lightControlMetod[3] = (conf.ligthtChannels4.u8ControlMode == 0xFF) ? "" : Convert.ToString(conf.ligthtChannels4.u8ControlMode); afterSunSetAndBeforeSunRise[0, 0] = (conf.ligthtChannels1.u8afterSunSet == 0xFF) ? 0 : Convert.ToInt32(conf.ligthtChannels1.u8afterSunSet); afterSunSetAndBeforeSunRise[1, 0] = (conf.ligthtChannels2.u8afterSunSet == 0xFF) ? 0 : Convert.ToInt32(conf.ligthtChannels2.u8afterSunSet); afterSunSetAndBeforeSunRise[2, 0] = (conf.ligthtChannels3.u8afterSunSet == 0xFF) ? 0 : Convert.ToInt32(conf.ligthtChannels3.u8afterSunSet); afterSunSetAndBeforeSunRise[3, 0] = (conf.ligthtChannels4.u8afterSunSet == 0xFF) ? 0 : Convert.ToInt32(conf.ligthtChannels4.u8afterSunSet); afterSunSetAndBeforeSunRise[0, 1] = (conf.ligthtChannels1.u8beforeSunRise == 0xFF) ? 0 : Convert.ToInt32(conf.ligthtChannels1.u8beforeSunRise); afterSunSetAndBeforeSunRise[1, 1] = (conf.ligthtChannels2.u8beforeSunRise == 0xFF) ? 0 : Convert.ToInt32(conf.ligthtChannels2.u8beforeSunRise); afterSunSetAndBeforeSunRise[2, 1] = (conf.ligthtChannels3.u8beforeSunRise == 0xFF) ? 0 : Convert.ToInt32(conf.ligthtChannels3.u8beforeSunRise); afterSunSetAndBeforeSunRise[3, 1] = (conf.ligthtChannels4.u8beforeSunRise == 0xFF) ? 0 : Convert.ToInt32(conf.ligthtChannels4.u8beforeSunRise); lightSheduleOn[0, 0] = conf.ligthtChannels1.on1; lightSheduleOn[1, 0] = conf.ligthtChannels2.on1; lightSheduleOn[2, 0] = conf.ligthtChannels3.on1; lightSheduleOn[3, 0] = conf.ligthtChannels4.on1; lightSheduleOn[0, 1] = conf.ligthtChannels1.on2; lightSheduleOn[1, 1] = conf.ligthtChannels2.on2; lightSheduleOn[2, 1] = conf.ligthtChannels3.on2; lightSheduleOn[3, 1] = conf.ligthtChannels4.on2; lightSheduleOff[0, 0] = conf.ligthtChannels1.off1; lightSheduleOff[1, 0] = conf.ligthtChannels2.off1; lightSheduleOff[2, 0] = conf.ligthtChannels3.off1; lightSheduleOff[3, 0] = conf.ligthtChannels4.off1; lightSheduleOff[0, 1] = conf.ligthtChannels1.off2; lightSheduleOff[1, 1] = conf.ligthtChannels2.off2; lightSheduleOff[2, 1] = conf.ligthtChannels3.off2; lightSheduleOff[3, 1] = conf.ligthtChannels4.off2; answer.body.strConfig = strConfig; answer.body.lightControlMetod = lightControlMetod; answer.body.afterSunSetAndBeforeSunRise = afterSunSetAndBeforeSunRise; answer.body.lightSheduleOn = lightSheduleOn; answer.body.lightSheduleOff = lightSheduleOff; } return(answer); } if (what == "node-get-matrix-terminal-config") { var answer = Helper.BuildMessage(what); Guid id = Guid.Parse(message.body.objectId.ToString()); dynamic node = StructureGraph.Instance.GetNodeById(id); var dnode = node as IDictionary <string, object>; if (dnode.ContainsKey("config")) { string strConfig = (string)node.config; var bytesConfig = strConfig.Split('-').Select(x => byte.Parse(x, NumberStyles.HexNumber)).ToArray(); MatrixTerminalConfig conf = StructsHelper.Instance.setBytesFromConfig <MatrixTerminalConfig>(bytesConfig, new MatrixTerminalConfig()); answer.body.config = conf; List <dynamic> listProfile = new List <dynamic>(); List <string> listApnName = new List <string>(); foreach (var profile in conf.profile) { dynamic profileTmp = new ExpandoObject(); string ipPort = StructsHelper.Instance.ParseStringFromBytes(profile.ip_port); profileTmp.ip = (ipPort.Contains(':')) ? ipPort.Split(':')[0] : ipPort; profileTmp.port = (ipPort.Contains(':')) ? ipPort.Split(':')[1] : ""; listProfile.Add(profileTmp); } foreach (var apnName in conf.apnName) { listApnName.Add(StructsHelper.Instance.ParseStringFromBytes(apnName.APN)); } answer.body.profiles = listProfile; answer.body.APNs = listApnName; answer.body.strConfig = strConfig; } return(answer); } if (what == "node-value") { double value = (double)message.body.indication; string valueUnitMeasurement = (string)message.body.indicatioUnitMeasurement; DateTime date = DateTime.Parse(message.body.date.ToString()); Guid objectId = Guid.Parse((string)message.body.objectId); Data.RowsCache.Instance.UpdateValue(value, valueUnitMeasurement, date, objectId, userId); Carantine.Instance.Push(objectId); } if (what == "node-save") { //var node = message.body.node; //Data.StructureGraph.Instance.SaveNode(node.type.ToString(), node, Guid.Parse((string)session.User.id)); } if (what == "nodes-save") { var nodes = message.body.nodes; var tokens = new List <dynamic>(); foreach (var node in nodes) { var token = node; token.userId = userId; tokens.Add(token); } Data.NodeBackgroundProccessor.Instance.AddTokens(tokens); return(Helper.BuildMessage(what)); } if (what == "node-poll-server") { string serverName = message.body.serverName; var server = StructureGraph.Instance.GetPollServer(serverName); var ans = Helper.BuildMessage(what); ans.body.server = StructureGraph.Instance.GetServer(serverName, Guid.Parse((string)session.userId)); return(ans); } if (what == "nodes-poll-branch") { string serverName = message.body.serverName; var server = StructureGraph.Instance.GetPollServer(serverName); var ans = Helper.BuildMessage(what); ans.body.server = server;//StructureGraph.Instance.GetServer(serverName, Guid.Parse((string)session.userId)); return(ans); } return(Helper.BuildMessage(what)); }
public async Task <dynamic> Handle(dynamic session, dynamic message) { string what = message.head.what; Guid userId = Guid.Parse(session.userId.ToString()); if (what == "rows-cache-update") { RowsCache.Instance.Update(userId); var ans = Helper.BuildMessage(what); return(ans); } if (what == "rows-get-2") { var filter = message.body.filter; var rows = RowsCache.Instance.Get(filter, userId); var ans = Helper.BuildMessage(what); ans.body = rows; return(ans); } if (what == "rows-get-3") { var filter = message.body.filter; var rows = RowsCache.Instance.Get(filter, userId); var ans = Helper.BuildMessage(what); ans.body.ids = (rows.rows as IEnumerable <dynamic>).Select(r => r.id).ToArray(); return(ans); } if (what == "rows-get-4") { var ids = new List <Guid>(); foreach (var id in message.body.ids) { ids.Add(Guid.Parse(id.ToString())); } var rows = RowsCache.Instance.Get(ids, userId); var ans = Helper.BuildMessage(what); ans.body.rows = rows; return(ans); } if (what == "rows-get-light") { var ids = new List <Guid>(); foreach (var id in message.body.ids) { ids.Add(Guid.Parse(id.ToString())); } var rows = RowsCache.Instance.Get(ids, userId); var sw = new Stopwatch(); var datas = new List <dynamic>(); var data0 = new List <dynamic>(); var records = RecordsDecorator.Decorate(ids.ToArray(), DateTime.Now.AddMinutes(-20), DateTime.Now.AddHours(1), "Current", new Guid()); foreach (var id in ids) { data0.Clear(); foreach (var group in records.Where(r => r.ObjectId == id).GroupBy(r => r.Date)) { dynamic rec = new ExpandoObject(); rec.date = group.Key; rec.objectId = id; var drec = rec as IDictionary <string, object>; foreach (var record in group) { var unit = record.S2; var val = record.D1; var name = record.S1.Replace(".", "").Replace(" ", ""); if (!drec.ContainsKey(name)) { drec.Add(name, val); } } data0.Add(rec); } if (data0.Count > 0) { datas.Add(data0[data0.Count - 1]); } } foreach (var row in rows) { foreach (var data in datas) { if (row.id == data.objectId) { row.dataLight = data; } } } var ans = Helper.BuildMessage(what); ans.body.rows = rows; return(ans); } if (what == "rows-get") { var sw = new Stopwatch(); var result = new List <dynamic>(); var ids = new List <Guid>(); sw.Start(); foreach (var raw in message.body.ids) { var id = Guid.Parse((string)raw); //log.Debug(string.Format("рассматривается строка {0}", id)); //check for cache var cachedRow = CacheRepository.Instance.Get("row", id); //var cachedRow = CacheRepository.Instance.GetLocal("row", id); if (cachedRow == null) { //log.Debug(string.Format("строка {0} НЕ найдена в кеше", id)); ids.Add(id); } else { //log.Debug(string.Format("строка {0} найдена в кеше", id)); var cache = CacheRepository.Instance.Get("cache", id); //var cache = CacheRepository.Instance.GetLocal("cache", id); cachedRow.cache = cache; result.Add(cachedRow); } } sw.Stop(); log.Debug(string.Format("поиск в кеше {0} мс", sw.ElapsedMilliseconds)); sw.Restart(); if (ids.Any()) { IEnumerable <dynamic> res = StructureGraph.Instance.GetRows(ids, Guid.Parse(session.userId)); foreach (var r in res) { var id = Guid.Parse(r.id.ToString()); //log.Debug(string.Format("строка {0} записана в кеш", id)); CacheRepository.Instance.Set("row", id, r); var cache = CacheRepository.Instance.Get("cache", id); //CacheRepository.Instance.SetLocal("row", id, r); //var cache = CacheRepository.Instance.GetLocal("cache", id); r.cache = cache; result.Add(r); } } log.Debug(string.Format("поиск в базе {0} мс", sw.ElapsedMilliseconds)); var answer = Helper.BuildMessage(what); answer.body.rows = result; return(answer); } if (what == "row-get-devices") { var devices = StructureGraph.Instance.GetDevices(); var answer = Helper.BuildMessage(what); answer.body.devices = devices; return(answer); } if (what == "row-get-for-edit") { var tubeId = message.body.id; //StructureGraph.Instance } if (what == "row-save-row") { foreach (var change in message.body.changes) { if (change.mode == "add") { if (change.type == "node") { StructureGraph.Instance.SaveNode(change.entity); } else { StructureGraph.Instance.Merge(change.entity.start, change.entity.end, change.entity, change.entity.type); } } if (change.mode == "upd") { if (change.type == "node") { StructureGraph.Instance.SaveNode(change.entity); } else { StructureGraph.Instance.Merge(change.entity.start, change.entity.end, change.entity, change.entity.type); } } if (change.mode == "del") { if (change.type == "relation") { StructureGraph.Instance.Break(change.entity.start, change.entity.end); } } } var sessions = CacheRepository.Instance.GetSessions(); foreach (var sess in sessions) { var bag = sess as IDictionary <string, object>; if (!bag.ContainsKey(SignalRConnection.SIGNAL_CONNECTION_ID)) { continue; } var connectionId = bag[SignalRConnection.SIGNAL_CONNECTION_ID].ToString(); SignalRConnection.RaiseEvent(message, connectionId); } var answer = Helper.BuildMessage(what); return(answer); } if (what == "rows-get-ids") { string filter = message.body.filter.text; //var groups = (message.body.filter.groups as IEnumerable<string>).Select(i=>Guid.Parse(i)).ToArray(); var groups = new List <Guid>(); foreach (var gid in message.body.filter.groups) { groups.Add(Guid.Parse(gid.ToString())); } dynamic res = StructureGraph.Instance.GetRowIds(filter, groups.ToArray(), userId); var answer = Helper.BuildMessage(what); answer.body.ids = res; return(answer); } if (what == "rows-for-server") { string serverName = message.body.serverName; var ans = Helper.BuildMessage(what); ans.body.server = StructureGraph.Instance.GetServer(serverName, userId); return(ans); } if (what == "row-get-card") { Guid rowId = Guid.Parse(message.body.rowId.ToString()); var abnormals = Data.Cache.Instance.GetLastRecords("Abnormal", new Guid[] { rowId }); var currents = Data.Cache.Instance.GetLastRecords("Current", new Guid[] { rowId }); var constants = Data.Cache.Instance.GetLastRecords("Constant", new Guid[] { rowId }); var dayDate = Data.Cache.Instance.GetLastDate("Day", rowId); var days = (dayDate != DateTime.MinValue) ? Data.RecordsDecorator.Decorate(new[] { rowId }, dayDate, dayDate, "Day", userId).Where(d => d.Date == dayDate) : null; dynamic ans = Helper.BuildMessage(what); try { var fr = StructureGraph.Instance.GetRows(new Guid[] { rowId }, userId).FirstOrDefault(); var dfr = (fr as IDictionary <string, object>); if (dfr.ContainsKey("Area") && (fr.Area is IEnumerable <dynamic>) && (fr.Area as IEnumerable <object>).Any() && (fr.Area[0] is IDictionary <string, object>)) { var obj = fr.Area[0]; var dobj = fr.Area[0] as IDictionary <string, object>; ans.body.addr = dobj.ContainsKey("name")? obj.name : ""; ans.body.number = dobj.ContainsKey("number") ? obj.number : ""; ans.body.address = dobj.ContainsKey("address") ? obj.address : ""; } if (dfr.ContainsKey("Device") && (fr.Device is IEnumerable <dynamic>) && (fr.Device as IEnumerable <object>).Any() && (fr.Device[0] is IDictionary <string, object>)) { var obj = fr.Device[0]; var dobj = fr.Device[0] as IDictionary <string, object>; ans.body.dev = dobj.ContainsKey("name") ? obj.name : ""; } if (dfr.ContainsKey("CsdConnection") && (fr.CsdConnection is IEnumerable <dynamic>) && (fr.CsdConnection as IEnumerable <object>).Any() && (fr.CsdConnection[0] is IDictionary <string, object>)) { var obj = fr.CsdConnection[0]; var dobj = fr.CsdConnection[0] as IDictionary <string, object>; ans.body.phone = dobj.ContainsKey("phone") ? obj.phone : ""; } } catch (Exception exx) { } if (message.body.matrixId != "undefined") { Guid matrixId = Guid.Parse(message.body.matrixId.ToString()); var signalDate = Data.Cache.Instance.GetLastDate("MatrixSignal", matrixId); var signal = Data.Cache.Instance.GetRecords(signalDate, signalDate, "MatrixSignal", new Guid[] { matrixId }); ans.body.signal = signal.Select(c => { dynamic d = new ExpandoObject(); d.date = c.Date; d.level = c.D1; return(d); }); } ans.body.currents = currents.Select(c => { dynamic d = new ExpandoObject(); d.date = c.Date; d.serverDate = c.Dt1; d.name = c.S1; d.unit = c.S2; d.value = c.D1; return(d); }); ans.body.constants = constants.Select(c => { dynamic d = new ExpandoObject(); d.name = c.S1; d.value = c.S2; return(d); }); ans.body.days = days == null ? new List <dynamic> { } : days.Select(c => { dynamic d = new ExpandoObject(); d.date = c.Date; d.name = c.S1; d.unit = c.S2; d.value = c.D1; return(d); }); ans.body.abnormals = abnormals.Select(c => { dynamic d = new ExpandoObject(); d.date = c.Date; d.name = c.S1; return(d); }); return(ans); } if (what == "row-get-card-before20190201") { Guid rowId = Guid.Parse(message.body.rowId.ToString()); var abnormals = Data.Cache.Instance.GetLastRecords("Abnormal", new Guid[] { rowId }); var currents = Data.Cache.Instance.GetLastRecords("Current", new Guid[] { rowId }); var constants = Data.Cache.Instance.GetLastRecords("Constant", new Guid[] { rowId }); var dayDate = Data.Cache.Instance.GetLastDate("Day", rowId); var days = (dayDate != DateTime.MinValue) ? Data.RecordsDecorator.Decorate(new[] { rowId }, dayDate, dayDate, "Day", userId).Where(d => d.Date == dayDate) : null; dynamic ans = Helper.BuildMessage(what); try { var fr = StructureGraph.Instance.GetRows(new Guid[] { rowId }, userId).FirstOrDefault(); var dfr = (fr as IDictionary <string, object>); if (dfr.ContainsKey("Area") && (fr.Area is IEnumerable <dynamic>) && (fr.Area as IEnumerable <object>).Any() && (fr.Area[0] is IDictionary <string, object>)) { var obj = fr.Area[0]; var dobj = fr.Area[0] as IDictionary <string, object>; ans.body.addr = dobj.ContainsKey("name") ? obj.name : ""; ans.body.number = dobj.ContainsKey("number") ? obj.number : ""; ans.body.address = dobj.ContainsKey("address") ? obj.address : ""; } if (dfr.ContainsKey("Device") && (fr.Device is IEnumerable <dynamic>) && (fr.Device as IEnumerable <object>).Any() && (fr.Device[0] is IDictionary <string, object>)) { var obj = fr.Device[0]; var dobj = fr.Device[0] as IDictionary <string, object>; ans.body.dev = dobj.ContainsKey("name") ? obj.name : ""; } if (dfr.ContainsKey("CsdConnection") && (fr.CsdConnection is IEnumerable <dynamic>) && (fr.CsdConnection as IEnumerable <object>).Any() && (fr.CsdConnection[0] is IDictionary <string, object>)) { var obj = fr.CsdConnection[0]; var dobj = fr.CsdConnection[0] as IDictionary <string, object>; ans.body.phone = dobj.ContainsKey("phone") ? obj.phone : ""; } } catch (Exception exx) { } if (message.body.matrixId != "undefined") { Guid matrixId = Guid.Parse(message.body.matrixId.ToString()); var signalDate = Data.Cache.Instance.GetLastDate("MatrixSignal", matrixId); var signal = Data.Cache.Instance.GetRecords(signalDate, signalDate, "MatrixSignal", new Guid[] { matrixId }); ans.body.signal = signal.Select(c => { dynamic d = new ExpandoObject(); d.date = c.Date; d.level = c.D1; return(d); }); } ans.body.currents = currents.Select(c => { dynamic d = new ExpandoObject(); d.date = c.Date; d.serverDate = c.Dt1; d.name = c.S1; d.unit = c.S2; d.value = c.D1; return(d); }); ans.body.constants = constants.Select(c => { dynamic d = new ExpandoObject(); d.name = c.S1; d.value = c.S2; return(d); }); ans.body.days = days == null ? new List <dynamic> { } : days.Select(c => { dynamic d = new ExpandoObject(); d.date = c.Date; d.name = c.S1; d.unit = c.S2; d.value = c.D1; return(d); }); ans.body.abnormals = abnormals.Select(c => { dynamic d = new ExpandoObject(); d.date = c.Date; d.name = c.S1; return(d); }); return(ans); } return(Helper.BuildMessage(what)); }
public async Task <dynamic> Handle(dynamic session, dynamic message) { string what = message.head.what; Guid userId = Guid.Parse(session.userId.ToString()); if (what == "setpoint-event") { var events = CacheRepository.Instance.Get("setpoint-event"); //var events = CacheRepository.Instance.GetLocal("setpoint-event"); var ans = Helper.BuildMessage(what); ans.body.events = events; return(ans); } if (what == "setpoint-recording-rows") { List <Guid> objectIds = new List <Guid>(); foreach (var row in message.body.rows) { Guid id = Guid.Parse((string)row.id); Guid objectId = Guid.Parse((string)row.objectId); DateTime dateStart = DateTime.Parse(row.dateStart.ToString()); string name = row.name.ToString(); double value = Double.Parse(row.value.ToString()); string parameter = row.parameter.ToString(); string tag = row.tag.ToString(); string message1 = row.message.ToString(); double setPoint = Double.Parse(row.setPoint.ToString()); TubeEvent.Instance.CreateRow(dateStart, objectId, message1, parameter, name, value, tag, DateTime.Now, setPoint); } var ans = Helper.BuildMessage(what); return(ans); } if (what == "setpoint-updating-rows") { foreach (var row in message.body.rows) { Guid id = Guid.Parse((string)row.id); DateTime dateEnd = DateTime.Parse(row.dateEnd.ToString()); TubeEvent.Instance.UpdateDateEnd(dateEnd, id); } var ans = Helper.BuildMessage(what); return(ans); } if (what == "setpoint-get-active-events") { List <Guid> objectIds = new List <Guid>(); foreach (var objectId in message.body.objectIds) { objectIds.Add(Guid.Parse(objectId.ToString())); } var rows = TubeEvent.Instance.GetActiveEvents(objectIds); var ans = Helper.BuildMessage(what); ans.body.rows = rows; return(ans); } if (what == "setpoint-get-ids-datestart") { List <Guid> objectIds = new List <Guid>(); foreach (var objectId in message.body.objectIds) { objectIds.Add(Guid.Parse(objectId.ToString())); } DateTime dateStart = DateTime.Parse(message.body.dateStart.ToString()); var rows = TubeEvent.Instance.GetByObjectIdAndDateStart(objectIds, dateStart, userId); var ans = Helper.BuildMessage(what); ans.body.rows = rows; return(ans); } if (what == "setpoint-get-datestart") { DateTime dateStart = DateTime.Parse(message.body.dateStart.ToString()); var rows = TubeEvent.Instance.GetByDateStart(dateStart, userId); var ans = Helper.BuildMessage(what); ans.body.rows = rows; return(ans); } if (what == "setpoint-get-by-date-startend") { DateTime startDate = DateTime.Parse(message.body.startDate.ToString()); DateTime endDate = DateTime.Parse(message.body.endDate.ToString()); var rows = TubeEvent.Instance.GetByDateStartEnd(startDate, endDate, userId); var ans = Helper.BuildMessage(what); ans.body.rows = rows; return(ans); } if (what == "setpoint-get-active-events-all") { //TubeEvent.Instance.GetActiveEvents(new List<Guid>() {Guid.Parse("9E4D2A48-9B0E-474D-A9D3-47FC246C7107") }, userId); var rows = TubeEvent.Instance.GetActiveEventsAll(); var ans = Helper.BuildMessage(what); ans.body.rows = rows; return(ans); } if (what == "setpoint-get-active-events-dateEnd") { //TubeEvent.Instance.GetActiveEvents(new List<Guid>() {Guid.Parse("9E4D2A48-9B0E-474D-A9D3-47FC246C7107") }, userId); var rows = TubeEvent.Instance.GetActiveEventsAllOnlyDateEnd(); var ans = Helper.BuildMessage(what); ans.body.rows = rows; return(ans); } if (what == "setpoint-quit") { Guid id = Guid.Parse((string)message.body.id); TubeEvent.Instance.UpdateDateQuit(DateTime.Now, id); var rows = TubeEvent.Instance.GetById(id, userId); var ans = Helper.BuildMessage(what); ans.body.rows = rows; return(ans); } return(Helper.BuildMessage(what)); }
public async Task <dynamic> Handle(dynamic session, dynamic message) { string what = message.head.what; var userId = Guid.Parse(session.userId.ToString()); if (what == "poll-cancel") { //var sessions = StructureGraph.Instance.GetSessions(); var sessions = CacheRepository.Instance.GetSessions(); foreach (var sess in sessions) { if (sess.id == session.id) { continue; } var bag = sess as IDictionary <string, object>; if (!bag.ContainsKey(SignalRConnection.SIGNAL_CONNECTION_ID)) { continue; } var connectionId = bag[SignalRConnection.SIGNAL_CONNECTION_ID].ToString(); SignalRConnection.RaiseEvent(message, connectionId); } return(Helper.BuildMessage(what)); } if (what.StartsWith("poll-vcom")) { //var sessions = StructureGraph.Instance.GetSessions(); var sessions = CacheRepository.Instance.GetSessions(); foreach (var sess in sessions) { if (sess.id == session.id) { continue; } var bag = sess as IDictionary <string, object>; if (!bag.ContainsKey(SignalRConnection.SIGNAL_CONNECTION_ID)) { continue; } var connectionId = bag[SignalRConnection.SIGNAL_CONNECTION_ID].ToString(); SignalRConnection.RaiseEvent(message, connectionId); } return(Helper.BuildMessage(what)); } if (what == "poll") { //препроцессинг //редиректы var dmessage = message.body as IDictionary <string, object>; if (dmessage.ContainsKey("redirect")) { var objIds = new List <Guid>(); foreach (var objId in message.body.objectIds) { objIds.Add(Guid.Parse(objId)); } message.body.objectIds = StructureGraph.Instance.GetRelatedIds(objIds, message.body.redirect.ToString()); } var sessions = CacheRepository.Instance.GetSessions(); foreach (var sess in sessions) { if (sess.id == session.id) { continue; } var bag = sess as IDictionary <string, object>; if (!bag.ContainsKey(SignalRConnection.SIGNAL_CONNECTION_ID)) { continue; } var connectionId = bag[SignalRConnection.SIGNAL_CONNECTION_ID].ToString(); SignalRConnection.RaiseEvent(message, connectionId); } } if (what == "poll-subscribe") { var bag = session.bag as IDictionary <string, object>; if (!bag.ContainsKey(SUBSCRIBE)) { bag.Add(SUBSCRIBE, new Dictionary <Guid, IEnumerable <Guid> >()); } var old = (Dictionary <Guid, IEnumerable <Guid> >)bag[SUBSCRIBE]; foreach (dynamic subs in message.body.subscribers) { Guid tubeId = subs.id; var sattelites = new List <Guid>(); foreach (Guid satteliteId in subs.sattelites) { sattelites.Add(satteliteId); } if (old.ContainsKey(tubeId)) { old[tubeId] = sattelites; } else { old.Add(tubeId, sattelites); } } session.Bag[SUBSCRIBE] = old; } if (what == "poll-unsubscribe") { var bag = session.bag as IDictionary <string, object>; if (!bag.ContainsKey(SUBSCRIBE)) { bag.Add(SUBSCRIBE, new Dictionary <Guid, IEnumerable <Guid> >()); } var old = (Dictionary <Guid, IEnumerable <Guid> >)bag[SUBSCRIBE]; foreach (dynamic subs in message.body.subscribers) { Guid tubeId = subs.tubeId; if (old.ContainsKey(tubeId)) { old.Remove(tubeId); } } session.Bag[SUBSCRIBE] = old; } if (what == "poll-get-objectid-imeina") { string imei = message.body.imei; string networkaddress = $"{message.body.networkaddress}"; var objectId = StructureGraph.Instance.GetTubeIdFromIMEIandNetworkAddress(imei, networkaddress); var answer = Helper.BuildMessage(what); answer.body.objectId = objectId; return(answer); } if (what == "poll-get-objectid-imeina-matrixterminal") { string imei = message.body.imei; string networkaddress = $"{message.body.networkaddress}"; var objectId = StructureGraph.Instance.GetTubeIdFromIMEIandNAMatrixTerminal(imei, networkaddress); var answer = Helper.BuildMessage(what); answer.body.objectId = objectId; return(answer); } if (what == "poll-set-light-astronomtimer") { byte afterSunSet = Byte.Parse(message.body.afterBeforeSunSetRise[0]); byte beforeSunRise = Byte.Parse(message.body.afterBeforeSunSetRise[1]); Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture; byte u8timeDiff = Byte.Parse(message.body.utc); double dLatitude = Double.Parse(((string)message.body.coordinates[0]).Replace(',', '.')); UInt32 latitude = (UInt32)(dLatitude * 10000000); double dLongitude = Double.Parse(((string)message.body.coordinates[1]).Replace(',', '.')); UInt32 longitude = (UInt32)(dLongitude * 10000000); string cmd = "setAstronTimer"; List <byte> listSetAstronom = new List <byte>(); listSetAstronom.Add(u8timeDiff); byte[] u32Lat = BitConverter.GetBytes(latitude); listSetAstronom.AddRange(u32Lat); byte[] u32Lon = BitConverter.GetBytes(longitude); listSetAstronom.AddRange(u32Lon); listSetAstronom.Add(afterSunSet); listSetAstronom.Add(beforeSunRise); dynamic msg = new ExpandoObject(); msg = Helper.BuildMessage("poll"); msg.head.sessionId = message.head.sessionId; msg.body.objectIds = new string[] { (string)message.body.objectId }; msg.body.what = "all"; msg.body.arg = new ExpandoObject(); msg.body.arg.components = "Current"; msg.body.arg.onlyHoles = false; msg.body.arg.cmd = cmd + BitConverter.ToString(listSetAstronom.ToArray()); var sessions = CacheRepository.Instance.GetSessions(); foreach (var sess in sessions) { if (sess.id == session.id) { continue; } var bag = sess as IDictionary <string, object>; if (!bag.ContainsKey(SignalRConnection.SIGNAL_CONNECTION_ID)) { continue; } var connectionId = bag[SignalRConnection.SIGNAL_CONNECTION_ID].ToString(); SignalRConnection.RaiseEvent(msg, connectionId); } } if (what == "poll-light-control-config") { var lightControlMetod = message.body.lightControlMetod; var afterSunSetAndBeforeSunRise = message.body.afterSunSetAndBeforeSunRise; var lightSheduleOn = message.body.lightSheduleOn; var lightSheduleOff = message.body.lightSheduleOff; DateTime dt1970 = new DateTime(1970, 1, 1, 0, 0, 0); Guid id = Guid.Parse(message.body.objectId.ToString()); dynamic tube = StructureGraph.Instance.GetTube(id, userId); string strConfig = (string)tube.strConfig; var bytesConfig = strConfig.Split('-').Select(x => byte.Parse(x, NumberStyles.HexNumber)).ToArray(); LightConfig conf = StructsHelper.Instance.setBytesFromConfig <LightConfig>(bytesConfig, new LightConfig()); string cmd = "setAstronTimer"; if (lightControlMetod.Count > 0 && lightControlMetod[0] != null) { conf.ligthtChannels1.u8ControlMode = Convert.ToByte(lightControlMetod[0]); } conf.ligthtChannels1.u8afterSunSet = Convert.ToByte(afterSunSetAndBeforeSunRise[0][0]); conf.ligthtChannels1.u8beforeSunRise = Convert.ToByte(afterSunSetAndBeforeSunRise[0][1]); conf.ligthtChannels1.on1 = lightChannelOnOff(lightSheduleOn[0][0]); conf.ligthtChannels1.on2 = lightChannelOnOff(lightSheduleOn[0][1]); //------------------ conf.ligthtChannels1.off1 = lightChannelOnOff(lightSheduleOff[0][0]); //--------------------- conf.ligthtChannels1.off2 = lightChannelOnOff(lightSheduleOff[0][1]); if (lightControlMetod.Count > 1 && lightControlMetod[1] != null) { conf.ligthtChannels2.u8ControlMode = Convert.ToByte(lightControlMetod[1]); } conf.ligthtChannels2.u8afterSunSet = Convert.ToByte(afterSunSetAndBeforeSunRise[1][0]); conf.ligthtChannels2.u8beforeSunRise = Convert.ToByte(afterSunSetAndBeforeSunRise[1][1]); conf.ligthtChannels2.on1 = lightChannelOnOff(lightSheduleOn[1][0]); conf.ligthtChannels2.on2 = lightChannelOnOff(lightSheduleOn[1][1]); conf.ligthtChannels2.off1 = lightChannelOnOff(lightSheduleOff[1][0]); conf.ligthtChannels2.off2 = lightChannelOnOff(lightSheduleOff[1][1]); if (lightControlMetod.Count > 2 && lightControlMetod[2] != null) { conf.ligthtChannels3.u8ControlMode = Convert.ToByte(lightControlMetod[2]); } conf.ligthtChannels3.u8afterSunSet = Convert.ToByte(afterSunSetAndBeforeSunRise[2][0]); conf.ligthtChannels3.u8beforeSunRise = Convert.ToByte(afterSunSetAndBeforeSunRise[2][1]); conf.ligthtChannels3.on1 = lightChannelOnOff(lightSheduleOn[2][0]); conf.ligthtChannels3.on2 = lightChannelOnOff(lightSheduleOn[2][1]); conf.ligthtChannels3.off1 = lightChannelOnOff(lightSheduleOff[2][0]); conf.ligthtChannels3.off2 = lightChannelOnOff(lightSheduleOff[2][1]); if (lightControlMetod.Count > 3 && lightControlMetod[3] != null) { conf.ligthtChannels4.u8ControlMode = Convert.ToByte(lightControlMetod[3]); } conf.ligthtChannels4.u8afterSunSet = Convert.ToByte(afterSunSetAndBeforeSunRise[3][0]); conf.ligthtChannels4.u8beforeSunRise = Convert.ToByte(afterSunSetAndBeforeSunRise[3][1]); conf.ligthtChannels4.on1 = lightChannelOnOff(lightSheduleOn[3][0]); conf.ligthtChannels4.on2 = lightChannelOnOff(lightSheduleOn[3][1]); conf.ligthtChannels4.off1 = lightChannelOnOff(lightSheduleOff[3][0]); conf.ligthtChannels4.off2 = lightChannelOnOff(lightSheduleOff[3][1]); byte[] outByte = StructsHelper.Instance.getBytes <LightConfig>(conf); dynamic msg = new ExpandoObject(); msg = Helper.BuildMessage("poll"); msg.head.sessionId = message.head.sessionId; msg.body.objectIds = new string[] { (string)message.body.objectId }; msg.body.what = "all"; msg.body.arg = new ExpandoObject(); msg.body.arg.components = "Current"; msg.body.arg.onlyHoles = false; msg.body.arg.cmd = cmd + BitConverter.ToString(outByte); var sessions = CacheRepository.Instance.GetSessions(); foreach (var sess in sessions) { if (sess.id == session.id) { continue; } var bag = sess as IDictionary <string, object>; if (!bag.ContainsKey(SignalRConnection.SIGNAL_CONNECTION_ID)) { continue; } var connectionId = bag[SignalRConnection.SIGNAL_CONNECTION_ID].ToString(); SignalRConnection.RaiseEvent(msg, connectionId); } } var ans = Helper.BuildMessage("poll-accepted"); return(ans); }
public async Task <dynamic> Handle(dynamic session, dynamic message) { string what = message.head.what; Guid userId = Guid.Parse(session.userId.ToString()); if (what == "export-ids") { var ids = Data.StructureGraph.Instance.GetRowIds("", new Guid[] { }, userId); var ans = Helper.BuildMessage(what); ans.body.ids = ids; return(ans); } if (what == "export-watertower") { var answer = Helper.BuildMessage(what); Guid objectId = Guid.Parse((string)message.body.objectId); var tube = StructureGraph.Instance.GetTube(objectId, userId); var dtube = tube as IDictionary <string, object>; if (dtube.ContainsKey("criticalMax")) { answer.body.criticalMax = tube.criticalMax.ToString().Replace(',', '.'); } if (dtube.ContainsKey("controlMode")) { answer.body.controlMode = tube.controlMode; } if (dtube.ContainsKey("criticalMin")) { answer.body.criticalMin = tube.criticalMin.ToString().Replace(',', '.');; } if (dtube.ContainsKey("max")) { answer.body.max = tube.max.ToString().Replace(',', '.');; } if (dtube.ContainsKey("min")) { answer.body.min = tube.min.ToString().Replace(',', '.');; } if (dtube.ContainsKey("interval")) { answer.body.interval = tube.interval.ToString().Replace(',', '.');; } return(answer); } if (what == "export-names") { var names = new List <dynamic>(); Func <dynamic, dynamic> toName = (d) => { var dd = d as IDictionary <string, object>; dynamic name = new ExpandoObject(); name.id = d.id; name.device = ""; if (dd.ContainsKey("Device") && d.Device is IEnumerable <dynamic> ) { name.device = d.Device[0].name; } name.name = ""; if (dd.ContainsKey("Area") && d.Area is IEnumerable <dynamic> ) { var area = d.Area[0]; var darea = area as IDictionary <string, object>; if (darea.ContainsKey("name")) { name.name += area.name + " "; } if (darea.ContainsKey("city")) { name.name += area.city + " "; } if (darea.ContainsKey("street")) { name.name += area.street + " "; } if (darea.ContainsKey("house")) { name.name += area.house + " "; } } if (dd.ContainsKey("name")) { name.name += d.name + " "; } return(name); }; var nonCachedIds = new List <Guid>(); foreach (var rid in message.body.ids) { Guid id = Guid.Parse(rid.ToString()); var cachedRow = CacheRepository.Instance.Get("row", id); //var cachedRow = CacheRepository.Instance.GetLocal("row", id); if (cachedRow == null) { nonCachedIds.Add(id); continue; } names.Add(toName(cachedRow)); } var rows = StructureGraph.Instance.GetRows(nonCachedIds, userId); foreach (var row in rows) { var id = Guid.Parse(row.id.ToString()); CacheRepository.Instance.Set("row", id, row); //CacheRepository.Instance.SetLocal("row", id, row); names.Add(toName(row)); } var ans = Helper.BuildMessage(what); ans.body.names = names; return(ans); } if (what == "export-values") { var ans = Helper.BuildMessage(what); bool isAll = false; List <Guid> fiasIds = new List <Guid>(); if ((message.body as IDictionary <string, object>).ContainsKey("fiasIds")) { if ((message.body.fiasIds is string) && (message.body.fiasIds == "*")) { isAll = true; } else if (message.body.fiasIds is IEnumerable <object> ) { foreach (object fiasId in (message.body.fiasIds as IEnumerable <object>)) { Guid id = new Guid(fiasId.ToString()); fiasIds.Add(id); } } } IDictionary <Guid, ExportValue> exportData = new Dictionary <Guid, ExportValue>(); if (isAll || (fiasIds.Count > 0)) { var rows = StructureGraph.Instance.GetRowsFias(fiasIds, userId); foreach (var row in rows) { exportData[row.Key] = new ExportValue { id = row.Value.Id, fiasId = row.Value.FiasId, address = row.Value.Address, name = row.Value.Name, resource = row.Value.Resource, lastRecords = new List <ExportRecord>() }; } var records = RecordsDecorator.DecorateLast(exportData.Keys.ToArray(), "Current", userId); foreach (var record in records) { exportData[record.ObjectId].lastRecords.Add(new ExportRecord { parameter = record.S1, value = record.D1 ?? 0.0, unit = record.S2, date = record.Date, dt = record.Dt1 ?? DateTime.MinValue }); } } ans.body.allIds = isAll; ans.body.fiasIds = fiasIds; ans.body.data = exportData.Values.ToList(); return(ans); } if (what == "export-data") { var sw = new Stopwatch(); string type = message.body.type; DateTime start = message.body.start; DateTime end = message.body.end; var data = new List <dynamic>(); var ids = new List <Guid>(); foreach (var id in message.body.ids) { ids.Add(Guid.Parse(id.ToString())); } var records = RecordsDecorator.Decorate(ids.ToArray(), start, end, type, userId); foreach (var id in ids) { foreach (var group in records.Where(r => r.ObjectId == id).GroupBy(r => r.Date)) { dynamic rec = new ExpandoObject(); rec.date = group.Key; rec.objectId = id; var drec = rec as IDictionary <string, object>; foreach (var record in group) { var unit = record.S2; var val = record.D1; if (thousand.Contains(unit)) { val *= 1000.0; } var name = record.S1.Replace(".", "").Replace(" ", ""); if (!drec.ContainsKey(name)) { drec.Add(name, val); } } data.Add(rec); } } var ans = Helper.BuildMessage(what); ans.body.data = data; return(ans); } return(Helper.BuildMessage(what)); }
public async Task <dynamic> Handle(dynamic session, dynamic message) { string what = message.head.what; Guid userId = Guid.Parse(session.userId.ToString()); #region edit if (what == "edit") { var relations = new List <dynamic>(); var nodes = new List <dynamic>(); var tubeIds = new List <Guid>(); foreach (var rule in message.body.rules) { string action = rule.action; string target = rule.target; dynamic content = rule.content; if (target == TARGET_RELATION) { relations.Add(rule); } if (target == TARGET_NODE) { nodes.Add(rule); } } var audit = new List <DataRecord>(); var ids = new List <Guid>(); //Удаление 1.Связей и 2.Нодов foreach (var rule in relations.Union(nodes)) { string action = rule.action; if (action == ACTION_DEL) { string target = rule.target; dynamic content = rule.content; if (target == TARGET_RELATION) { Guid start = Guid.Parse(content.start.ToString()); Guid end = Guid.Parse(content.end.ToString()); ids.Add(start); ids.Add(end); string type = content.type; dynamic body = content.body; body.type = type; var leftTubes = StructureGraph.Instance.GetRelatedTubs(start); var rightTubes = StructureGraph.Instance.GetRelatedTubs(end); var relatedTubes = leftTubes.Union(rightTubes).Distinct(); //var relatedTubes = StructureGraph.Instance.GetRelatedTubs(end); //if (action == ACTION_DEL) { StructureGraph.Instance.DelRelation(start, end, type, userId); var st = StructureGraph.Instance.GetNodeById(start, userId); var ed = StructureGraph.Instance.GetNodeById(end, userId); if (st.type == "Folder" && ed.type == "Folder") { audit.AddRange(MakeAudit(string.Format("группа {0} удалена из группы {1}", ed.name, st.name), userId, relatedTubes, Guid.Parse(ed.id.ToString()))); } else if (st.type == "Folder" && ed.type == "Area") { audit.AddRange(MakeAudit(string.Format("плошадка {0} удалена из группы {1}", ed.name, st.name), userId, relatedTubes, Guid.Parse(ed.id.ToString()))); } else if (st.type == "Tube" && ed.type == "MatrixConnection") { audit.AddRange(MakeAudit(string.Format("контроллер матрикс {0} отвязан от объекта {1}", ed.imei, st.id), userId, relatedTubes, Guid.Parse(ed.id.ToString()))); } else if (st.type == "Tube" && ed.type == "CsdConnection") { audit.AddRange(MakeAudit(string.Format("модем или контроллер СТЕЛ {0} отвязан от объекта {1}", ed.phone, st.id), userId, relatedTubes, Guid.Parse(ed.id.ToString()))); } else if (st.type == "Tube" && ed.type == "LanConnection") { audit.AddRange(MakeAudit(string.Format("ethernet контроллер {0}:{1} отвязан от объекта {2}", ed.host, ed.port, st.id), userId, relatedTubes, Guid.Parse(ed.id.ToString()))); } else { audit.AddRange(MakeAudit(string.Format("удалено соединение {0} -> {1}", st.id, Guid.Parse(ed.id.ToString())), userId, relatedTubes, Guid.Parse(ed.id.ToString()))); } } } else if (target == TARGET_NODE) { Guid id = Guid.Parse(content.id.ToString()); ids.Add(id); string type = content.type; dynamic body = content.body; //NamesCache.Instance.Update(body, userId); if (type == "Tube") { tubeIds.Add(id); } var relatedTubes = StructureGraph.Instance.GetRelatedTubs(id); { StructureGraph.Instance.DelNode(id, type, userId); //var st = StructureGraph.Instance.GetNodeById(start, userId); //var ed = StructureGraph.Instance.GetNodeById(end, userId); if (body.type == "Folder") { audit.AddRange(MakeAudit(string.Format("группа {0} удалена", body.name), userId, relatedTubes, Guid.Parse(body.id.ToString()))); } else { audit.AddRange(MakeAudit(string.Format("нод {0} удален", body.id), userId, relatedTubes, Guid.Parse(body.id.ToString()))); } } } } } //Добавление или Изменение 1.Нодов и 2.Связей foreach (var rule in nodes.Union(relations)) { string action = rule.action; string target = rule.target; dynamic content = rule.content; if ((action == ACTION_ADD) || (action == ACTION_UPD)) { if (target == TARGET_RELATION) { Guid start = Guid.Parse(content.start.ToString()); Guid end = Guid.Parse(content.end.ToString()); ids.Add(start); ids.Add(end); string type = content.type; dynamic body = content.body; body.type = type; var leftTubes = StructureGraph.Instance.GetRelatedTubs(start); var rightTubes = StructureGraph.Instance.GetRelatedTubs(end); var relatedTubes = leftTubes.Union(rightTubes).Distinct(); //var relatedTubes = StructureGraph.Instance.GetRelatedTubs(end); if (action == ACTION_ADD) { StructureGraph.Instance.AddOrUpdRelation(start, end, type, body, userId); var st = StructureGraph.Instance.GetNodeById(start, userId); //F4E311F5-35E6-4E35-90D5-BA85F1A315CB var ed = StructureGraph.Instance.GetNodeById(end, userId); //f4e311f5-35e6-4e35-90d5-ba85f1a315cb if (st.type == "Folder" && ed.type == "Folder") { audit.AddRange(MakeAudit(string.Format("группа {0} добавлена в группу {1}", ed.name, st.name), userId, relatedTubes, Guid.Parse(ed.id.ToString()))); } else if (st.type == "Folder" && ed.type == "Area") { audit.AddRange(MakeAudit(string.Format("плошадка {0} добавлена в группу {1}", ed.name, st.name), userId, relatedTubes, Guid.Parse(ed.id.ToString()))); } else if (st.type == "Tube" && ed.type == "MatrixConnection") { audit.AddRange(MakeAudit(string.Format("контроллер матрикс {0} привязан к объекту {1}", ed.imei, st.id), userId, relatedTubes, Guid.Parse(ed.id.ToString()))); } else if (st.type == "Tube" && ed.type == "CsdConnection") { audit.AddRange(MakeAudit(string.Format("модем или контроллер СТЕЛ {0} привязан к объекту {1}", ed.phone, st.id), userId, relatedTubes, Guid.Parse(ed.id.ToString()))); } else if (st.type == "Tube" && ed.type == "LanConnection") { audit.AddRange(MakeAudit(string.Format("ethernet контроллер {0}:{1} привязан к объекту {2}", ed.host, ed.port, st.id), userId, relatedTubes, Guid.Parse(ed.id.ToString()))); } else { audit.AddRange(MakeAudit(string.Format("добавлено соединение {0} -> {1}", st.id, Guid.Parse(ed.id.ToString())), userId, relatedTubes, Guid.Parse(ed.id.ToString()))); } } else if (action == ACTION_UPD) { StructureGraph.Instance.AddOrUpdRelation(start, end, type, body, userId); var st = StructureGraph.Instance.GetNodeById(start, userId); var ed = StructureGraph.Instance.GetNodeById(end, userId); if (st.type == "Folder" && ed.type == "Folder") { audit.AddRange(MakeAudit(string.Format("группа {0} добавлена в группу {1}", ed.name, st.name), userId, relatedTubes, Guid.Parse(ed.id.ToString()))); } else if (st.type == "Folder" && ed.type == "Area") { audit.AddRange(MakeAudit(string.Format("плошадка {0} добавлена в группу {1}", ed.name, st.name), userId, relatedTubes, Guid.Parse(ed.id.ToString()))); } else if (st.type == "Tube" && ed.type == "MatrixConnection") { audit.AddRange(MakeAudit(string.Format("контроллер матрикс {0} привязан к объекту {1}", ed.imei, st.id), userId, relatedTubes, Guid.Parse(ed.id.ToString()))); } else if (st.type == "Tube" && ed.type == "CsdConnection") { audit.AddRange(MakeAudit(string.Format("модем или контроллер СТЕЛ {0} привязан к объекту {1}", ed.phone, st.id), userId, relatedTubes, Guid.Parse(ed.id.ToString()))); } else if (st.type == "Tube" && ed.type == "LanConnection") { audit.AddRange(MakeAudit(string.Format("ethernet контроллер {0}:{1} привязан к объекту {2}", ed.host, ed.port, st.id), userId, relatedTubes, Guid.Parse(ed.id.ToString()))); } else { audit.AddRange(MakeAudit(string.Format("обновлено соединение {0} -> {1}", st.id, Guid.Parse(ed.id.ToString())), userId, relatedTubes, Guid.Parse(ed.id.ToString()))); } } } else if (target == TARGET_NODE) { Guid id = Guid.Parse(content.id.ToString()); ids.Add(id); string type = content.type; dynamic body = content.body; //NamesCache.Instance.Update(body, userId); if (type == "Tube") { tubeIds.Add(id); } else if (type == "Area") { if ((body as IDictionary <string, object>).ContainsKey("addr") && (body.addr is string) && ((body.addr as string) != null) && ((body.addr as string) != "")) { body.city = ""; body.street = ""; body.house = ""; body.fiasid = ""; body.address = ""; var response = api.QueryAddress(body.addr as string); if (response != null && response.suggestions.Count > 0) { var result = response.suggestions.FirstOrDefault().data; body.city = result.city_with_type ?? ""; body.street = result.street_with_type ?? ""; body.house = result.house ?? ""; body.fiasid = result.house_fias_id ?? ""; body.address = $"{body.city}, {body.street}, {body.house}"; } } } var relatedTubes = StructureGraph.Instance.GetRelatedTubs(id); if (action == ACTION_ADD) { StructureGraph.Instance.AddNode(id, type, body, userId); var ser = JsonConvert.SerializeObject(body).Replace(@"/""", "'"); if (body.type == "Folder") { audit.AddRange(MakeAudit(string.Format("добавлена группа ({0})", ser), userId, relatedTubes, id)); } else if (body.type == "Area") { audit.AddRange(MakeAudit(string.Format("добавлена площадка учета ({0})", ser), userId, relatedTubes, id)); } else if (body.type == "Tube") { audit.AddRange(MakeAudit(string.Format("добавлена точка учета ({0})", ser), userId, relatedTubes, id)); } else if (body.type == "CsdConnection") { audit.AddRange(MakeAudit(string.Format("добавлено модемное соединение ({0})", ser), userId, relatedTubes, id)); } else if (body.type == "MatrixConnection") { audit.AddRange(MakeAudit(string.Format("добавлено соединение matrix ({0})", ser), userId, relatedTubes, id)); } else { audit.AddRange(MakeAudit(string.Format("добавлен объект {0}", ser), userId, relatedTubes, id)); } } else if (action == ACTION_UPD) { StructureGraph.Instance.UpdNode(id, type, body, userId); var ser = JsonConvert.SerializeObject(body).Replace(@"/""", "'"); if (body.type == "Folder") { audit.AddRange(MakeAudit(string.Format("обновлена группа ({0})", ser), userId, relatedTubes, id)); } else if (body.type == "Area") { audit.AddRange(MakeAudit(string.Format("обновлена площадка учета ({0})", ser), userId, relatedTubes, id)); } else if (body.type == "Tube") { audit.AddRange(MakeAudit(string.Format("обновлена точка учета ({0})", ser), userId, relatedTubes, id)); } else if (body.type == "CsdConnection") { audit.AddRange(MakeAudit(string.Format("обновлено модемное соединение ({0})", ser), userId, relatedTubes, id)); } else if (body.type == "MatrixConnection") { audit.AddRange(MakeAudit(string.Format("обновлено соединение matrix ({0})", ser), userId, relatedTubes, id)); } else { audit.AddRange(MakeAudit(string.Format("обновлен объект {0}", ser), userId, relatedTubes, id)); } } } } } foreach (var node in nodes) { NamesCache.Instance.Update(node.content.body, userId); } Cache.Instance.SaveRecords(audit); RowsCache.Instance.UpdateRow(tubeIds, userId); ids.Distinct().ToList().ForEach(id => CacheRepository.Instance.Del("row", id)); var sessions = CacheRepository.Instance.GetSessions(); sessions.AsParallel().ForAll(s => { var ds = s as IDictionary <string, object>; if (ds == null || !ds.ContainsKey(SignalRConnection.SIGNAL_CONNECTION_ID) || ds[SignalRConnection.SIGNAL_CONNECTION_ID] == null) { return; } Guid uId = Guid.Parse(s.userId.ToString()); dynamic msg = Helper.BuildMessage("changes"); msg.body.rules = new List <dynamic>(); foreach (var rule in message.body.rules) { string target = rule.target; dynamic content = rule.content; Guid id = Guid.Empty; if (target == TARGET_RELATION) { id = Guid.Parse(content.end.ToString()); } else if (target == TARGET_NODE) { id = Guid.Parse(content.id.ToString()); } if (id != Guid.Empty && StructureGraph.Instance.CanSee(id, uId)) { msg.body.rules.Add(rule); } } if (msg.body.rules.Count > 0) { var connectionId = ds[SignalRConnection.SIGNAL_CONNECTION_ID].ToString(); SignalRConnection.RaiseEvent(msg, connectionId); } }); } #endregion if (what == "edit-get-connections") { string filter = message.body.filter; var types = new List <string>(); foreach (string type in message.body.types) { types.Add(type); } var dbody = message.body as IDictionary <string, object>; Guid startId = Guid.Empty; //if (dbody.ContainsKey("startId")) //{ // startId = Guid.Parse(message.body.startId.ToString()); //} var answer = Helper.BuildMessage(what); //StructureGraph.Instance.GetNeightbours(startId, userId); answer.body.connections = StructureGraph.Instance.GetConnections(filter, types, userId); return(answer); } if (what == "edit-get-wave") { Guid startId = Guid.Parse(message.body.startId.ToString()); var answer = Helper.BuildMessage(what); answer.body.wave = StructureGraph.Instance.GetNeightbours(startId, userId); return(answer); } if (what == "edit-get-devices") { var answer = Helper.BuildMessage(what); answer.body.devices = StructureGraph.Instance.GetDevices(); return(answer); } if (what == "edit-get-fias") { var answer = Helper.BuildMessage(what); string queryText = ""; if ((message.body as IDictionary <string, object>).ContainsKey("searchText")) { queryText = message.body.searchText; } AddressSuggestQuery asquery = new AddressSuggestQuery(queryText); if ((message.body as IDictionary <string, object>).ContainsKey("searchFias")) { string queryFias = message.body.searchFias; AddressData addrData = new AddressData(); addrData.fias_id = queryFias; asquery.locations = new AddressData[] { addrData }; } var response = api.QueryAddress(asquery); if (response == null) { throw new Exception("Сервис подсказок недоступен"); } var results = new List <dynamic>(); foreach (var suggest in response.suggestions) { dynamic result = new ExpandoObject(); result.value = suggest.value; result.fiasid = suggest.data.fias_id; result.fiaslvl = suggest.data.fias_level; result.housefiasid = suggest.data.house_fias_id; results.Add(result); } answer.body.results = results; return(answer); } if (what == "edit-get-row") { var answer = Helper.BuildMessage(what); Guid id; if (message.body.isNew) { answer.body.area = new ExpandoObject(); answer.body.area.id = Guid.NewGuid(); answer.body.area.type = "Area"; answer.body.tube = new ExpandoObject(); answer.body.tube.id = Guid.NewGuid(); answer.body.tube.type = "Tube"; } else { id = Guid.Parse(message.body.id.ToString()); answer.body.area = StructureGraph.Instance.GetArea(id, userId); answer.body.tube = StructureGraph.Instance.GetTube(id, userId); answer.body.areaIsNew = false; if (answer.body.tube != null && answer.body.area == null) { answer.body.area = new ExpandoObject(); answer.body.area.id = Guid.NewGuid(); answer.body.area.type = "Area"; answer.body.areaIsNew = true; } answer.body.device = StructureGraph.Instance.GetTubeDevice(id, userId); answer.body.Tube = StructureGraph.Instance.GetHouseTubes(id, userId); //answer.body.connections = StructureGraph.Instance.GetTubeConnections(id, userId); answer.body.relations = StructureGraph.Instance.GetTubeRelations(id, userId); } answer.body.devices = StructureGraph.Instance.GetDevices(); //answer.body.ports = StructureGraph.Instance.GetPollPorts(userId); return(answer); } //if (what == "edit-get-house") //{ // var answer = Helper.BuildMessage(what); // Guid id; // if (message.body.isNew) // { // answer.body.area = new ExpandoObject(); // answer.body.area.id = Guid.NewGuid(); // answer.body.area.type = "Area"; // answer.body.tube = new ExpandoObject(); // answer.body.tube.id = Guid.NewGuid(); // answer.body.tube.type = "Tube"; // } // else // { // id = Guid.Parse(message.body.id.ToString()); // answer.body.area = StructureGraph.Instance.GetArea(id, userId); // answer.body.tube = StructureGraph.Instance.GetTube(id, userId); // answer.body.device = StructureGraph.Instance.GetTubeDevice(id, userId); // answer.body.relations = StructureGraph.Instance.GetTubeRelations(id, userId); // } // return answer; //} if (what == "edit-get-folder") { var answer = Helper.BuildMessage(what); Guid id; if (message.body.isNew) { answer.body.folderNew = new ExpandoObject(); answer.body.folderNew.id = Guid.NewGuid(); answer.body.folderNew.type = "Folder"; //answer.body.connections = new List<object>(); } if (message.body.id != null) { id = Guid.Parse(message.body.id.ToString()); dynamic pack = StructureGraph.Instance.GetFolder(id, userId); answer.body.folder = pack.folder; answer.body.parent = pack.parent; } return(answer); } if (what == "edit-get-folder-id") { var folderId = Guid.Parse((string)message.body.id); // var folder = StructureGraph.Instance.GetFolderById(folderId, userId); // var answer = Helper.BuildMessage(what); answer.body.folder = folder; return(answer); } if (what == "edit-get-folders-id") { var folders = new List <dynamic>(); foreach (string sid in message.body.ids) { var folderId = Guid.Parse(sid); var folder = StructureGraph.Instance.GetFolderById(folderId, userId); folders.Add(folder); } var answer = Helper.BuildMessage(what); answer.body.folders = folders; return(answer); } if (what == "edit-get-branch") { var answer = Helper.BuildMessage(what); Guid id = Guid.Parse(message.body.id.ToString()); answer.body.branch = StructureGraph.Instance.GetServerBranch(id, userId); return(answer); } if (what == "edit-get-area-id") { var answer = Helper.BuildMessage(what); Guid id = Guid.Parse(message.body.id.ToString()); answer.body.areaId = StructureGraph.Instance.GetIdAreaForTube(id, userId); return(answer); } if (what == "edit-get-area") { var answer = Helper.BuildMessage(what); Guid id = Guid.Parse(message.body.id.ToString()); answer.body.area = StructureGraph.Instance.GetArea(id, userId); return(answer); } if (what == "edit-get-name-area") { var answer = Helper.BuildMessage(what); var ids = message.body.ids; var areas = new List <string>(); foreach (var id in ids) { Guid guid = Guid.Parse(id.ToString()); var area = StructureGraph.Instance.GetArea(guid, userId); if (area != null) { areas.Add(area.name); } } answer.body.areas = areas.ToArray(); return(answer); } if (what == "edit-get-tasks") { var answer = Helper.BuildMessage(what); var tasks = StructureGraph.Instance.GetNodesByType("Task", Guid.Parse(session.userId.ToString())); answer.body.tasks = tasks; return(answer); } if (what == "edit-delate-tube") { var answer = Helper.BuildMessage(what); if (message.body.objectIds == null) { return(answer); } List <Guid> listObjectIds = new List <Guid>(); foreach (var objectId in message.body.objectIds) { Guid id = Guid.Parse(objectId.ToString()); StructureGraph.Instance.DelAllRelationObjects(id, userId); if (StructureGraph.Instance.DelObject(id, userId)) { listObjectIds.Add(id); } } if (listObjectIds.Any()) { Data.Cache.Instance.DeleteRow(listObjectIds); } } if (what == "edit-disable-tube") { Guid id = Guid.Parse(message.body.id.ToString()); var tube = StructureGraph.Instance.GetTube(id, userId); tube.isDisabled = true; StructureGraph.Instance.UpdNode(id, "Tube", tube, userId); NamesCache.Instance.Update(tube, userId); } return(Helper.BuildMessage(what)); }
public async Task <dynamic> Handle(dynamic session, dynamic message) { string what = message.head.what; if (what == "reports-list") { var answer = Helper.BuildMessage(what); //answer.body. var reports = StructureGraph.Instance.GetNodesByType("Report", Guid.Parse(session.userId.ToString())); answer.body.reports = reports; return(answer); } //if (what == "reports-names") //{ // var answer = Helper.BuildMessage(what); // answer.body.reports = new JArray(); // var entities = Cache.Instance.GetEntities(session.User); // foreach (var report in entities.OfType<Report>()) // { // dynamic rep = new JObject(); // rep.id = report.Id; // rep.name = report.Name; // answer.body.reports.Add(rep); // } // return answer; //} if (what == "reports-save") { //var tokens = new List<dynamic>(); var userId = Guid.Parse((string)session.userId); foreach (var report in message.body.reports) { //dynamic token = new ExpandoObject(); //token.action = "save"; report.type = "Report"; //token.start = report; //token.userId = userId; //tokens.Add(token); StructureGraph.Instance.SaveSingle(report, userId); } //Data.NodeBackgroundProccessor.Instance.AddTokens(tokens); return(Helper.BuildMessage(what)); } if (what == "report-build") { #if (NEWREPORTS) try { message.session = session; var r = await bus.SyncSend(Bus.REPORTS_EXCHANGE, message); logger.Debug("ушел отчет"); return(r); } catch (Exception ex) { logger.Error(ex, "отчет не построен"); return(null); } #endif Guid reportId = Guid.Parse((string)message.body.report); //dynamic model = new ExpandoObject(); var targets = new List <Guid>(); foreach (var t in message.body.targets) { if (t is string) { targets.Add(Guid.Parse((string)t)); } else if ((t is IDictionary <string, object>) && (t as IDictionary <string, object>).ContainsKey("id") && (t.id is string)) { targets.Add(Guid.Parse((string)t.id)); } else { throw new NotSupportedException(); } } //model.targets = StructureGraph.Instance.GetRows(targets, Guid.Parse((string)session.userId)).ToArray(); //model.start = message.body.start; //model.end = message.body.end; var result = Build(reportId, targets, (DateTime)message.body.start, (DateTime)message.body.end, Guid.Parse((string)session.userId), session); //var report = StructureGraph.Instance.GetNodeById(reportId, Guid.Parse((string)session.userId));// (Report)Cache.Instance.GetById(reportId, session.User); //var result = Reports.Mapper.Instance.Map(model, report.template, session); var answer = Helper.BuildMessage(what); answer.body.report = result.render; answer.body.options = result.build; return(answer); } if (what == "report-export") { #if (NEWREPORTS) return(await bus.SyncSend(Bus.REPORTS_EXCHANGE, message)); #else string type = message.body.type; string wayToPictures = ConfigurationManager.AppSettings["way_pictures"]; // путь для рисунков в отчетах(печать и тд) string text = message.body.text; string fullText = ""; bool isOrientationAlbum = ((message.body as IDictionary <string, object>).ContainsKey("isOrientationAlbum")) && (message.body.isOrientationAlbum is bool) && (message.body.isOrientationAlbum == true); if (text.Contains("\\img\\image")) { int indexImg = text.IndexOf("\\img\\image"); fullText = text.Insert(indexImg, wayToPictures); } else { fullText = text; } byte[] bytes = Html2PdfConvertor.Instance.Convert(fullText, isOrientationAlbum: isOrientationAlbum); logger.Debug("отчет конвертирован в pdf {0} байт", bytes.Length); //var p = new Pechkin.SimplePechkin(new Pechkin.GlobalConfig() { }); //var bytes = p.Convert(text); var answer = Helper.BuildMessage(what); answer.body.bytes = bytes; return(answer); #endif } if (what == "report-mail-send") { var ans = Helper.BuildMessage(what); try { var reportsId = Guid.Parse((string)message.body.reportid); var userId = Guid.Parse(session.user.id); List <Guid> tubeIds = new List <Guid>(); foreach (var tubeid in message.body.tubeIds) { tubeIds.Add(Guid.Parse((string)tubeid)); } var dateStart = (DateTime)message.body.dateStart; var dateEnd = (DateTime)message.body.dateEnd; var pdfOrExcel = (string)message.body.type; string text = message.body.text; bool isOrientationAlbum = ((message.body as IDictionary <string, object>).ContainsKey("isOrientationAlbum")) && (message.body.isOrientationAlbum is bool) && (message.body.isOrientationAlbum == true); var sent = Send(reportsId, tubeIds, dateStart, dateEnd, userId, pdfOrExcel, isOrientationAlbum, text); //var sent = Send(mailerId, start, end, userId, session, period); ans.body.sent = sent.data; ans.body.error = sent.error; ans.body.success = sent.success; } catch { ans.body.error = "Ошибка при рассылки отчета"; ans.body.success = false; } return(ans); } return(Helper.BuildMessage(what)); }
public async Task <dynamic> Handle(dynamic session, dynamic message) { string what = message.head.what; Guid userId = Guid.Parse((string)session.user.id); if (what == "records-save") { //var sw = new Stopwatch(); //sw.Start(); var records = new List <DataRecord>(); foreach (var raw in message.body.records) { records.Add(EntityExtensions.ToRecord(raw)); } //RecordsBackgroundProccessor.Instance.AddPart(records); RecordAcceptor.Instance.Save(records); //хук для паралельной обработки записей в микросервисе bus.SendRecords(AdaptRecords(records)); return(Helper.BuildMessage(what)); } if (what == "records-get-load-pretty") { var objectIds = new List <Guid>(); foreach (string target in message.body.targets) { objectIds.Add(Guid.Parse(target)); } DateTime start = message.body.start; DateTime end = message.body.end; string type = message.body.type; var records = RecordsDecorator.Decorate(objectIds.ToArray(), start, end, type, userId).ToDynamic(); var ans = Helper.BuildMessage(what); ans.body.records = records; return(ans); } if (what == "records-get") { var objectIds = new List <Guid>(); foreach (string target in message.body.targets) { var id = Guid.Parse(target); if (StructureGraph.Instance.CanSee(id, Guid.Parse((string)session.userId))) { objectIds.Add(id); } } DateTime start = message.body.start; DateTime end = message.body.end; string type = message.body.type; var records = Cache.Instance.GetRecords(start, end, type, objectIds.ToArray()).ToDynamic(); var ans = Helper.BuildMessage(what); ans.body.records = records; return(ans); } if (what == "records-get1") { var objectIds = new List <Guid>(); foreach (string target in message.body.targets) { var id = Guid.Parse(target); //if (StructureGraph.Instance.CanSee(id, Guid.Parse((string)session.userId))) objectIds.Add(id); } DateTime start = DateTime.Parse(message.body.start); DateTime end = DateTime.Parse(message.body.end); string type = message.body.type; var records = Cache.Instance.GetRecords(start, end, type, objectIds.ToArray()).ToDynamic(); var rec = records.OrderBy(x => x.date); var ans = Helper.BuildMessage(what); ans.body.records = rec; return(ans); } if (what == "records-get-with-ids-and-s1") { List <Guid> listIds = new List <Guid>(); Guid objectId = Guid.Parse((string)message.body.objectId); listIds.Add(objectId); if (message.body.cmd == "findAnotherTubes") { var objectIds = StructureGraph.Instance.GetIdsByTubeId(objectId); listIds.AddRange(objectIds); } else if (((string)message.body.cmd).Contains("ids:")) { listIds.Clear(); string[] strIds = ((string)message.body.cmd).Substring(4).Split(','); for (int i = 0; i < strIds.Length; i++) { if (Guid.TryParse(strIds[i], out Guid guidId)) { listIds.Add(guidId); } } } DateTime start = message.body.start; DateTime end = message.body.end; string type = message.body.type; string s1 = message.body.s1; var records = Cache.Instance.GetWithIdAndS1Records(listIds, start, end, type, s1).ToDynamic(); var ans = Helper.BuildMessage(what); ans.body.records = records; return(ans); } if (what == "records-get-only-with-type") { DateTime start = message.body.start; DateTime end = message.body.end; string type = message.body.type; var records = Cache.Instance.GetDataOnlyWithTypeRecords(start, end, type).ToDynamic(); var ans = Helper.BuildMessage(what); ans.body.records = records; return(ans); } if (what == "records-get-dates") { Guid id = Guid.Parse(message.body.id.ToString()); DateTime start = message.body.start; DateTime end = message.body.end; string type = message.body.type; DateTime[] records = Cache.Instance.GetDateSet(start, end, type, id).ToArray(); var ans = Helper.BuildMessage(what); ans.body.records = records; return(ans); } if (what == "records-save-count") { Guid objectId = Guid.Parse(message.body.objectId.ToString()); DateTime date = DateTime.Now; if (DateTime.TryParse(Convert.ToString(message.body.date), out DateTime tmpDate)) { date = tmpDate; } double count = Convert.ToDouble((string)message.body.count); string comment = message.body.comment.ToString(); var records = new List <DataRecord>(); records.Add(EntityExtensions.ToRecord(CountRecord(objectId, date, count, "Оплата", comment))); RecordAcceptor.Instance.Save(records); return(Helper.BuildMessage(what)); } if (what == "records-delete") { var records = new List <DataRecord>(); List <Guid> listIds = new List <Guid>(); foreach (var id in message.body.ids) { listIds.Add(Guid.Parse((string)id)); } string type = (string)message.body.type; Cache.Instance.DeleteRecords(listIds, type); var ans = Helper.BuildMessage(what); return(ans); } return(Helper.BuildMessage("unhandled")); }