using Container.Common; using Container.Services; using Newtonsoft.Json; using RabbitMQ.Client; using RabbitMQ.Client.Events; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows; namespace Container.Business { public class RabbitHostedService { private readonly IConnection connection; private static App app = ((App)Application.Current); private readonly IModel channel; static Class_Log _log = new Class_Log(); public delegate void WebSocketReceiveDelegate(string type, string message); public static event WebSocketReceiveDelegate WebSocketReceiveEvent; private HttpClient httpclient = new HttpClient(); private Class_Config con = new Class_Config(); public RabbitHostedService() { try { var factory = new ConnectionFactory() { UserName = app.rabbitMQ.UserName, Password = app.rabbitMQ.Password, HostName = app.rabbitMQ.HostName, Port = app.rabbitMQ.Port, }; this.connection = factory.CreateConnection(); this.channel = connection.CreateModel(); } catch (Exception ex) { //Console.WriteLine($"RabbitListener init error,ex:{ex.Message}"); _log.WriteLogFile("rabbitMq"+"init error:" + ex.Message, "RabbitHosted"); } } public Task StartAsync(CancellationToken cancellationToken) { Register(); return Task.CompletedTask; } // 注册消费者监听在这里 public void Register() { //Console.WriteLine($"RabbitListener register,routeKey:{RouteKey}"); if (string.IsNullOrEmpty(app.deviceid)) { _log.WriteLogFile("rabbitMq"+ "设备未注册", "RabbitHosted"); return; } _log.WriteLogFile("rabbitMq"+ "已连接连接到服务器", "RabbitHosted"); //交换机名称 String exchangeName = "topic_immediately"; //声明交换机 //channel.ExchangeDeclare(exchange: exchangeName, type: "topic", durable: true); //channel.ExchangeDeclare(exchange: "topic.default", type: "topic", durable: true); //消息队列名称 String queueName = "device."+ app.deviceid; //声明队列 channel.QueueDeclare(queue: queueName, durable: false, exclusive: false, autoDelete: true, arguments: null); //将队列与交换机进行绑定 //foreach (var routeKey in args) //{//匹配多个路由 // channel.QueueBind(queue: queueName, exchange: exchangeName, routingKey: routeKey); //} //channel.QueueBind(queue: queueName, exchange: "topic.default", routingKey: ""); channel.QueueBind(queue: queueName, exchange: exchangeName, routingKey: queueName); //声明为手动确认 channel.BasicQos(0, 1, false); //定义消费者 var consumer = new EventingBasicConsumer(channel); consumer.Received += (model, ea) => { var body = ea.Body; var message = Encoding.UTF8.GetString(body); var result = Process(message); if (result) { channel.BasicAck(ea.DeliveryTag, false); } }; //开启监听 channel.BasicConsume(queue: queueName, autoAck: false, consumer: consumer); } // 处理消息的方法 public virtual bool Process(string msg) { try { string type = ""; _log.WriteLogFile(msg,"rabbit"); Dictionary diccontent = Newtonsoft.Json.JsonConvert.DeserializeObject>(msg.ToLower()); if (diccontent["content"] != null) { Dictionary dic = JsonConvert.DeserializeObject>(diccontent["content"].ToString()); if (dic["content"] != null && dic["senderid"] != null) { Dictionary Commands = JsonConvert.DeserializeObject>(dic["content"].ToString()); if (!string.IsNullOrEmpty(Commands["type"].ToString())) { type = Commands["type"].ToString(); } if (type.Trim().Equals("apppublish")) { AppListModel model = new AppListModel(); model.AppID = string.IsNullOrEmpty(Commands["appid"].ToString()) ? "" : Commands["appid"].ToString(); model.AppType = string.IsNullOrEmpty(Commands["apptype"].ToString()) ? "" : Commands["apptype"].ToString(); //model.AppUrl = string.IsNullOrEmpty(Commands["appurl"].ToString()) ? "" : Commands["appurl"].ToString(); model.Code = string.IsNullOrEmpty(Commands["code"].ToString()) ? "" : Commands["code"].ToString(); model.Logo = string.IsNullOrEmpty(Commands["logo"].ToString()) ? "" : Commands["logo"].ToString(); model.Name = string.IsNullOrEmpty(Commands["name"].ToString()) ? "" : Commands["name"].ToString(); model.ShelfTime = (Commands["shelftime"] == null || string.IsNullOrEmpty(Commands["shelftime"].ToString())) ? "" : Commands["shelftime"].ToString(); model.Default = string.IsNullOrEmpty(Commands["default"].ToString()) ? "false" : Commands["default"].ToString(); model.File = Commands["file"]==null ? "" : Commands["file"].ToString(); model.PackageName = Commands["packagename"]==null ? "" : Commands["packagename"].ToString(); model.PlatformType = Commands["platformtype"]==null ? "" : Commands["platformtype"].ToString(); model.Startup = Commands["startup"]==null ? "" : Commands["startup"].ToString(); model.Version = Commands["version"]==null ? "" : Commands["version"].ToString(); bool flag = httpclient.DownLoadIcon(ref model.Logo); if (!string.IsNullOrEmpty(model.File)) { httpclient.DownLoadFiles(model.File, ref model.File); } if (!string.IsNullOrEmpty(model.Startup) && (model.Startup.ToLower().StartsWith("https://") || model.Startup.ToLower().StartsWith("http://"))) { model.Startup = _log.WriteAppStart(model.Name, model.Startup); } con.WriteToExeConfig(model); app.AppList.Add(model); //_log.WriteLogFile("发布应用", "WebSocketLog"); //app.AppUpdate = false; //if (!string.IsNullOrEmpty(Commands["appname"].ToString())) //{ // app.appName = Commands["appname"].ToString(); // app.Appdowninfo.exename = Commands["appname"].ToString(); //} //if (!string.IsNullOrEmpty(Commands["filepath"].ToString())) //{ // app.appUrl = Commands["filepath"].ToString(); //} //if (!string.IsNullOrEmpty(Commands["appnameen"].ToString())) //{ // app.Appdowninfo.exestartname = Commands["appnameen"].ToString(); //} //if (!string.IsNullOrEmpty(Commands["iconfilepath"].ToString())) //{ // app.icourl = Commands["iconfilepath"].ToString(); //} //if (!string.IsNullOrEmpty(Commands["appid"].ToString())) //{ // app.Appdowninfo.AppID = Commands["appid"].ToString(); //} //if (!string.IsNullOrEmpty(Commands["version"].ToString())) //{ // app.Appdowninfo.Version = Commands["version"].ToString(); //} //if (!string.IsNullOrEmpty(Commands["default"].ToString())) //{ // app.Appdowninfo.Default = Convert.ToBoolean(Commands["default"]); //} } else if (type.Trim().Equals("cloud-screenshot")) { app.screenshotUserName = string.IsNullOrEmpty(Commands["parameter"].ToString()) ? "" : Commands["parameter"].ToString(); } else if (type.Trim().Equals("appdown")) { var code = Commands["code"].ToString(); var defaultCode= Commands["defaultapp"].ToString(); if (!string.IsNullOrEmpty(code)) { var appmodel = app.AppList.Where(i => i.Code == code).FirstOrDefault(); var appList = app.AppList; app.AppList.Remove(appmodel); foreach (var item in app.AppList) { if (item.Code == defaultCode) { item.Default = Boolean.TrueString; } } //con.RemoveExeConfig(appmodel.Code, ref appmodel.File, ref appmodel.Logo, ref appmodel.Startup); //if (!string.IsNullOrEmpty(appmodel.File) && Directory.Exists(appmodel.File)) //{ // Directory.Delete(appmodel.File); //} //if (!string.IsNullOrEmpty(appmodel.Logo) && File.Exists(appmodel.Logo)) //{ // File.Delete(appmodel.Logo); //} //if (!string.IsNullOrEmpty(appmodel.Logo) && File.Exists(appmodel.Startup)) //{ // File.Delete(appmodel.Startup); //} var nowTimeSlot = app.AppTimeList.Where(i => i.AppCode != code&&i.AppCode!=defaultCode).ToList(); if (nowTimeSlot.Count < app.AppTimeList.Count) { app.AppTimeList = nowTimeSlot; con.WriteToAppTimeConfig(app.AppTimeList); } } //app.AppDownCode = ""; //app.DefaultAppCode = ""; //if (!string.IsNullOrEmpty(Commands["appid"].ToString())) //{ // app.AppDownCode = Commands["appid"].ToString(); //} //if (!string.IsNullOrEmpty(Commands["defaultappcode"].ToString())) //{ // app.DefaultAppCode = Commands["defaultappcode"].ToString(); //} } else if (type.Trim().Equals("apptimeset")) { HttpMessage httpMessage = new HttpMessage(); httpMessage.LoadAppTimeConfig(); //app.DefaultAppCode = ""; //if (!string.IsNullOrEmpty(Commands["defaultappcode"].ToString())) //{ // app.DefaultAppCode = Commands["defaultappcode"].ToString(); //} } else if (type.Trim().Equals("appupdate")) { AppListModel model = new AppListModel(); model.AppID = string.IsNullOrEmpty(Commands["appid"].ToString()) ? "" : Commands["appid"].ToString(); model.AppType = string.IsNullOrEmpty(Commands["apptype"].ToString()) ? "" : Commands["apptype"].ToString(); //model.AppUrl = string.IsNullOrEmpty(Commands["appurl"].ToString()) ? "" : Commands["appurl"].ToString(); model.Code = string.IsNullOrEmpty(Commands["code"].ToString()) ? "" : Commands["code"].ToString(); model.Logo = string.IsNullOrEmpty(Commands["logo"].ToString()) ? "" : Commands["logo"].ToString(); model.Name = string.IsNullOrEmpty(Commands["name"].ToString()) ? "" : Commands["name"].ToString(); model.ShelfTime = (Commands["shelftime"] == null || string.IsNullOrEmpty(Commands["shelftime"].ToString())) ? "" : Commands["shelftime"].ToString(); model.Default = string.IsNullOrEmpty(Commands["default"].ToString()) ? "false" : Commands["default"].ToString(); model.File = Commands["file"] == null ? "" : Commands["file"].ToString(); model.PackageName = Commands["packagename"] == null ? "" : Commands["packagename"].ToString(); model.PlatformType = Commands["platformtype"] == null ? "" : Commands["platformtype"].ToString(); model.Startup = Commands["startup"] == null ? "" : Commands["startup"].ToString(); model.Version = Commands["version"] == null ? "" : Commands["version"].ToString(); bool flag = httpclient.DownLoadIcon(ref model.Logo); var appModel = app.AppList.Where(i => i.Code == model.Code).FirstOrDefault(); if ((appModel == null || appModel.Version != model.Version) && !string.IsNullOrEmpty(model.File)) { httpclient.DownLoadFiles(model.File, ref model.File); } if (!string.IsNullOrEmpty(model.Startup) && (model.Startup.ToLower().StartsWith("https://") || model.Startup.ToLower().StartsWith("http://"))) { model.Startup = _log.WriteAppStart(model.Name, model.Startup); } con.WriteToExeConfig(model); foreach (var item in app.AppList) { if (item.Code == model.Code) { item.AppID = model.AppID; item.AppType = model.AppType; item.Default = model.Default; item.File = model.File; item.Logo = model.Logo; item.Name = model.Name; item.PackageName = model.PackageName; item.PlatformType = model.PlatformType; item.ShelfTime = model.ShelfTime; item.Startup = model.Startup; item.Version = model.Version; } } } else if (type.Trim().Equals("appclock")) { //if (!string.IsNullOrEmpty(Commands["data"].ToString())) //{ // Dictionary data = JsonConvert.DeserializeObject>(Commands["data"].ToString()); // if (!string.IsNullOrEmpty(data["startapp"].ToString())) // { // Dictionary startapp = JsonConvert.DeserializeObject>(data["startapp"].ToString()); // if (!string.IsNullOrEmpty(startapp["filename"].ToString())) // { // app.AppPlayDir = startapp["filename"].ToString(); // app.AppStartinfo.exepath = startapp["appnameen"].ToString(); // if (!string.IsNullOrEmpty(startapp["appnameen"].ToString())) // { // //app.AppPlayName = startapp["appnameen"].ToString(); // app.AppStartinfo.exestartname = startapp["appnameen"].ToString(); // } // if (!string.IsNullOrEmpty(startapp["appid"].ToString())) // { // app.AppStartinfo.AppID = startapp["appid"].ToString(); // } // if (!string.IsNullOrEmpty(startapp["appname"].ToString())) // { // app.AppStartinfo.exename = startapp["appname"].ToString(); // } // } // else // { // if (!string.IsNullOrEmpty(data["endapp"].ToString())) // { // Dictionary endapp = JsonConvert.DeserializeObject>(data["endapp"].ToString()); // if (!string.IsNullOrEmpty(endapp["name"].ToString())) // { // app.AppStartinfo.exename = ""; // } // } // } // } //} } else if (type.Trim().Equals("insertad")) { //if (!string.IsNullOrEmpty(Commands["data"].ToString())) //{ // Dictionary data = JsonConvert.DeserializeObject>(Commands["data"].ToString()); // if (!string.IsNullOrEmpty(data["filepath"].ToString())) // { // //Dictionary admodel = JsonConvert.DeserializeObject>(data["admodel"].ToString()); // //if (!string.IsNullOrEmpty(data["filepath"].ToString())) // //{ // app.insertAD.Duration = Convert.ToInt32(data["duration"]); // app.insertAD.FilePath = data["filepath"].ToString(); // //} // } //} } else if (type.Trim().Equals("addown")) { //app.insertAD.Duration = 0; //app.insertAD.FilePath = ""; } else if (type.Trim().Equals("devnumedit")) { if (!string.IsNullOrEmpty(Commands["devnum"].ToString())) { app.devicemark = Commands["devnum"].ToString(); } } else if (type.Trim().Equals("bgset")) { if (!string.IsNullOrEmpty(Commands["filepath"].ToString())) { app.bgPath = Commands["filepath"].ToString(); } } else if (type.Trim().Equals("screensaver")) { app.screensaver.ScreenTime = 30; if (!string.IsNullOrEmpty(Commands["time"].ToString())) { app.screensaver.ScreenTime = Convert.ToInt32(Commands["time"]); } string fileName = string.Empty; if (!string.IsNullOrEmpty(Commands["screenfilepath"].ToString())) { string path = Commands["screenfilepath"].ToString(); if (!string.IsNullOrEmpty(path)) { httpclient.DownLoadImage(path, "exefile/PCScreen/config", ref fileName); } } Class_Config config = new Class_Config(); string screentype = "0"; if (!string.IsNullOrEmpty(Commands["screentype"].ToString())) { screentype = Commands["screentype"].ToString(); } string screeneffect = "0"; if (!string.IsNullOrEmpty(Commands["screeneffect"].ToString())) { screeneffect = Commands["screeneffect"].ToString(); } string effecttype = "0"; if (!string.IsNullOrEmpty(Commands["effecttype"].ToString())) { effecttype = Commands["effecttype"].ToString(); } config.WriteToScreenConfig(screentype, screeneffect, fileName, effecttype); } else if (type.Trim().Equals("shutdowntime")) { app.shutdowntime = Commands["parameter"].ToString(); } } } if (WebSocketReceiveEvent != null) { WebSocketReceiveEvent(type, ""); } } catch (Exception ex) { _log.WriteLogFile(ex.ToString(), "WebSocketLog"); } return true; } public void DeRegister() { this.connection.Close(); } public Task StopAsync(CancellationToken cancellationToken) { this.connection.Close(); return Task.CompletedTask; } } }