commit 8f4ea4666a4f1834023f8bf797875eb4300567aa Author: congopeng Date: Fri Jul 15 10:31:05 2022 +0800 新塘提交 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..ee36599 --- /dev/null +++ b/.gitignore @@ -0,0 +1,11 @@ +/packages/ +/*/packages/ +/*/*/packages/ +/*/bin/ +/*/*/bin/ +/*/obj/ +/*/*/obj/ +/build_64/ +/数据库/*.ldf +/数据库/*.mdf +/build_64/ diff --git a/.vs/Container/FileContentIndex/472e21bc-fd73-460f-87d0-18c0158eabba.vsidx b/.vs/Container/FileContentIndex/472e21bc-fd73-460f-87d0-18c0158eabba.vsidx new file mode 100644 index 0000000..85d0795 Binary files /dev/null and b/.vs/Container/FileContentIndex/472e21bc-fd73-460f-87d0-18c0158eabba.vsidx differ diff --git a/.vs/Container/FileContentIndex/read.lock b/.vs/Container/FileContentIndex/read.lock new file mode 100644 index 0000000..e69de29 diff --git a/.vs/Container/v16/.suo b/.vs/Container/v16/.suo new file mode 100644 index 0000000..86195e6 Binary files /dev/null and b/.vs/Container/v16/.suo differ diff --git a/.vs/Container/v17/.suo b/.vs/Container/v17/.suo new file mode 100644 index 0000000..8ee5dcc Binary files /dev/null and b/.vs/Container/v17/.suo differ diff --git a/.vs/Container/v17/fileList.bin b/.vs/Container/v17/fileList.bin new file mode 100644 index 0000000..e920c85 Binary files /dev/null and b/.vs/Container/v17/fileList.bin differ diff --git a/ConUpdate/App.config b/ConUpdate/App.config new file mode 100644 index 0000000..bc11697 --- /dev/null +++ b/ConUpdate/App.config @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/ConUpdate/App.xaml b/ConUpdate/App.xaml new file mode 100644 index 0000000..a326575 --- /dev/null +++ b/ConUpdate/App.xaml @@ -0,0 +1,8 @@ + + + + + diff --git a/ConUpdate/App.xaml.cs b/ConUpdate/App.xaml.cs new file mode 100644 index 0000000..05375e1 --- /dev/null +++ b/ConUpdate/App.xaml.cs @@ -0,0 +1,50 @@ +using System; +using System.Collections.Generic; +using System.Configuration; +using System.Data; +using System.Linq; +using System.Threading.Tasks; +using System.Windows; + +namespace ConUpdate +{ + /// + /// App.xaml 的交互逻辑 + /// + public partial class App : Application + { + internal string info = ""; + private LogHelper log = new LogHelper(); + private void Application_Startup(object sender, StartupEventArgs e) + { + //http://1000my.cn:8080/update/ConUpdate.xml + try + { + if (e.Args.Count() > 0) + { + log.WriteInfoFile("收到" + e.Args[0].ToString()); + info = e.Args[0].ToString(); + } + } + catch (Exception ex) + { + log.WriteInfoFile(ex.ToString()); + } + { + MainWindow win = new MainWindow(); + win.Show(); + } + AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException); + Application.Current.DispatcherUnhandledException += new System.Windows.Threading.DispatcherUnhandledExceptionEventHandler(Current_DispatcherUnhandledException); + } + + private void Current_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e) + { + } + + private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) + { + Exception ex = (Exception)e.ExceptionObject; + } + } +} diff --git a/ConUpdate/CommonMethod.cs b/ConUpdate/CommonMethod.cs new file mode 100644 index 0000000..7c29b12 --- /dev/null +++ b/ConUpdate/CommonMethod.cs @@ -0,0 +1,261 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Net; +using System.IO; +using System.Xml; +using ConUpdate.ViewModel; +using System.Configuration; + +namespace ConUpdate +{ + class CommonMethod + { + private LogHelper log = new LogHelper(); + /// + /// 是否需要更新 + /// + /// + public List IsUpdate(out string currentVersion) + { + List updateList = new List(); + try + { + string localPath = Directory.GetCurrentDirectory() + "\\ScreenVersion.txt"; + + FileStream fs = new FileStream(localPath, FileMode.Open); + using (StreamReader sr = new StreamReader(fs)) + { + string temp = sr.ReadLine(); + currentVersion = temp.Substring(temp.LastIndexOf("V")); + } + fs.Close(); + + log.WriteInfoFile("服务器配置文件地址:" + ConfigurationManager.AppSettings["url"]); + List versionList = XmlReader(ConfigurationManager.AppSettings["url"]); + + foreach (var item in versionList) + { + if (currentVersion != item.Title) + updateList.Add(item); + else + break; + } + return updateList; + } + catch + { + currentVersion = ""; + return updateList; + } + } + + /// + /// 开始更新 + /// + /// + public void StartUpdate(XmlNodeItem versionItem, ProgressViewModel viewModel) + { + try + { + List fileList = GetDirectoryContents(versionItem.Url); + List copyfile = new List(); + List sourcefile = new List(); + viewModel.Title = "正在更新版本..."; + viewModel.MaxValue = 100; + viewModel.CurrentProgress = 1; + viewModel.Val = 0; + viewModel.Message = viewModel.CurrentProgress + "/" + fileList.Count; + + for (int i = 0; i < fileList.Count; i++) + { + try + { + string remoteFile = versionItem.Url + "/" + fileList[i]; + string localFile = Directory.GetCurrentDirectory() + "\\" + fileList[i]; + string dir = localFile.Remove(localFile.LastIndexOf("\\")) + "\\updatetemp"; + + viewModel.CurrentProgress = i + 1; + viewModel.Message = viewModel.CurrentProgress + "/" + fileList.Count; + + if (!Directory.Exists(dir)) + Directory.CreateDirectory(dir); + if (!Directory.Exists(localFile.Remove(localFile.LastIndexOf("\\")))) + Directory.CreateDirectory(localFile.Remove(localFile.LastIndexOf("\\"))); + if (File.Exists(localFile)) + { + string tempfile = localFile.Remove(localFile.LastIndexOf("\\")) + "\\updatetemp\\" + fileList[i].Replace("\\", "/").Substring(fileList[i].LastIndexOf("/") + 1, fileList[i].Length - fileList[i].LastIndexOf("/") - 1); + if (File.Exists(tempfile)) + { + File.Delete(tempfile); + } + log.WriteInfoFile("正在移动:"+localFile); + File.Move(localFile, tempfile); + copyfile.Add(tempfile); + sourcefile.Add(localFile); + File.Delete(localFile); + } + + WebRequest request = WebRequest.Create(remoteFile); + WebResponse respone = request.GetResponse(); + Stream netStream = respone.GetResponseStream(); + Stream fileStream = new FileStream(localFile, FileMode.Create); + long totalDownloadedByte = 0; + byte[] read = new byte[1024]; + int realReadLen = netStream.Read(read, 0, read.Length); + while (realReadLen > 0) + { + totalDownloadedByte = realReadLen + totalDownloadedByte; + fileStream.Write(read, 0, realReadLen); + realReadLen = netStream.Read(read, 0, read.Length); + + viewModel.Val = ((totalDownloadedByte / respone.ContentLength) * 100); + } + netStream.Close(); + fileStream.Close(); + } + catch(Exception ex) + { + log.WriteInfoFile(ex.ToString()); + for (int j = 0; j < copyfile.Count; j++) + { + if (File.Exists(copyfile[j])) + { + if (File.Exists(sourcefile[j])) + { + File.Delete(sourcefile[j]); + + } + File.Move(copyfile[j], sourcefile[j]); + } + } + + return; + } + } + log.WriteInfoFile("更新完成!" ); + } + catch(Exception ex) + { + log.WriteInfoFile(ex.ToString()); + } + } + + /// + /// 获取路径下所有文件路径 + /// + /// + /// + /// + private List GetDirectoryContents(string remotePath) + { + List fileNames = new List(); + string filePath = remotePath + "/config.txt"; + + WebRequest request = WebRequest.Create(filePath); + WebResponse respone = request.GetResponse(); + + Stream netStream = respone.GetResponseStream(); + StreamReader sr = new StreamReader(netStream, Encoding.UTF8); + string lineStr = sr.ReadLine(); + while (!string.IsNullOrEmpty(lineStr)) + { + fileNames.Add(lineStr.Replace("\0", "")); + lineStr = sr.ReadLine(); + } + + netStream.Close(); + sr.Close(); + + //Stream fs = new FileStream(localPath, FileMode.Create); + + //int readBytes = netStream.Read(buffer, 0, buffer.Length); + //while (readBytes > 0) + //{ + // fs.Write(buffer, 0, buffer.Length); + // readBytes = netStream.Read(buffer, 0, buffer.Length); + //} + //netStream.Close(); + //fs.Close(); + + //if (File.Exists(localPath)) + //{ + // string[] names = File.ReadAllLines(localPath, Encoding.UTF8); + // foreach (var item in names) + // fileNames.Add(item.Replace("\0", "")); + //} + + return fileNames; + } + + /// + /// 读取xml文件 + /// + /// + /// + private List XmlReader(string url) + { + + List nodeList = new List(); + try + { + XmlDocument doc = new XmlDocument(); + doc.Load(url); //加载Xml文件 + XmlElement rootElem = doc.DocumentElement; //获取根节点 + XmlNodeList itemNodes = rootElem.GetElementsByTagName("item"); //获取item子节点集合 + foreach (XmlNode node in itemNodes) + { + XmlNodeItem item = new XmlNodeItem(); + XmlNodeList subTitleNodes = ((XmlElement)node).GetElementsByTagName("title"); //获取title子XmlElement集合 + XmlNodeList subDateNodes = ((XmlElement)node).GetElementsByTagName("date"); //获取date子XmlElement集合 + XmlNodeList subUrlNodes = ((XmlElement)node).GetElementsByTagName("url"); //获取url子XmlElement集合 + XmlNodeList subConfigNodes = ((XmlElement)node).GetElementsByTagName("iscopyconfig"); //获取iscopyconfig子XmlElement集合 + XmlNodeList subDescribtionNodes = ((XmlElement)node).GetElementsByTagName("describtion"); //获取describtion子XmlElement集合 + if (subTitleNodes.Count == 1) + item.Title = subTitleNodes[0].InnerText; + if (subDateNodes.Count == 1) + item.Date = subDateNodes[0].InnerText; + if (subUrlNodes.Count == 1) + item.Url = subUrlNodes[0].InnerText; + if (subConfigNodes.Count == 1) + item.IsCopyConfig = subConfigNodes[0].InnerText; + if (subDescribtionNodes.Count == 1) + item.Describtion = subDescribtionNodes[0].InnerText; + + nodeList.Add(item); + } + + return nodeList; + } + catch (Exception ex) + { + log.WriteInfoFile(ex.ToString()); + return nodeList; + } + } + + /// + /// 比较两个数组是否相等 + /// + /// + /// + /// + private int CompareBytes(byte[] b1, byte[] b2) + { + if (b1 == null || b2 == null) + return -1; + if (b1.Length != b2.Length) + return -1; + else + { + for (int i = 0; i < b1.Length; i++) + { + if (b1[i] != b2[i]) + return -1; + } + return 0; + } + } + } +} diff --git a/ConUpdate/ConUpdate.csproj b/ConUpdate/ConUpdate.csproj new file mode 100644 index 0000000..6a4bf06 --- /dev/null +++ b/ConUpdate/ConUpdate.csproj @@ -0,0 +1,123 @@ + + + + + Debug + AnyCPU + {DF0EAD54-D31A-4C8A-ADF3-D4963C1DED01} + WinExe + Properties + ConUpdate + ConUpdate + v4.8 + 512 + {60dc8134-eba5-43b8-bcc9-bb4bc16c2548};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + 4 + + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + ..\Container\bin\Release\ + TRACE + prompt + 4 + + + x64 + bin\x64\Debug\ + + + x64 + bin\x64\Release\ + + + + + + + + + + + + + 4.0 + + + + + + + + MSBuild:Compile + Designer + + + + + + MSBuild:Compile + Designer + + + App.xaml + Code + + + + + MainWindow.xaml + Code + + + + + Code + + + True + True + Resources.resx + + + True + Settings.settings + True + + + ResXFileCodeGenerator + Resources.Designer.cs + + + SettingsSingleFileGenerator + Settings.Designer.cs + + + + + + + + + + + + \ No newline at end of file diff --git a/ConUpdate/ConUpdate.csproj.user b/ConUpdate/ConUpdate.csproj.user new file mode 100644 index 0000000..fe7dc22 --- /dev/null +++ b/ConUpdate/ConUpdate.csproj.user @@ -0,0 +1,6 @@ + + + + ShowAllFiles + + \ No newline at end of file diff --git a/ConUpdate/LogHelper.cs b/ConUpdate/LogHelper.cs new file mode 100644 index 0000000..b030f0a --- /dev/null +++ b/ConUpdate/LogHelper.cs @@ -0,0 +1,151 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.IO; + +namespace ConUpdate +{ + class LogHelper + { + /**/ + /// + /// 写入日志文件 + /// + /// + public string WriteInfoFile(string input) + { + try + { + if (!Directory.Exists(Directory.GetCurrentDirectory() + "\\UpdateLogs")) + Directory.CreateDirectory(Directory.GetCurrentDirectory() + "\\UpdateLogs"); + /**/ + ///指定日志文件的目录 + string fname = Directory.GetCurrentDirectory() + "\\UpdateLogs\\LogFile(" + DateTime.Today.Date.ToString("yyyy-MM-dd") + ").txt"; + /**/ + ///定义文件信息对象 + + FileInfo finfo = new FileInfo(fname); + + if (!finfo.Exists) + { + FileStream fs; + fs = File.Create(fname); + fs.Close(); + finfo = new FileInfo(fname); + } + + /**/ + ///判断文件是否存在以及是否大于2K + if (finfo.Length > 1024 * 1024 * 10) + { + /**/ + ///文件超过10MB则重命名 + File.Move(Directory.GetCurrentDirectory() + "\\UpdateLogs\\LogFile.txt", Directory.GetCurrentDirectory() + "\\UpdateLogs\\" + "LogFile{" + Guid.NewGuid() + "}.txt"); + /**/ + ///删除该文件 + //finfo.Delete(); + } + //finfo.AppendText(); + /**/ + ///创建只写文件流 + + using (FileStream fs = finfo.OpenWrite()) + { + /**/ + ///根据上面创建的文件流创建写数据流 + StreamWriter w = new StreamWriter(fs); + + /**/ + ///设置写数据流的起始位置为文件流的末尾 + w.BaseStream.Seek(0, SeekOrigin.End); + + /**/ + ///写入“Log Entry : ” + w.Write("\n\rLog Entry : "); + + /**/ + ///写入当前系统时间并换行 + w.Write("{0} {1} \n\r", DateTime.Now.ToLongTimeString(), + DateTime.Now.ToLongDateString()); + + /**/ + ///写入日志内容并换行 + w.Write(input + "\n\r"); + + /**/ + ///写入------------------------------------“并换行 + //w.Write("------------------------------------\n\r"); + + /**/ + ///清空缓冲区内容,并把缓冲区内容写入基础流 + w.Flush(); + + /**/ + ///关闭写数据流 + w.Close(); + + return "0"; + } + } + catch (Exception ex) + { + return ex.Message + ex.StackTrace; + } + } + + /// + /// 删除 fileName 文件夹里一个月之前的日志 + /// + /// + /// + public void DeleteFiles(string fileName = "") + { + try + { + if (string.IsNullOrEmpty(fileName)) + fileName = Directory.GetCurrentDirectory() + "\\UpdateLogs"; + if (!Directory.Exists(fileName))//若文件夹不存在则返回 + return; + DirectoryInfo dir = new DirectoryInfo(fileName); + //不是目录 + + if (dir == null) + return; + //DateTime DT = dir.CreationTime; + + FileSystemInfo[] files = dir.GetFileSystemInfos(); + for (int i = 0; i < files.Length; i++) + { + FileInfo file = files[i] as FileInfo; + //是文件 + if (file != null) + { + DateTime DT = file.CreationTime; + if (DateTime.Now.Month - DT.Month >= 1) + { + file.Delete(); + } + } + else + { + DirectoryInfo dir1 = files[i] as DirectoryInfo; + if (dir1 != null) + { + DateTime DT = dir1.CreationTime; + if (DateTime.Now.Month - DT.Month >= 1) + { + //dir1.Delete(); + System.IO.Directory.Delete(fileName + "\\" + dir1.Name, true); + } + } + } + } + } + catch + { + } + + } + } +} diff --git a/ConUpdate/MainWindow.xaml b/ConUpdate/MainWindow.xaml new file mode 100644 index 0000000..3397b6b --- /dev/null +++ b/ConUpdate/MainWindow.xaml @@ -0,0 +1,15 @@ + + + + + + + + + + + + diff --git a/ConUpdate/MainWindow.xaml.cs b/ConUpdate/MainWindow.xaml.cs new file mode 100644 index 0000000..8d61083 --- /dev/null +++ b/ConUpdate/MainWindow.xaml.cs @@ -0,0 +1,149 @@ +using ConUpdate.ViewModel; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Data; +using System.Windows.Documents; +using System.Windows.Input; +using System.Windows.Media; +using System.Windows.Media.Imaging; +using System.Windows.Navigation; +using System.Windows.Shapes; + +namespace ConUpdate +{ + /// + /// MainWindow.xaml 的交互逻辑 + /// + public partial class MainWindow : Window + { + private CommonMethod common = new CommonMethod(); + private ProgressViewModel pvm = new ProgressViewModel(); + private LogHelper log = new LogHelper(); + App app = ((App)Application.Current); + bool killexe = false; + public MainWindow() + { + InitializeComponent(); + } + + private void Window_Loaded(object sender, RoutedEventArgs e) + { + log.WriteInfoFile("Loading..."); + this.DataContext = pvm; + + try + { + log.DeleteFiles(); + List updateList = new List(); + Action ac = new Action(() => + { + string currentVersion = string.Empty; + updateList = common.IsUpdate(out currentVersion); + }); + ac.BeginInvoke((o) => + { + if (updateList.Count > 0) + { + killExE(); + Thread.Sleep(2000); + common.StartUpdate(updateList[0], pvm); + } + this.Dispatcher.Invoke(new Action(() => + { + this.Close(); + })); + }, updateList); + } + catch (Exception ex) + { + log.WriteInfoFile(ex.Message + ex.StackTrace); + } + } + + + private void killExE() + { + try + { + Process[] pro = Process.GetProcesses(); + for (int i = 0; i < pro.Length; i++) + { + if (pro[i].ProcessName.ToLower() == "pcscreensavers.exe") + { + pro[i].Kill();//结束进程 + killexe = true; + + log.WriteInfoFile("进程关闭"); + return; + } + } + } + catch (Exception ex) + { + log.WriteInfoFile(ex.ToString()); + } + } + private void Window_Closed(object sender, EventArgs e) + { + //if (killexe) + { + System.Security.Principal.WindowsIdentity identity = System.Security.Principal.WindowsIdentity.GetCurrent(); + //创建Windows用户主题 + System.Windows.Forms.Application.EnableVisualStyles(); + System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(identity); + //判断当前登录用户是否为管理员 + if (!principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator)) + { + //创建启动对象 + System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo(); + //设置运行文件 + startInfo.WorkingDirectory = System.Windows.Forms.Application.ExecutablePath.Replace("\\", "/").Substring(0, System.Windows.Forms.Application.ExecutablePath.Replace("\\", "/").LastIndexOf("/"));//设置应用程序在其所在目录 + startInfo.FileName = startInfo.WorkingDirectory + "/Container.exe"; //设置启动参数 + startInfo.Arguments = app.info + "&true"; + log.WriteInfoFile("发送" + startInfo.Arguments); + //设置启动动作,确保以管理员身份运行 + startInfo.Verb = "runas"; + //如果不是管理员,则启动UAC + //log.WriteLogFile("工作路径:" + startInfo.WorkingDirectory, "APPError"); + System.Diagnostics.Process.Start(startInfo); + //退出 + System.Windows.Forms.Application.Exit(); + + //System.Diagnostics.Process p = new System.Diagnostics.Process(); + //p.StartInfo.WorkingDirectory = System.Windows.Forms.Application.ExecutablePath.Replace("\\", "/").Substring(0, System.Windows.Forms.Application.ExecutablePath.Replace("\\", "/").LastIndexOf("/"));//设置应用程序在其所在目录 + //p.StartInfo.FileName = p.StartInfo.WorkingDirectory + "/PCScreenSavers.exe"; + //p.StartInfo.Arguments = app.info; + //p.StartInfo.Verb = "runas"; + //p.StartInfo.UseShellExecute = false; //是否使用操作系统shell启动 + //p.StartInfo.RedirectStandardInput = true;//接受来自调用程序的输入信息 + //p.StartInfo.RedirectStandardOutput = true;//由调用程序获取输出信息 + //p.StartInfo.RedirectStandardError = true;//重定向标准错误输出 + ////p.ProcessNa = "PCScreenUpdate"; + //p.StartInfo.CreateNoWindow = false;//不显示程序窗口 + //p.Start();//启动程序 + } + else + { + System.Diagnostics.Process p = new System.Diagnostics.Process(); + p.StartInfo.WorkingDirectory = System.Windows.Forms.Application.ExecutablePath.Replace("\\", "/").Substring(0, System.Windows.Forms.Application.ExecutablePath.Replace("\\", "/").LastIndexOf("/"));//设置应用程序在其所在目录 + p.StartInfo.FileName = p.StartInfo.WorkingDirectory + "/Container.exe"; + p.StartInfo.Arguments = app.info + "&true"; + log.WriteInfoFile("发送" + p.StartInfo.Arguments); + p.StartInfo.UseShellExecute = false; //是否使用操作系统shell启动 + p.StartInfo.RedirectStandardInput = true;//接受来自调用程序的输入信息 + p.StartInfo.RedirectStandardOutput = true;//由调用程序获取输出信息 + p.StartInfo.RedirectStandardError = true;//重定向标准错误输出 + p.StartInfo.CreateNoWindow = false;//不显示程序窗口 + p.Start();//启动程序 + } + } + } + } +} diff --git a/ConUpdate/Properties/AssemblyInfo.cs b/ConUpdate/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..84aeab8 --- /dev/null +++ b/ConUpdate/Properties/AssemblyInfo.cs @@ -0,0 +1,55 @@ +using System.Reflection; +using System.Resources; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Windows; + +// 有关程序集的常规信息通过以下 +// 特性集控制。更改这些特性值可修改 +// 与程序集关联的信息。 +[assembly: AssemblyTitle("ConUpdate")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("Microsoft")] +[assembly: AssemblyProduct("ConUpdate")] +[assembly: AssemblyCopyright("Copyright © Microsoft 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// 将 ComVisible 设置为 false 使此程序集中的类型 +// 对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型, +// 则将该类型上的 ComVisible 特性设置为 true。 +[assembly: ComVisible(false)] + +//若要开始生成可本地化的应用程序,请在 +// 中的 .csproj 文件中 +//设置 CultureYouAreCodingWith。 例如,如果您在源文件中 +//使用的是美国英语,请将 设置为 en-US。 然后取消 +//对以下 NeutralResourceLanguage 特性的注释。 更新 +//以下行中的“en-US”以匹配项目文件中的 UICulture 设置。 + +//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] + + +[assembly: ThemeInfo( + ResourceDictionaryLocation.None, //主题特定资源词典所处位置 + //(在页面或应用程序资源词典中 + // 未找到某个资源的情况下使用) + ResourceDictionaryLocation.SourceAssembly //常规资源词典所处位置 + //(在页面、应用程序或任何主题特定资源词典中 + // 未找到某个资源的情况下使用) +)] + + +// 程序集的版本信息由下面四个值组成: +// +// 主版本 +// 次版本 +// 生成号 +// 修订号 +// +// 可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值, +// 方法是按如下所示使用“*”: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/ConUpdate/Properties/Resources.Designer.cs b/ConUpdate/Properties/Resources.Designer.cs new file mode 100644 index 0000000..ce22081 --- /dev/null +++ b/ConUpdate/Properties/Resources.Designer.cs @@ -0,0 +1,63 @@ +//------------------------------------------------------------------------------ +// +// 此代码由工具生成。 +// 运行时版本:4.0.30319.42000 +// +// 对此文件的更改可能会导致不正确的行为,并且如果 +// 重新生成代码,这些更改将会丢失。 +// +//------------------------------------------------------------------------------ + +namespace ConUpdate.Properties { + using System; + + + /// + /// 一个强类型的资源类,用于查找本地化的字符串等。 + /// + // 此类是由 StronglyTypedResourceBuilder + // 类通过类似于 ResGen 或 Visual Studio 的工具自动生成的。 + // 若要添加或移除成员,请编辑 .ResX 文件,然后重新运行 ResGen + // (以 /str 作为命令选项),或重新生成 VS 项目。 + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + internal class Resources { + + private static global::System.Resources.ResourceManager resourceMan; + + private static global::System.Globalization.CultureInfo resourceCulture; + + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + internal Resources() { + } + + /// + /// 返回此类使用的缓存的 ResourceManager 实例。 + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Resources.ResourceManager ResourceManager { + get { + if (object.ReferenceEquals(resourceMan, null)) { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("ConUpdate.Properties.Resources", typeof(Resources).Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + /// + /// 重写当前线程的 CurrentUICulture 属性,对 + /// 使用此强类型资源类的所有资源查找执行重写。 + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Globalization.CultureInfo Culture { + get { + return resourceCulture; + } + set { + resourceCulture = value; + } + } + } +} diff --git a/ConUpdate/Properties/Resources.resx b/ConUpdate/Properties/Resources.resx new file mode 100644 index 0000000..af7dbeb --- /dev/null +++ b/ConUpdate/Properties/Resources.resx @@ -0,0 +1,117 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/ConUpdate/Properties/Settings.Designer.cs b/ConUpdate/Properties/Settings.Designer.cs new file mode 100644 index 0000000..4415f66 --- /dev/null +++ b/ConUpdate/Properties/Settings.Designer.cs @@ -0,0 +1,26 @@ +//------------------------------------------------------------------------------ +// +// 此代码由工具生成。 +// 运行时版本:4.0.30319.42000 +// +// 对此文件的更改可能会导致不正确的行为,并且如果 +// 重新生成代码,这些更改将会丢失。 +// +//------------------------------------------------------------------------------ + +namespace ConUpdate.Properties { + + + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "17.2.0.0")] + internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { + + private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); + + public static Settings Default { + get { + return defaultInstance; + } + } + } +} diff --git a/ConUpdate/Properties/Settings.settings b/ConUpdate/Properties/Settings.settings new file mode 100644 index 0000000..033d7a5 --- /dev/null +++ b/ConUpdate/Properties/Settings.settings @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/ConUpdate/ViewModel/ProgressViewModel.cs b/ConUpdate/ViewModel/ProgressViewModel.cs new file mode 100644 index 0000000..0719d5f --- /dev/null +++ b/ConUpdate/ViewModel/ProgressViewModel.cs @@ -0,0 +1,67 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace ConUpdate.ViewModel +{ + class ProgressViewModel : ViewModelBase + { + private int currentProgress = 0; + private int maxValue = 0; + private double val = 0.00; + private string message = string.Empty; + private string title = string.Empty; + + + public double Val + { + get { return val; } + set + { + val = value; + OnPropertyChanged("Val"); + } + } + + public string Title + { + get { return title; } + set + { + title = value; + OnPropertyChanged("Title"); + } + } + + public int CurrentProgress + { + get { return currentProgress; } + set + { + currentProgress = value; + OnPropertyChanged("CurrentProgress"); + } + } + + public int MaxValue + { + get { return maxValue; } + set + { + maxValue = value; + OnPropertyChanged("MaxValue"); + } + } + + public string Message + { + get { return message; } + set + { + message = value; + OnPropertyChanged("Message"); + } + } + } +} diff --git a/ConUpdate/ViewModel/ViewModelBase.cs b/ConUpdate/ViewModel/ViewModelBase.cs new file mode 100644 index 0000000..66ddcde --- /dev/null +++ b/ConUpdate/ViewModel/ViewModelBase.cs @@ -0,0 +1,19 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.ComponentModel; + +namespace ConUpdate.ViewModel +{ + class ViewModelBase : INotifyPropertyChanged + { + public event PropertyChangedEventHandler PropertyChanged; + + protected virtual void OnPropertyChanged(string propertyName) + { + if (PropertyChanged != null) + PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); + } + } +} diff --git a/ConUpdate/XmlNodeItem.cs b/ConUpdate/XmlNodeItem.cs new file mode 100644 index 0000000..2e02588 --- /dev/null +++ b/ConUpdate/XmlNodeItem.cs @@ -0,0 +1,61 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace ConUpdate +{ + class XmlNodeItem + { + private string title = string.Empty; + private string date = string.Empty; + private string url = string.Empty; + private string isCopyConfig = string.Empty; + private string describtion = string.Empty; + + /// + /// 标题 + /// + public string Title + { + get { return title; } + set { title = value; } + } + + /// + /// 日期 + /// + public string Date + { + get { return date; } + set { date = value; } + } + + /// + /// 地址 + /// + public string Url + { + get { return url; } + set { url = value; } + } + + /// + /// 是否替换配置文件 + /// + public string IsCopyConfig + { + get { return isCopyConfig; } + set { isCopyConfig = value; } + } + + /// + /// 描述 + /// + public string Describtion + { + get { return describtion; } + set { describtion = value; } + } + } +} diff --git a/ConUpdate/qm.ico b/ConUpdate/qm.ico new file mode 100644 index 0000000..34a51b5 Binary files /dev/null and b/ConUpdate/qm.ico differ diff --git a/Container.sln b/Container.sln new file mode 100644 index 0000000..5d9246b --- /dev/null +++ b/Container.sln @@ -0,0 +1,53 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.28010.2003 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Container", "Container\Container.csproj", "{DAE19E2F-B2BB-4778-B0F2-5FC48DC5975A}" + ProjectSection(ProjectDependencies) = postProject + {DF0EAD54-D31A-4C8A-ADF3-D4963C1DED01} = {DF0EAD54-D31A-4C8A-ADF3-D4963C1DED01} + EndProjectSection +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ConUpdate", "ConUpdate\ConUpdate.csproj", "{DF0EAD54-D31A-4C8A-ADF3-D4963C1DED01}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 + Release|Any CPU = Release|Any CPU + Release|x64 = Release|x64 + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {DAE19E2F-B2BB-4778-B0F2-5FC48DC5975A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {DAE19E2F-B2BB-4778-B0F2-5FC48DC5975A}.Debug|Any CPU.Build.0 = Debug|Any CPU + {DAE19E2F-B2BB-4778-B0F2-5FC48DC5975A}.Debug|x64.ActiveCfg = Debug|x64 + {DAE19E2F-B2BB-4778-B0F2-5FC48DC5975A}.Debug|x64.Build.0 = Debug|x64 + {DAE19E2F-B2BB-4778-B0F2-5FC48DC5975A}.Debug|x86.ActiveCfg = Debug|Any CPU + {DAE19E2F-B2BB-4778-B0F2-5FC48DC5975A}.Debug|x86.Build.0 = Debug|Any CPU + {DAE19E2F-B2BB-4778-B0F2-5FC48DC5975A}.Debug|x86.Deploy.0 = Debug|Any CPU + {DAE19E2F-B2BB-4778-B0F2-5FC48DC5975A}.Release|Any CPU.ActiveCfg = Release|Any CPU + {DAE19E2F-B2BB-4778-B0F2-5FC48DC5975A}.Release|Any CPU.Build.0 = Release|Any CPU + {DAE19E2F-B2BB-4778-B0F2-5FC48DC5975A}.Release|x64.ActiveCfg = Release|x64 + {DAE19E2F-B2BB-4778-B0F2-5FC48DC5975A}.Release|x64.Build.0 = Release|x64 + {DAE19E2F-B2BB-4778-B0F2-5FC48DC5975A}.Release|x86.ActiveCfg = Release|x86 + {DAE19E2F-B2BB-4778-B0F2-5FC48DC5975A}.Release|x86.Build.0 = Release|x86 + {DF0EAD54-D31A-4C8A-ADF3-D4963C1DED01}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {DF0EAD54-D31A-4C8A-ADF3-D4963C1DED01}.Debug|Any CPU.Build.0 = Debug|Any CPU + {DF0EAD54-D31A-4C8A-ADF3-D4963C1DED01}.Debug|x64.ActiveCfg = Debug|x64 + {DF0EAD54-D31A-4C8A-ADF3-D4963C1DED01}.Debug|x64.Build.0 = Debug|x64 + {DF0EAD54-D31A-4C8A-ADF3-D4963C1DED01}.Debug|x86.ActiveCfg = Debug|Any CPU + {DF0EAD54-D31A-4C8A-ADF3-D4963C1DED01}.Release|Any CPU.ActiveCfg = Release|Any CPU + {DF0EAD54-D31A-4C8A-ADF3-D4963C1DED01}.Release|Any CPU.Build.0 = Release|Any CPU + {DF0EAD54-D31A-4C8A-ADF3-D4963C1DED01}.Release|x64.ActiveCfg = Release|x64 + {DF0EAD54-D31A-4C8A-ADF3-D4963C1DED01}.Release|x64.Build.0 = Release|x64 + {DF0EAD54-D31A-4C8A-ADF3-D4963C1DED01}.Release|x86.ActiveCfg = Release|x64 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {85DCECB3-CF29-4484-8CF1-B55638B3B124} + EndGlobalSection +EndGlobal diff --git a/Container.v12.suo b/Container.v12.suo new file mode 100644 index 0000000..dff67a1 Binary files /dev/null and b/Container.v12.suo differ diff --git a/Container/App.config b/Container/App.config new file mode 100644 index 0000000..4a63d5e --- /dev/null +++ b/Container/App.config @@ -0,0 +1,35 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Container/App.xaml b/Container/App.xaml new file mode 100644 index 0000000..41c917a --- /dev/null +++ b/Container/App.xaml @@ -0,0 +1,10 @@ + + + /Container;Component/Resources/DINPro-Regular.otf#DINPro + /Container;Component/Resources/SourceHanSansCN-Regular.otf#Source Han Sans CN + /Container;Component/Resources/BROWNSTD REGULAR.otf#BrownStd + + diff --git a/Container/App.xaml.cs b/Container/App.xaml.cs new file mode 100644 index 0000000..49de3de --- /dev/null +++ b/Container/App.xaml.cs @@ -0,0 +1,328 @@ +using System; +using System.Collections.Generic; +using System.Configuration; +using System.Data; +using System.Linq; +using System.Threading.Tasks; +using System.Windows; +using Container.Common; +using Container.Model; +using Container.Services; +using System.Diagnostics; +using Container.ChildWindows; +using Container.Viewmodel; +using Container.Win; +using Container.SaversViewModel; +using System.Threading; + +namespace Container +{ + /// + /// App.xaml 的交互逻辑 + /// + public partial class App : Application + { + internal string shutdowntime; + internal AppListModel NowNeedPlayApp;//当前时间段需要播放的app(时间轴或默认) + internal string mallCode = ""; + internal string mallRegKey = ""; + internal string configurl = "http://192.168.0.250"; + internal string configHttpUrl = ""; + internal string SecurityKey = CommonLib.StringDecode("==wchF2UNFVO4cjN1QzMyEDM"); + + internal string configstartexe = ""; + internal string configwebsocket = "ws://192.168.0.250:8080"; + internal string configport = "8888"; + internal string BuildingID = ""; + internal string Floor = ""; + internal string HttpUrl = "";// + internal string LocalIP = "";//本机IP + internal string DeviceType = "";//设备类型 + internal string appUrl = "";//下载应用程序的路径 + internal string appName = "";//应用下载文件名 + //internal List NowAppList = new List(); + internal bool appClick = false;//应用下载文件名 + + internal string NowAppType = "";//当前应用类型,exe、html。。 + internal string deviceid = "";//设备编号 + internal string devicemark = "";//设备备注 + internal List Buildinginfo = new List();//楼栋列表 + internal List DeviceTypeList = new List();//设备类型字典 + internal List AppList = new List(); + internal List AppTimeList = new List(); + internal List Floors = new List();//楼层列表 + //internal string Programname = "";//默认启动的程序名 + internal string AppPlayDir = "";//需要播放的应用所在的文件夹名 + internal string AppPlayName = "";//需要播放的应用启动文件名 + internal string CurAppPlayName = "";//当前应用名称 + internal string AppPlayNameCH = "";//中文名称 + internal string Appversion = "";//应用版本号 + internal string Containerversion = "";//容器版本号 + //internal bool AppUpdate = false;//是否已更新 + //internal string AppDownCode = "";//应用下线 + //internal ExeModel Appdowninfo = new ExeModel();//应用下载对象 + //internal ExeModel AppStartinfo = new ExeModel();//应用启动对象 + internal AppListModel AppPlayinfo = new AppListModel();//当前应用对象 + //internal List exeinfo = new List();//应用列表 + //internal string icourl = "";//应用图标路径 + //internal InsertADModel insertAD=new InsertADModel(); + internal string bgPath = ""; + internal BGPage pageBg; + //internal string defaultFile = ""; + internal Screensaver screensaver = new Screensaver() { EffectType = 1, ScreenEffect = 1, ScreenFile = "", ScreenType = 0 ,ScreenTime=30}; + //internal int screenTime = 30; + internal RabbitMQModel rabbitMQ = new RabbitMQModel(); + + internal bool isStartScreen = false; + Class_Log log = new Class_Log(); + internal List TopSubTitle = new List { }; + internal List BottomSubTitle = new List { }; + internal int TopSubTitleIndex = 0; + internal int BottomSubTitleIndex = 0; + //internal string kioskUrl = ""; + internal static bool Downloaddone = false; + internal int currentIndex = 0; + //internal WindowView view; + //internal Screensaver screensaver = new Screensaver() { EffectType = 1, ScreenEffect = 1, ScreenFile = "", ScreenType = 0 }; + internal NavViewModel navModel = new NavViewModel(); + System.Threading.Mutex mutex; + internal bool isProgramServer = false; + internal bool isProgramSync = false; + internal bool isSendSync = false; + internal string websocketProgramIP = string.Empty; + internal WebsocketForProgramServer websocketForProgramServer = null; + internal WebSocketForProgram webSocketForProgram = null; + internal string kioskUrl = ""; + internal bool IsCanConnect = true; + internal Live live = new Live(); + internal CurrentLive curLive = new CurrentLive(); + internal bool LiveReload = false; + internal bool isLoadLive = false; + internal DateTime? CloseServerTime = null; + internal List playProgList = new List(); + internal List shutDownProgList = new List(); + internal string BGFile = string.Empty; + internal string defaultCity = string.Empty; + internal bool isCheckServerTime = false; + internal string kioskVersion = ""; + internal string screenshotUserName = ""; + //internal bool isStartHeat = false; + + internal bool IsDownScreen = false; + internal string screenConfig = string.Empty; + internal int downErrorTime = 0; + internal string FileServerPath = string.Empty; + internal string OBSPath = string.Empty; + internal double ScreenWidth = 0; + internal double ScreenHeight = 0; + internal bool isStartGetProg = false; + string info = ""; + public MainWindow main; + + private void Application_Startup(object sender, StartupEventArgs e) + { + Class_Log clog = new Class_Log(); + bool ret; + mutex = new System.Threading.Mutex(true, "WpfMuerterrrterterttex11", out ret); + if (!ret) + { + // MessageBox.Show("程序已启动"); + Environment.Exit(0); + } + + try + { + this.configHttpUrl = ConfigurationManager.AppSettings["HttpUrl"]; + if (!string.IsNullOrEmpty(this.configHttpUrl)) + { + this.HttpUrl = this.configHttpUrl; + this.configurl = this.configHttpUrl; + } + + bool update = true; + clog.WriteLogFile("收到:" + e.Args.Count(), "Loadargs"); + if (e.Args.Count() > 0) + { + clog.WriteLogFile("收到:" + e.Args[0].ToString(), "Loadargs"); + string[] inf = e.Args[0].ToString().Split('&'); + clog.WriteLogFile("inf.Count():" + inf.Count().ToString(), "Loadargs"); + if (inf.Count() > 1) + update = false; + } + if (update) + { + //System.Security.Principal.WindowsIdentity identity1 = System.Security.Principal.WindowsIdentity.GetCurrent(); + ////创建Windows用户主题 + //System.Windows.Forms.Application.EnableVisualStyles(); + //System.Security.Principal.WindowsPrincipal principal1 = new System.Security.Principal.WindowsPrincipal(identity1); + ////判断当前登录用户是否为管理员 + //if (!principal1.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator)) + //{ + // //创建启动对象 + // System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo(); + // //设置运行文件 + // startInfo.WorkingDirectory = System.Windows.Forms.Application.ExecutablePath.Replace("\\", "/").Substring(0, System.Windows.Forms.Application.ExecutablePath.Replace("\\", "/").LastIndexOf("/"));//设置应用程序在其所在目录 + // startInfo.FileName = startInfo.WorkingDirectory + "/ConUpdate.exe"; //设置启动参数 + // startInfo.Arguments = info; + // //设置启动动作,确保以管理员身份运行 + // startInfo.Verb = "runas"; + // //如果不是管理员,则启动UAC + // //log.WriteLogFile("工作路径:" + startInfo.WorkingDirectory, "APPError"); + // System.Diagnostics.Process.Start(startInfo); + // //退出 + // System.Windows.Forms.Application.Exit(); + + // //System.Diagnostics.Process p = new System.Diagnostics.Process(); + // //p.StartInfo.WorkingDirectory = System.Windows.Forms.Application.ExecutablePath.Replace("\\", "/").Substring(0, System.Windows.Forms.Application.ExecutablePath.Replace("\\", "/").LastIndexOf("/"));//设置应用程序在其所在目录 + // //p.StartInfo.FileName = p.StartInfo.WorkingDirectory + "/PCScreenSavers.exe"; + // //p.StartInfo.Arguments = app.info; + // //p.StartInfo.Verb = "runas"; + // //p.StartInfo.UseShellExecute = false; //是否使用操作系统shell启动 + // //p.StartInfo.RedirectStandardInput = true;//接受来自调用程序的输入信息 + // //p.StartInfo.RedirectStandardOutput = true;//由调用程序获取输出信息 + // //p.StartInfo.RedirectStandardError = true;//重定向标准错误输出 + // ////p.ProcessNa = "PCScreenUpdate"; + // //p.StartInfo.CreateNoWindow = false;//不显示程序窗口 + // //p.Start();//启动程序 + //} + //else + //{ + // System.Diagnostics.Process p = new System.Diagnostics.Process(); + // p.StartInfo.WorkingDirectory = System.Windows.Forms.Application.ExecutablePath.Replace("\\", "/").Substring(0, System.Windows.Forms.Application.ExecutablePath.Replace("\\", "/").LastIndexOf("/"));//设置应用程序在其所在目录 + // p.StartInfo.FileName = p.StartInfo.WorkingDirectory + "/ConUpdate.exe"; + // p.StartInfo.Arguments = info; + // p.StartInfo.UseShellExecute = false; //是否使用操作系统shell启动 + // p.StartInfo.RedirectStandardInput = true;//接受来自调用程序的输入信息 + // p.StartInfo.RedirectStandardOutput = true;//由调用程序获取输出信息 + // p.StartInfo.RedirectStandardError = true;//重定向标准错误输出 + // p.StartInfo.CreateNoWindow = false;//不显示程序窗口 + // p.Start();//启动程序 + //} + StartConUpdate(info); + Environment.Exit(0); + } + + + + } + catch (Exception ex) + { + clog.WriteLogFile(ex.ToString()); + } + try + { + System.Security.Principal.WindowsIdentity identity = System.Security.Principal.WindowsIdentity.GetCurrent(); + //创建Windows用户主题 + System.Windows.Forms.Application.EnableVisualStyles(); + Class_Log log = new Class_Log(); + + System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(identity); + //判断当前登录用户是否为管理员 + if (!principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator)) + { + //创建启动对象 + System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo(); + //设置运行文件 + startInfo.FileName = System.Windows.Forms.Application.ExecutablePath; + + startInfo.WorkingDirectory = System.Windows.Forms.Application.ExecutablePath.Replace("\\", "/").Substring(0, System.Windows.Forms.Application.ExecutablePath.Replace("\\", "/").LastIndexOf("/"));//设置应用程序在其所在目录 + //设置启动参数 + startInfo.Arguments = String.Join(" ", e); + //设置启动动作,确保以管理员身份运行 + startInfo.Verb = "runas"; + //如果不是管理员,则启动UAC + System.Diagnostics.Process.Start(startInfo); + //退出 + System.Windows.Forms.Application.Exit(); + } + else + { + AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException); + Application.Current.DispatcherUnhandledException += new System.Windows.Threading.DispatcherUnhandledExceptionEventHandler(Current_DispatcherUnhandledException); + MainWindow win = new MainWindow(); + main = win; + win.Show(); + } + } + catch (Exception ex) + { + clog.WriteLogFile(ex.ToString()); + // MessageBox.Show("程序启动失败"); + } + } + + + private void Current_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e) + { + log.WriteLogFile(e.Exception.Message + e.Exception.StackTrace, "APPError"); + log.WriteLogFile("---111--" + e.ToString(), "APPError"); + StartConUpdate(info); + Environment.Exit(0); + } + + private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) + { + Exception ex = (Exception)e.ExceptionObject; + log.WriteLogFile(ex.Message + ex.StackTrace, "APPError"); + log.WriteLogFile("-----"+ex.ToString(), "APPError"); + StartConUpdate(info); + Environment.Exit(0); + } + + void App_Startup(object sender, StartupEventArgs e) + { + + } + + private void StartConUpdate(string info) { + System.Security.Principal.WindowsIdentity identity1 = System.Security.Principal.WindowsIdentity.GetCurrent(); + //创建Windows用户主题 + System.Windows.Forms.Application.EnableVisualStyles(); + System.Security.Principal.WindowsPrincipal principal1 = new System.Security.Principal.WindowsPrincipal(identity1); + //判断当前登录用户是否为管理员 + if (!principal1.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator)) + { + //创建启动对象 + System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo(); + //设置运行文件 + startInfo.WorkingDirectory = System.Windows.Forms.Application.ExecutablePath.Replace("\\", "/").Substring(0, System.Windows.Forms.Application.ExecutablePath.Replace("\\", "/").LastIndexOf("/"));//设置应用程序在其所在目录 + startInfo.FileName = startInfo.WorkingDirectory + "/ConUpdate.exe"; //设置启动参数 + startInfo.Arguments = info; + //设置启动动作,确保以管理员身份运行 + startInfo.Verb = "runas"; + //如果不是管理员,则启动UAC + //log.WriteLogFile("工作路径:" + startInfo.WorkingDirectory, "APPError"); + System.Diagnostics.Process.Start(startInfo); + //退出 + System.Windows.Forms.Application.Exit(); + + //System.Diagnostics.Process p = new System.Diagnostics.Process(); + //p.StartInfo.WorkingDirectory = System.Windows.Forms.Application.ExecutablePath.Replace("\\", "/").Substring(0, System.Windows.Forms.Application.ExecutablePath.Replace("\\", "/").LastIndexOf("/"));//设置应用程序在其所在目录 + //p.StartInfo.FileName = p.StartInfo.WorkingDirectory + "/PCScreenSavers.exe"; + //p.StartInfo.Arguments = app.info; + //p.StartInfo.Verb = "runas"; + //p.StartInfo.UseShellExecute = false; //是否使用操作系统shell启动 + //p.StartInfo.RedirectStandardInput = true;//接受来自调用程序的输入信息 + //p.StartInfo.RedirectStandardOutput = true;//由调用程序获取输出信息 + //p.StartInfo.RedirectStandardError = true;//重定向标准错误输出 + ////p.ProcessNa = "PCScreenUpdate"; + //p.StartInfo.CreateNoWindow = false;//不显示程序窗口 + //p.Start();//启动程序 + } + else + { + System.Diagnostics.Process p = new System.Diagnostics.Process(); + p.StartInfo.WorkingDirectory = System.Windows.Forms.Application.ExecutablePath.Replace("\\", "/").Substring(0, System.Windows.Forms.Application.ExecutablePath.Replace("\\", "/").LastIndexOf("/"));//设置应用程序在其所在目录 + p.StartInfo.FileName = p.StartInfo.WorkingDirectory + "/ConUpdate.exe"; + p.StartInfo.Arguments = info; + p.StartInfo.UseShellExecute = false; //是否使用操作系统shell启动 + p.StartInfo.RedirectStandardInput = true;//接受来自调用程序的输入信息 + p.StartInfo.RedirectStandardOutput = true;//由调用程序获取输出信息 + p.StartInfo.RedirectStandardError = true;//重定向标准错误输出 + p.StartInfo.CreateNoWindow = false;//不显示程序窗口 + p.Start();//启动程序 + } + } + + } +} diff --git a/Container/Business/DownLoadMethod.cs b/Container/Business/DownLoadMethod.cs new file mode 100644 index 0000000..9452917 --- /dev/null +++ b/Container/Business/DownLoadMethod.cs @@ -0,0 +1,564 @@ +using Container.Common; +using Container.Model; +using System; +using System.Collections.Generic; +using System.IO; +using System.IO.Compression; +using System.Linq; +using System.Net; +using System.Text; +using System.Threading.Tasks; +using System.Windows; + +namespace Container.Business +{ + public class DownLoadMethod + { + private Class_Log log = new Class_Log(); + private App app = ((App)Application.Current); + //public bool DownLoadZip(string url, string downloadFolder, string md5, out string errorMsg, bool isback = true, bool isupdate = true) + //{ + // bool flag = false; + // errorMsg = string.Empty; + // try + // { + // if (!Directory.Exists(downloadFolder)) + // { + // Directory.CreateDirectory(downloadFolder); + // } + // WebClientPro webClient = new WebClientPro(30 * 60 * 1000); + // string fileName = url.Substring(url.Replace("\\", "/").Replace(@"\", "/").LastIndexOf('/') + 1); + // if (fileName.Contains("?")) + // { + // fileName = fileName.Substring(0, fileName.IndexOf('?')); + // } + // string downUrl = downloadFolder + @"\" + fileName; + // //下载更新包 + // webClient.DownloadFile(url, downUrl); + // string localMD5 = GetMD5HashFromFile(downUrl); + // if (!string.IsNullOrEmpty(md5) && md5 != localMD5) + // { + // errorMsg = "MD5校验不合格"; + // File.Delete(downUrl); + // return flag; + // } + + // string UpdateReleasePath = downloadFolder + @"/temp/"; + // //解压更新包至指定路径 + // if (Directory.Exists(UpdateReleasePath)) + // { + // DeleteDir(UpdateReleasePath, 1); + // Directory.CreateDirectory(UpdateReleasePath); + // } + // ZipFile.ExtractToDirectory(downUrl, UpdateReleasePath); + // string mainpropath = downloadFolder + @"\Main"; + // DirectoryInfo di = new DirectoryInfo(mainpropath);//正式包路径 + // DirectoryInfo di2 = new DirectoryInfo(UpdateReleasePath);//更新包解压路径 + + + + // if (isback) + // { + // DirectoryInfo source = new DirectoryInfo(downloadFolder); + // DirectoryInfo[] dirs = source.GetDirectories(); + + // foreach (DirectoryInfo dir in dirs) + // { + // log.WriteLogFile(mainpropath + "----" + dir.Name.Length + "----" + mainpropath.Length, "更新"); + // if (dir.Name.Contains("Main") && dir.Name.Length > 4) + // { + // DeleteDir(dir.FullName, 1); + // } + // } + // DirectoryInfo diback = new DirectoryInfo(mainpropath + DateTime.Now.ToString("yyyyMMddHHmmss"));//正式包路径 + // MoveDirectory(di, diback, true); //复制子目录 + // } + // if (isupdate) + // { + // MoveDirectory(di2, di, true); //复制子目录 + // } + + // flag = true; + // } + // catch (Exception e) + // { + // flag = false; + // errorMsg = e.Message; + // log.WriteLogFile(e.ToString(), "DownLoadZipError"); + // } + // return flag; + //} + + /// + /// 获取文件MD5 哈希码 + /// + /// + /// + public string GetMD5HashFromFile(string fileName) + { + try + { + FileStream file = new FileStream(fileName, FileMode.Open); + System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider(); + byte[] retVal = md5.ComputeHash(file); + file.Close(); + + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < retVal.Length; i++) + { + sb.Append(retVal[i].ToString("x2")); + } + return sb.ToString(); + } + catch (Exception ex) + { + log.WriteLogFile("GetMD5HashFromFile() fail, error:" + ex.ToString(), "downloaderror"); + return ""; + } + } + + public static string ReadContext(string path) + { + + try + { + if (File.Exists(path)) + { + FileStream fs = new FileStream(path, FileMode.Open); + StreamReader sr = new StreamReader(fs, System.Text.Encoding.UTF8); + string context = sr.ReadToEnd(); + fs.Close(); + sr.Close(); + sr.Dispose(); + fs.Dispose(); + + return context; + } + else + { + return ""; + } + } + catch (Exception ex) + { + Class_Log log = new Class_Log(); + log.WriteLogFile(ex.ToString(), "Temp113"); + ReadContext(path); + return ""; + } + } + + public void DeleteDir(string srcPath, int isSelf = 0) + { + try + { + if (!Directory.Exists(srcPath)) + { + return; + } + DirectoryInfo dir = new DirectoryInfo(srcPath); + FileSystemInfo[] fileinfo = dir.GetFileSystemInfos(); //返回目录中所有文件和子目录 + foreach (FileSystemInfo i in fileinfo) + { + try + { + if (i is DirectoryInfo) //判断是否文件夹 + { + DirectoryInfo subdir = new DirectoryInfo(i.FullName); + subdir.Delete(true); //删除子目录和文件 + } + else + { + //如果 使用了 streamreader 在删除前 必须先关闭流 ,否则无法删除 sr.close(); + File.Delete(i.FullName); //删除指定文件 + } + } + catch (Exception) + { + + + } + } + if (isSelf == 1) + { + dir.Delete(); + } + } + catch (Exception e) + { + log.WriteLogFile("DeleteDir:" + e.Message, "downloaderror"); + } + } + + /// + /// 拷贝目录内容 + /// + /// 源目录 + /// 目的目录 + /// 是否拷贝子目录 + public void CopyDirectory(DirectoryInfo source, DirectoryInfo destination, bool copySubDirs) + { + + if (!destination.Exists) + { + destination.Create(); //目标目录若不存在就创建 + } + FileInfo[] files = source.GetFiles(); + foreach (FileInfo file in files) + { + file.CopyTo(Path.Combine(destination.FullName, file.Name), true); //复制目录中所有文件,替换相同文件 + } + if (copySubDirs) + { + DirectoryInfo[] dirs = source.GetDirectories(); + foreach (DirectoryInfo dir in dirs) + { + string destinationDir = Path.Combine(destination.FullName, dir.Name); + CopyDirectory(dir, new DirectoryInfo(destinationDir), copySubDirs); //复制子目录 + } + } + + } + + /// + /// 拷贝目录内容,删除本身 + /// + /// 源目录 + /// 目的目录 + /// 是否拷贝子目录 + public void MoveDirectory(DirectoryInfo source, DirectoryInfo destination, bool copySubDirs) + { + if (!destination.Exists) + { + destination.Create(); //目标目录若不存在就创建 + } + FileInfo[] files = source.GetFiles(); + foreach (FileInfo file in files) + { + file.CopyTo(Path.Combine(destination.FullName, file.Name), true); //复制目录中所有文件,替换相同文件 + file.Delete(); + } + + if (copySubDirs) + { + DirectoryInfo[] dirs = source.GetDirectories(); + + foreach (DirectoryInfo dir in dirs) + { + string destinationDir = Path.Combine(destination.FullName, dir.Name); + MoveDirectory(dir, new DirectoryInfo(destinationDir), copySubDirs); //复制子目录 + } + if (source.GetDirectories().Length == 0) + source.Delete(); + } + } + + + + bool done = false; + private string outLinePath = AppDomain.CurrentDomain.BaseDirectory + "/OutlineFiles"; + public bool DownLoadScreenConfig(List ScheduleList, string configStr) + { + if (!done) + { + done = true; + log.WriteLogFile("开始下载", "exelog"); + try + { + int downerrorCount = 0; + foreach (var resource in ScheduleList) + { + if (resource == null || resource.schedule == null || resource.schedule.Count == 0) + { + continue; + } + foreach (var item in resource.schedule) + { + if (item != null && item.programs != null) + { + foreach (var itemprogram in item.programs) + { + if (itemprogram.backgroundMaterialInfo != null) + { + var localFileName = string.Empty; + if (localFileName.Contains('?')) + { + localFileName = itemprogram.backgroundMaterialInfo.fileHash + itemprogram.backgroundMaterialInfo.filePath.Substring(itemprogram.backgroundMaterialInfo.filePath.LastIndexOf("."), itemprogram.backgroundMaterialInfo.filePath.LastIndexOf("?") - itemprogram.backgroundMaterialInfo.filePath.LastIndexOf(".")); + } + else + { + localFileName = itemprogram.backgroundMaterialInfo.fileHash + itemprogram.backgroundMaterialInfo.filePath.Substring(itemprogram.backgroundMaterialInfo.filePath.LastIndexOf(".")); + } + bool flag = DownLoadFile(itemprogram.backgroundMaterialInfo.filePath, localFileName, itemprogram.backgroundMaterialInfo.fileHash); + if (!flag) + { + downerrorCount += 1; + } + } + foreach (var itemcomponent in itemprogram.components) + { + if (itemcomponent.materials != null) + { + foreach (var material in itemcomponent.materials) + { + if (string.IsNullOrEmpty(material.fileUrl)) + { + continue; + } + var localFileName = string.Empty; + if (localFileName.Contains('?')) + { + localFileName = material.fileHash + material.fileUrl.Substring(material.fileUrl.LastIndexOf("."), material.fileUrl.LastIndexOf("?") - material.fileUrl.LastIndexOf(".")); + } + else + { + localFileName = material.fileHash + material.fileUrl.Substring(material.fileUrl.LastIndexOf(".")); + } + bool flag = DownLoadFile(material.fileUrl, localFileName, material.fileHash); + if (!flag) + { + downerrorCount += 1; + } + } + } + } + } + } + } + } + + if (downerrorCount > 0) + { + done = false; + return false; + } + else + { + bool flag = Write(outLinePath + "/temp/screenconfig.txt", configStr); + if (flag) + { + //DeleteDir(outLinePath + "/Main", 0); + DirectoryInfo di = new DirectoryInfo(outLinePath + "/Main");//正式包路径 + DirectoryInfo di2 = new DirectoryInfo(outLinePath + "/temp");//更新包解压路径 + MergeDirectory(di2, di, true); + done = false; + return true; + } + else + { + done = false; + return false; + } + } + } + catch (Exception ex) + { + log.WriteLogFile(ex.ToString(), "OutLineLog"); + done = false; + return false; + } + finally + { + done = false; + } + } + else + { + return false; + } + } + + private bool DownLoadFile(string filePath, string localFileName, string hash) + { + try + { + filePath = app.FileServerPath + filePath; + filePath = filePath.Replace(@"\", @"/"); + var tempFolder = outLinePath + "/temp"; + var mainFolder = outLinePath + "/Main"; + if (!Directory.Exists(tempFolder)) + { + Directory.CreateDirectory(tempFolder); + } + if (!File.Exists(tempFolder + "/" + localFileName)) + { + if (!File.Exists(mainFolder + "/" + localFileName)) + { + if (File.Exists(tempFolder + "/" + localFileName)) + { + return true; + } + if (File.Exists(tempFolder + "/" + localFileName + ".temp")) + File.Delete(tempFolder + "/" + localFileName + ".temp"); + using (Stream fileStream = new FileStream(tempFolder + "/" + localFileName + ".temp", FileMode.OpenOrCreate)) + { + try + { + HttpWebRequest request = (HttpWebRequest)WebRequest.Create(filePath); + request.AddRange(fileStream.Length); + + HttpWebResponse respone = (HttpWebResponse)request.GetResponse(); + using (Stream netStream = respone.GetResponseStream()) + { + long totalDownloadedByte = 0; + byte[] read = new byte[1024]; + int realReadLen = netStream.Read(read, 0, read.Length); + while (realReadLen > 0) + { + totalDownloadedByte = realReadLen + totalDownloadedByte; + + fileStream.Write(read, 0, realReadLen); + realReadLen = netStream.Read(read, 0, read.Length); + + System.Windows.Forms.Application.DoEvents(); + } + netStream.Close(); + } + if (fileStream.Length != respone.ContentLength) + { + log.WriteLogFile("文件未下载完毕", "文件"); + } + fileStream.Close(); + log.WriteLogFile("下载完成" + tempFolder + "/" + localFileName, "exelog"); + File.Move(tempFolder + "/" + localFileName + ".temp", tempFolder + "/" + localFileName); + + + + var fileHash = GetMD5HashFromFile(tempFolder + "/" + localFileName); + if (fileHash != hash) + { + log.WriteLogFile("localFile " + fileHash + " getHash:" + hash, "exelog"); + File.Delete(tempFolder + "/" + localFileName); + log.WriteLogFile("FileHash对比不一致,须删除重新下载" + tempFolder + "/" + localFileName, "exelog"); + return false; + } + + } + catch (Exception ex) + { + fileStream.Close(); + log.WriteLogFile("下载失败" + tempFolder + "/" + localFileName + ex.ToString(), "exelog"); + File.Delete(tempFolder + "/" + localFileName + ".temp"); + log.WriteLogFile(ex.ToString(), "OutLineLog"); + return false; + } + } + } + else + { + File.Copy(mainFolder + "/" + localFileName, tempFolder + "/" + localFileName); + } + } + return true; + } + catch (Exception e) + { + log.WriteLogFile(e.ToString(), "OutLineLog"); + return false; + } + } + + public bool Write(string path, string configStr) + { + try + { + if (!Directory.Exists(outLinePath + "/temp")) + { + Directory.CreateDirectory(outLinePath + "/temp"); + } + FileStream fs = new FileStream(path, FileMode.Create); + StreamWriter sw = new StreamWriter(fs); + //开始写入 + sw.Write(configStr); + //清空缓冲区 + sw.Flush(); + //关闭流 + sw.Close(); + fs.Close(); + return true; + } + catch (Exception) + { + + return false; + } + } + + /// + /// 拷贝目录内容,删除本身 + /// + /// 源目录 + /// 目的目录 + /// 是否拷贝子目录 + public void MergeDirectory(DirectoryInfo source, DirectoryInfo destination, bool copySubDirs) + { + if (!destination.Exists) + { + destination.Create(); //目标目录若不存在就创建 + } + if (!source.Exists) + { + source.Create(); //目标目录若不存在就创建 + } + FileInfo[] sourceFiles = source.GetFiles(); + FileInfo[] destinationFiles = destination.GetFiles(); + foreach (var item in sourceFiles) + { + if (item.Extension.Contains("txt")) + { + item.CopyTo(Path.Combine(destination.FullName, item.Name), true); + } + else if ((!File.Exists(Path.Combine(destination.FullName, item.Name)))) + { + CopyTo(item, Path.Combine(destination.FullName, item.Name)); + //item.CopyTo(Path.Combine(destination.FullName, item.Name),true); + } + } + + foreach (var item in destinationFiles) + { + if (!File.Exists(Path.Combine(source.FullName, item.Name))) + { + try + { + item.Delete(); + } + catch (Exception) + { + + + } + } + } + DeleteDir(source.FullName, 1); + } + + private void CopyTo(FileInfo tempFile, string mainFilePath) + { + try + { + string fileTempMD5 = GetMD5HashFromFile(tempFile.FullName); + tempFile.CopyTo(mainFilePath, true); + string fileMainMD5 = GetMD5HashFromFile(mainFilePath); + if (fileTempMD5 != fileMainMD5) + { + File.Delete(mainFilePath); + CopyTo(tempFile, mainFilePath); + } + else + { + File.Delete(tempFile.FullName); + } + } + catch (Exception e) + { + log.WriteLogFile(e.ToString(), "copyError"); + if (File.Exists(mainFilePath)) + { + File.Delete(mainFilePath); + } + CopyTo(tempFile, mainFilePath); + } + } + } +} diff --git a/Container/Business/JService.cs b/Container/Business/JService.cs new file mode 100644 index 0000000..8888bf8 --- /dev/null +++ b/Container/Business/JService.cs @@ -0,0 +1,569 @@ +using Container.Common; +using Container.Model; +using Container.Services; +using Container.Viewmodel; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Net; +using System.Text; +using System.Threading; +using System.Windows; +using System.Xml; + +namespace Container.Business +{ + public class ItemInfo + { + public int id { get; set; } + + public string img { get; set; } + + public int time { get; set; } + + public string effect { get; set; } + + //public string text { get; set; } + + public string screenmatch { get; set; } + + public string code { get; set; } + public string launchtime { get; set; } + public string expirydate { get; set; } + public string protype { get; set; } + public string xaxis { get; set; } + + public string yaxis { get; set; } + + public string devNum { get; set; } + + public string floorOrder { get; set; } + public string applets { get; set; } + + public ShopInfo shopInfo { get; set; } + } + + public class ShopInfo + { + public string FloorName { get; set; } + + public string ShopName { get; set; } + + public string LogoPath { get; set; } + + public string Angle { get; set; } + + public string houseNum { get; set; } + public string shopFormatIcon { get; set; } + public string shopFormatName { get; set; } + } + public class JService + { + App app = ((App)Application.Current); + //private string localIP = app.LocalIP; + //private string remoteAddress = ConfigurationManager.AppSettings["RemoteAddress"]; + Class_Log Mylog = new Class_Log(); + public delegate void ScreenConfigDelegate(); + public static event ScreenConfigDelegate ScreenConfigReceiveEvent; + ///// + ///// 绑定ip + ///// + //public bool BindIp() + //{ + // string urlString = string.Format("http://{0}/shanjing/interFace/kioskBinding.do?ip={1}", remoteAddress, localIP); + // string ret = GetHttpResponse(urlString); + + // if (string.IsNullOrEmpty(ret)) + // return false; + // else + // return true; + //} + public string WriteToConfig(List itemList, string code) + { + try + { + + XmlDocument doc = new XmlDocument(); // 创建dom对象 + + XmlElement root = doc.CreateElement("root"); // 创建根节点 + + doc.AppendChild(root); // 加入到xml document + XmlElement FillItem; // 创建FillItem元素 + + FillItem = doc.CreateElement("code"); + FillItem.InnerText = code; + root.AppendChild(FillItem); // 添加到xml document + FillItem = doc.CreateElement("items"); + if (itemList != null && itemList.Count > 0) + { + for (int i = 0; i < itemList.Count; i++) + { + XmlElement Node = doc.CreateElement("item"); + Node.SetAttribute("id", itemList[i].id.ToString()); + Node.SetAttribute("img", itemList[i].img); + Node.SetAttribute("time", itemList[i].time.ToString()); + Node.SetAttribute("effect", itemList[i].effect); + Node.SetAttribute("screenmatch", itemList[i].screenmatch); + Node.SetAttribute("launchtime", itemList[i].launchtime); + Node.SetAttribute("expirydate", itemList[i].expirydate); + Node.SetAttribute("protype", itemList[i].protype); + Node.SetAttribute("code", itemList[i].code); + Node.SetAttribute("xaxis", itemList[i].xaxis); + Node.SetAttribute("yaxis", itemList[i].yaxis); + Node.SetAttribute("floorOrder", itemList[i].floorOrder); + Node.SetAttribute("devNum", itemList[i].devNum); + Node.SetAttribute("applets", itemList[i].applets); + Node.SetAttribute("floorName", itemList[i].shopInfo == null ? "" : itemList[i].shopInfo.FloorName); + Node.SetAttribute("shopName", itemList[i].shopInfo == null ? "" : itemList[i].shopInfo.ShopName); + Node.SetAttribute("logoPath", itemList[i].shopInfo == null ? "" : itemList[i].shopInfo.LogoPath); + Node.SetAttribute("houseNum", itemList[i].shopInfo == null ? "" : itemList[i].shopInfo.houseNum); + Node.SetAttribute("shopFormatIcon", itemList[i].shopInfo == null ? "" : itemList[i].shopInfo.shopFormatIcon); + Node.SetAttribute("shopFormatName", itemList[i].shopInfo == null ? "" : itemList[i].shopInfo.shopFormatName); + + FillItem.AppendChild(Node); + } + } + root.AppendChild(FillItem); + + + + MemoryStream stream = new MemoryStream(); + XmlTextWriter writer = new XmlTextWriter(stream, null); + writer.Formatting = System.Xml.Formatting.Indented; + doc.Save(writer); + StreamReader sr = new StreamReader(stream, Encoding.UTF8); + + stream.Position = 0; + + string XMLString = sr.ReadToEnd(); + Mylog.WriteLogFile(XMLString, "XMLString"); + sr.Close(); + writer.Flush(); + writer.Close(); + stream.Flush(); + stream.Close(); + + return XMLString; + + + } + catch (Exception ex) + { + Mylog.WriteLogFile(ex.ToString(), "JServiceErrorLog"); + return ""; + } + } + /// + /// 获取后台图片或视频资源地址 + /// + /// + public bool GetOutLineResource() + { + bool flag = false; + try + { + string MethodStr = "/Api/Programme/DevProgrammeList"; + var data = new { DevCode = app.deviceid }; + var ret = MyHttpClient.CryptPost(MethodStr, data, app.HttpUrl); + Mylog.WriteLogFile(ret, "HttpClient"); + //ret= DownLoadMethod.ReadContext(AppDomain.CurrentDomain.BaseDirectory + "/OutlineFiles/1.txt"); + if (!string.IsNullOrEmpty(ret)) + { + app.isStartGetProg = false; + string oldConfig = DownLoadMethod.ReadContext(AppDomain.CurrentDomain.BaseDirectory + "/OutlineFiles/Main/screenconfig.txt"); + if (ret != oldConfig) + { + + var Jo = JObject.Parse(ret); + string code = Jo.Value("code"); + if (code == "200") + { + if (app.IsDownScreen) + { + app.screenConfig = ret; + } + else + { + app.downErrorTime = 0; + DownScreen(ret); + } + return true; + //DownLoadMethod downLoadMethod = new DownLoadMethod(); + //flag = downLoadMethod.DownLoadScreenConfig(itemList, ret); + //if (flag) { + + //} + } + } + } + else + { + if (app.isStartGetProg) + { + Thread.Sleep(30000); + GetOutLineResource(); + } + } + + } + catch (Exception ex) + { + Mylog.WriteLogFile(ex.ToString(), "JServiceErrorLog"); + } + return flag; + } + + private void DownScreen(string revScreen) + { + try + { + + var Jo = JObject.Parse(revScreen); + List itemList = Jo.Value("data").ToObject>(); + + Action action = new Action(() => + { + // List itemList = Jo.Value("data").ToObject>(); + app.IsDownScreen = true; + DownLoadMethod downLoadMethod = new DownLoadMethod(); + bool flag = downLoadMethod.DownLoadScreenConfig(itemList, revScreen); + if (flag) + { + ScreenConfigReceiveEvent?.Invoke(); + if (!string.IsNullOrEmpty(app.screenConfig)) + { + + DownScreen(app.screenConfig); + app.screenConfig = string.Empty; + app.downErrorTime = 0; + } + else + { + app.IsDownScreen = false; + } + } + else + { + + if (!string.IsNullOrEmpty(app.screenConfig)) + { + DownScreen(app.screenConfig); + app.screenConfig = string.Empty; + app.downErrorTime = 0; + } + else + { + if (app.downErrorTime < 100) + { + Thread.Sleep(1000); + DownScreen(revScreen); + app.downErrorTime++; + } + else + { + app.downErrorTime = 0; + app.IsDownScreen = false; + } + + + } + } + //config.WriteToScreenConfig(); + }); + action.BeginInvoke(null, null); + + } + catch (Exception e) + { + + Mylog.WriteLogFile(e.ToString(), "HttpClientError"); + } + } + + + /// + /// 获取天气 + /// + /// + public WeatherViewModel GetEnvironmental(string city) + { + WeatherViewModel weather = new WeatherViewModel(); + try + { + + //string urlString = string.Format("{0}/API/CDN/GetEnvironmentalData", app.kioskUrl); + //string ret = GetHttpResponse(urlString); + HttpClient httpclient = new HttpClient(); + StringBuilder sb = new StringBuilder(); + sb.Append("{\"city\":\"" + city + "\"}"); + httpclient.message = sb.ToString(); + httpclient.url = "http://saas.1000my.com:8999/API/Weather/GetWeather"; + string ret = httpclient.PostMoths(httpclient.message, httpclient.url); + + + if (!string.IsNullOrEmpty(ret)) + { + Dictionary dic = JsonConvert.DeserializeObject>(ret); + if (!string.IsNullOrEmpty(dic["data"].ToString()) && dic["code"].ToString() == "200") + { + Dictionary dicdata = JsonConvert.DeserializeObject>(dic["data"].ToString()); + weather.aqi = dicdata["realAqi"].ToString(); + weather.humidity = dicdata["humidity"].ToString(); + weather.pm25 = dicdata["aqi"].ToString(); + weather.temperature = dicdata["temperature_Now"].ToString(); + weather.windPower = dicdata["wind_Power"].ToString(); + weather.status = dicdata["status"].ToString(); + } + } + } + catch (Exception ex) + { + Mylog.WriteLogFile("天气获取失败" + ex.ToString(), "JServiceErrorLog"); + } + return weather; + } + + public void SetPlayRecord() + { + try + { + + + StringBuilder record = new StringBuilder(); + string fpath = Directory.GetCurrentDirectory() + "\\record\\"; + if (!Directory.Exists(fpath)) + { + return; + } + + string fname = Directory.GetCurrentDirectory() + "\\record\\Record.txt"; + FileInfo finfo = new FileInfo(fname); + Mylog.WriteLogFile("文件地址" + fname, "UploadPlayRecord"); + if (!finfo.Exists) + { + return; + } + else + { + StreamReader sr = new StreamReader(fname, Encoding.Default); + String line; + while ((line = sr.ReadLine()) != null) + { + record.Append(line.ToString()); + } + sr.Close(); + + if (!string.IsNullOrEmpty(record.ToString())) + { + var array = JArray.Parse("[" + record + "]"); + //var list = Jo.Value("data").ToObject>(); + var data = new { DevCode = app.deviceid, List = array }; + Mylog.WriteLogFile("文件地址" + JsonConvert.SerializeObject(data), "UploadPlayRecord"); + string MethodStr = "/API/ProgramStatistics/UploadPlayRecord"; + var ret = MyHttpClient.CryptPost(MethodStr, data); + if (!string.IsNullOrEmpty(ret)) + { + var Jo = JObject.Parse(ret); + string code = Jo.Value("code"); + + if (code == "200") + { + File.Delete(fname); + + } + else + { + Mylog.WriteLogFile("上传节目播放统计错误" + ret, "UploadPlayRecordError"); + } + } + } + } + } + catch (Exception e) + { + + Mylog.WriteLogFile("上传节目播放统计错误" + e.ToString(), "UploadPlayRecordError"); + } + + } + public void GetSubTitle() + { + try + { + + + string MethodStr = "/API/Subtitle/GetDevSubtitle"; + var data = new { Code = app.deviceid }; + var ret = MyHttpClient.CryptPost(MethodStr, data); + if (!string.IsNullOrEmpty(ret)) + { + var Jo = JObject.Parse(ret); + string code = Jo.Value("code"); + + if (code == "200") + { + try + { + List itemList = Jo.Value("data").ToObject>(); + //Mylog.WriteLogFile("-data---" + JsonConvert.SerializeObject(Data), "Subtitle"); + //List itemList = JsonConvert.DeserializeObject<>(Data); + var groupList = itemList.GroupBy(i => i.location).Select(g => (new { Name = g.Key, List = g })).ToList(); + app.TopSubTitle.Clear(); + app.BottomSubTitle.Clear(); + foreach (var item in groupList) + { + if (item.Name == "top") + { + app.TopSubTitle = item.List.ToList(); + app.TopSubTitleIndex = 0; + } + else + { + app.BottomSubTitle = item.List.ToList(); + app.BottomSubTitleIndex = 0; + } + } + } + catch (Exception e) + { + app.TopSubTitle.Clear(); + app.BottomSubTitle.Clear(); + app.BottomSubTitleIndex = 0; + app.TopSubTitleIndex = 0; + Mylog.WriteLogFile("-----error----" + e.Message, "Subtitle"); + } + + } + } + } + catch (Exception e) + { + app.TopSubTitle.Clear(); + app.BottomSubTitle.Clear(); + app.BottomSubTitleIndex = 0; + app.TopSubTitleIndex = 0; + Mylog.WriteLogFile("-----error----" + e.Message, "Subtitle"); + } + } + + public void GetSyncDev() + { + Class_Log log = new Class_Log(); + try + { + log.WriteLogFile("获取", "GetSyncDev"); + string MethodStr = "/API/Dev/GetSyncDev"; + var data = new { Code = app.deviceid }; + var ret = MyHttpClient.CryptPost(MethodStr, data); + log.WriteLogFile(ret, "GetSyncDev"); + if (!string.IsNullOrEmpty(ret)) + { + var Jo = JObject.Parse(ret); + string code = Jo.Value("code"); + + if (code == "200") + { + try + { + var dicData = Jo.Value("data"); + if (dicData != null) + { + //app.deviceid = dicData["code"].ToString(); + string ip = dicData["ip"].ToString(); + log.WriteLogFile(ip, "GetSyncDev"); + log.WriteLogFile("------" + app.websocketProgramIP, "GetSyncDev"); + if (app.websocketProgramIP != ip) + { + app.websocketProgramIP = ip; + if (app.isProgramServer) + { + if (app.websocketForProgramServer == null) + { + app.websocketForProgramServer = new WebsocketForProgramServer(); + } + app.websocketForProgramServer.CloasSocket(); + app.isProgramServer = false; + } + else + { + string AddressIP = string.Empty; + foreach (IPAddress _IPAddress in Dns.GetHostEntry(Dns.GetHostName()).AddressList) + { + if (_IPAddress.AddressFamily.ToString() == "InterNetwork") + { + AddressIP = _IPAddress.ToString(); + } + } + if (AddressIP == ip) + { + app.isProgramServer = true; + if (app.websocketForProgramServer == null) + { + app.websocketForProgramServer = new WebsocketForProgramServer(); + } + app.websocketForProgramServer.openSocket(); + } + } + app.isProgramSync = false; + if (app.webSocketForProgram == null) + { + app.webSocketForProgram = new WebSocketForProgram(); + } + app.webSocketForProgram.ReloadWebSocket(); + log.WriteLogFile("app.isProgramSync--" + app.isProgramSync, "GetSyncDev"); + } + else + { + if (!app.isProgramSync) + { + if (app.webSocketForProgram == null) + { + app.webSocketForProgram = new WebSocketForProgram(); + } + app.webSocketForProgram.ReloadWebSocket(); + } + } + } + } + catch (Exception e) + { + + Mylog.WriteLogFile("-----error----" + e.Message, "GetSyncDevError"); + } + + } + else + { + if (app.isProgramServer) + { + if (app.websocketForProgramServer == null) + { + app.websocketForProgramServer = new WebsocketForProgramServer(); + } + app.websocketForProgramServer.CloasSocket(); + app.isProgramServer = false; + } + if (app.isProgramSync) + { + if (app.webSocketForProgram == null) + { + app.webSocketForProgram = new WebSocketForProgram(); + } + app.webSocketForProgram.CloseWebSocket(); + app.isProgramSync = false; + } + + } + } + } + catch (Exception e) + { + + log.WriteLogFile(e.ToString(), "GetSyncDevError"); + } + } + } +} diff --git a/Container/Business/MqServer.cs b/Container/Business/MqServer.cs new file mode 100644 index 0000000..75de6c9 --- /dev/null +++ b/Container/Business/MqServer.cs @@ -0,0 +1,138 @@ +using Container.Common; +using Newtonsoft.Json; +using RabbitMQ.Client; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows; + +namespace Container.Business +{ + public class MqServer + { + private static App app = ((App)Application.Current); + //public static RabbitConfig config; + public static ConnectionFactory factory = new ConnectionFactory + { + + UserName = app.rabbitMQ.UserName, + Password = app.rabbitMQ.Password, + HostName = app.rabbitMQ.HostName, + Port = app.rabbitMQ.Port, + }; + static IModel models = null; + private static Class_Log _log = new Class_Log(); + static string exchangeName = "topic"; + static string exchangeName_temp = "topic_immediately"; + public MqServer() + { + Create(); + } + static public bool Create() + { + + factory.AutomaticRecoveryEnabled = true; + //创建连接 + var conn = factory.CreateConnection(); + conn.CallbackException += Connetion_CallbackException; + conn.RecoverySucceeded += Connetion_RecoverySucceeded; + conn.ConnectionRecoveryError += Connetion_ConnectionRecoveryError; + conn.ConnectionBlocked += Connetion_ConnectionBlocked; + conn.ConnectionUnblocked += Connetion_ConnectionUnblocked; + //连接关闭的时候 + conn.ConnectionShutdown += Connetion_ConnectionShutdown; + { + models = conn.CreateModel(); + + //声明持久消息队列 + models.ExchangeDeclare(exchangeName, "topic", true, false, null); + //声明即时消息队列 + models.ExchangeDeclare(exchangeName_temp, "topic", true, false, null); + //models.ExchangeDeclare("topic_temp", "topic", true, false, null); + //models.QueueDelete(); + //models.QueueDeclare("deviceInfo", true, false, false, null); + //Console.WriteLine("生产者启动成功"); + _log.WriteLogFile("Start-"+"消息中心启动成功", "MqServer"); + //for (int i = 0; i < 5; i++) + //{ + // models.BasicPublish("message", "myRabbit", mandatory: true, null, Encoding.UTF8.GetBytes(i + "")); + //} + } + return true; + } + private static bool Publish(string Msg, string routingKey = "default", bool isDurable = false) + { + try + { + _log.WriteLogFile(routingKey); + _log.WriteLogFile(Msg); + models.BasicPublish(exchange: isDurable ? exchangeName : exchangeName_temp, routingKey: "device." + routingKey, mandatory: true, body: Encoding.UTF8.GetBytes(Msg)); + //Console.WriteLine("推送消息成功"); + } + catch (Exception ex) + { + _log.WriteLogFile(routingKey+ex.Message, "MqServer"); + } + return true; + } + /// + /// 发布消息 + /// + /// + /// + /// + /// 是否持久化 + /// + public static void PublishMessage(string module, object content, string[] Queue, bool isDurable = true) + { + try + { + string msg = JsonConvert.SerializeObject(new { content, module, MallCode = app.mallCode }); + if (Queue.Length == 0) + Publish(msg, isDurable: isDurable); + else + foreach (var item in Queue) + { + Publish(msg, item, isDurable); + } + } + catch (Exception ex) + { + _log.WriteLogFile("rabbitMq--" + "PublishMessage"+ex.Message, "MqServer"); + } + } + + private static void Connetion_ConnectionShutdown(object sender, ShutdownEventArgs e) + { + _log.WriteLogFile("rabbitMq--"+ "Connetion_ConnectionShutdown", "MqServer"); + + } + + private static void Connetion_ConnectionUnblocked(object sender, EventArgs e) + { + _log.WriteLogFile("rabbitMq--" + "Connetion_ConnectionUnblocked", "MqServer"); + } + + private static void Connetion_ConnectionBlocked(object sender, RabbitMQ.Client.Events.ConnectionBlockedEventArgs e) + { + _log.WriteLogFile("rabbitMq--" + "Connetion_ConnectionBlocked", "MqServer"); + } + + private static void Connetion_ConnectionRecoveryError(object sender, RabbitMQ.Client.Events.ConnectionRecoveryErrorEventArgs e) + { + _log.WriteLogFile("rabbitMq--" + "Connetion_ConnectionRecoveryError", "MqServer"); + } + + private static void Connetion_RecoverySucceeded(object sender, EventArgs e) + { + _log.WriteLogFile("rabbitMq--" + "Connetion_RecoverySucceeded", "MqServer"); + } + + private static void Connetion_CallbackException(object sender, RabbitMQ.Client.Events.CallbackExceptionEventArgs e) + { + _log.WriteLogFile("rabbitMq--" + "Connetion_CallbackException", "MqServer"); + } + } +} diff --git a/Container/Business/OutLine.cs b/Container/Business/OutLine.cs new file mode 100644 index 0000000..09d8eb3 --- /dev/null +++ b/Container/Business/OutLine.cs @@ -0,0 +1,626 @@ +using Container.Common; +using Container.Model; +using Newtonsoft.Json.Linq; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Net; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using System.Windows; +using Transitionals; + +namespace Container.Business +{ + class OutLine + { + App app = ((App)Application.Current); + private string outLinePath = Environment.CurrentDirectory + "/OutlineFiles"; + //private string localIP = ConfigurationManager.AppSettings["LocalIP"]; + //private string remoteAddress = ConfigurationManager.AppSettings["RemoteAddress"]; + private List needDel = new List(); + private List needDownLoad = new List(); + Class_Log log = new Class_Log(); + private static readonly object lockHelper = new object(); + private static OutLine OutLineInstance = null; + + private OutLine() + { + } + + public static OutLine CreateInstance() + { + if (OutLineInstance == null) + { + lock (lockHelper) + { + if (OutLineInstance == null) + { + OutLineInstance = new OutLine(); + } + } + } + + return OutLineInstance; + } + + /// + /// 通过对比本地和网络数据来看是否需要下载或更改播单 + /// + /// + public void DownOutLineFiles(ScreenSavers resource) + { + try + { + if (resource == null) + return; + DirectoryInfo dir = new DirectoryInfo(outLinePath); + List localFilesPath = new List(); + List remoteFilesPath = new List(); + needDownLoad.Clear(); + needDel.Clear(); + + if (dir.Exists) + { + FileInfo[] fiList = dir.GetFiles(); + foreach (var item in fiList) + { + if (!Path.GetExtension(item.FullName).Contains("temp")) + { + localFilesPath.Add(item.FullName); + } + } + + } + else + Directory.CreateDirectory(outLinePath); + + if (resource.ResList.Count > 0) + { + foreach (var item in resource.ResList) + remoteFilesPath.Add(item.img); + + } + //else + // return; + + foreach (var item in remoteFilesPath) + { + var httpPath = item.Substring(0, item.IndexOf("://") + 3); + var fileBackPath = item.Substring(item.IndexOf("://") + 3).Replace("//", "/").Replace("\\", "/"); + var file = httpPath + fileBackPath; + var names = file.Split('/'); + var fileName = file; + if (names.Length > 0) + { + fileName = names[names.Length - 2]; + } + if (localFilesPath.FindAll(p => p.Contains(fileName)).Count <= 0) + { + //if (!localFilesPath.Contains(fileName)) { + needDownLoad.Add(item); + } + //if (localFilesPath.FindAll(p => p.EndsWith(Path.GetFileName(item))).Count <= 0) + // needDownLoad.Add(item); + } + + foreach (var item in localFilesPath) + { + if (remoteFilesPath.FindAll(p => p.Contains(Path.GetFileNameWithoutExtension(item))).Count <= 0) + { + needDel.Add(item); + } + //if (remoteFilesPath.FindAll(p => p.EndsWith(Path.GetFileName(item))).Count <= 0) + // needDel.Add(item); + } + if (needDel.Count > 1 || needDownLoad.Count > 0 || !File.Exists(Environment.CurrentDirectory + "/OutlineFiles" + "/temp.xml")) + DownLoadFiles(resource); + else + { + if (resource.ResList.Count < 0) + return; + foreach (var item in resource.ResList) + { + var httpPath = item.img.Substring(0, item.img.IndexOf("://") + 3); + var fileBackPath = item.img.Substring(item.img.IndexOf("://") + 3).Replace("//", "/").Replace("\\", "/"); + item.img = httpPath + fileBackPath; + log.WriteLogFile("原图片地址" + item.img, "image"); + if (item.img.Contains("/")) + { + var names = item.img.Split('/'); + log.WriteLogFile("names个数" + names.Length, "image"); + if (names.Length > 0) + { + item.img = outLinePath + "/" + names[names.Length - 2] + names[names.Length - 1].Substring(names[names.Length - 1].LastIndexOf('.')); + } + else + { + item.img = outLinePath + item.img.Substring(item.img.LastIndexOf("/")); + } + log.WriteLogFile("下载后地址" + item.img, "image"); + } + + else + item.img = outLinePath + item.img; + } + + //string xmlPath = outLinePath + "/temp.xml"; + //if (File.Exists(xmlPath)) + // File.Delete(xmlPath); + + ////写入离线配置文件 + //using (Stream fs = new FileStream(xmlPath, FileMode.Create)) + //{ + // StreamWriter sw = new StreamWriter(fs); + // sw.Write(CommonMethod.SerializeXML(resource)); + // sw.Close(); + // fs.Close(); + //} + + ScreenSavers result = new ScreenSavers(); + if (File.Exists(outLinePath + "/temp.xml")) + { + using (StreamReader sr = new StreamReader(outLinePath + "/temp.xml")) + { + result = CommonMethod.DeserializeXML(sr.ReadToEnd()); + sr.Close(); + } + if (result != null) + { + ScreenSavers result1 = new ScreenSavers(); + if (!result.Equals(resource)) + { + string xmlPath = outLinePath + "/temp.xml"; + //if (File.Exists(xmlPath)) + // File.Delete(xmlPath); + + //写入离线配置文件 + using (Stream fs = new FileStream(xmlPath, FileMode.Create)) + { + StreamWriter sw = new StreamWriter(fs); + sw.Write(CommonMethod.SerializeXML(resource)); + sw.Close(); + fs.Close(); + } + App.Downloaddone = true; + } + } + else + { + string xmlPath = outLinePath + "/temp.xml"; + //if (File.Exists(xmlPath)) + // File.Delete(xmlPath); + + //写入离线配置文件 + using (Stream fs = new FileStream(xmlPath, FileMode.Create)) + { + StreamWriter sw = new StreamWriter(fs); + sw.Write(CommonMethod.SerializeXML(resource)); + sw.Close(); + fs.Close(); + } + App.Downloaddone = true; + } + } + else + { + string xmlPath = outLinePath + "/temp.xml"; + //if (File.Exists(xmlPath)) + // File.Delete(xmlPath); + + //写入离线配置文件 + using (Stream fs = new FileStream(xmlPath, FileMode.Create)) + { + StreamWriter sw = new StreamWriter(fs); + sw.Write(CommonMethod.SerializeXML(resource)); + sw.Close(); + fs.Close(); + } + App.Downloaddone = true; + } + return; + } + } + catch (Exception ex) + { + log.WriteLogFile(ex.ToString(), "OutLineLog"); + } + } + + /// + /// 通过对比本地和网络数据来看是否需要删除过期文件 + /// + /// + public void DeleteOutTimeFiles(ScreenSavers resource) + { + try + { + if (resource == null) + return; + DirectoryInfo dir = new DirectoryInfo(outLinePath); + List localFilesPath = new List(); + List remoteFilesPath = new List(); + needDel.Clear(); + + if (dir.Exists) + { + FileInfo[] fiList = dir.GetFiles(); + foreach (var item in fiList) + { + if (!Path.GetExtension(item.FullName).Contains("temp")) + { + localFilesPath.Add(item.FullName); + } + } + + } + else + return; + + if (resource.ResList.Count > 0) + { + foreach (var item in resource.ResList) + remoteFilesPath.Add(item.img); + } + else + return; + + foreach (var item in localFilesPath) + { + if (remoteFilesPath.FindAll(p => p.Contains(Path.GetFileNameWithoutExtension(item))).Count <= 0) + { + needDel.Add(item); + } + //if (remoteFilesPath.FindAll(p => p.EndsWith(Path.GetFileName(item))).Count <= 0) + // needDel.Add(item); + } + + //删除多余的文件 + if (needDel.Count > 1) + { + for (int i = 0; i < needDel.Count; i++) + { + try + { + if (File.Exists(needDel[i]) && Path.GetFileName(needDel[i]) != "temp.xml") + File.Delete(needDel[i]); + } + catch (Exception ex) + { + log.WriteLogFile(ex.ToString(), "OutLineLog"); + } + } + } + } + catch (Exception ex) + { + log.WriteLogFile(ex.ToString(), "OutLineLog"); + } + } + + /// + /// 获取后台图片或视频资源地址 + /// + /// + public List> GetResource() + { + try + { + List> tpList = new List>(); + + while (!File.Exists(outLinePath + "/temp.xml"))//等待更新播放单 + { + Thread.Sleep(200); + } + + ScreenSavers result = new ScreenSavers(); + using (StreamReader sr = new StreamReader(outLinePath + "/temp.xml")) + { + //MessageBox.Show(sr.ReadToEnd()); + result = CommonMethod.DeserializeXML(sr.ReadToEnd()); + sr.Close(); + } + var curDate = DateTime.Now; + var list = result.ResList.Where(i => !string.IsNullOrEmpty(i.img) && Convert.ToDateTime(i.launchtime) < curDate && Convert.ToDateTime(i.expirydate) > curDate.AddDays(-1)).ToList(); + if (list == null || list.Count == 0) + return tpList; + + foreach (var item in list) + { + if (!string.IsNullOrEmpty(item.img)) + { + Transition t = CommonMethod.GetTransition(item.effect); + Tuple tp = new Tuple(item, t); + tpList.Add(tp); + } + } + + return tpList; + } + catch (Exception ex) + { + log.WriteLogFile(ex.ToString(), "OutLineLog"); + return null; + } + } + + public List LoadScreenConfig() + { + string outLinePath = AppDomain.CurrentDomain.BaseDirectory + "/OutlineFiles"; + if (!Directory.Exists(outLinePath + "/Main")) + { + return null; + } + else + { + if (File.Exists(outLinePath + "/Main/screenconfig.txt")) + { + string rev = DownLoadMethod.ReadContext(outLinePath + "/Main/screenconfig.txt"); + if (!string.IsNullOrEmpty(rev)) + { + var Jo = JObject.Parse(rev); + string code = Jo.Value("code"); + if (code == "200") + { + List itemList = Jo.Value("data").ToObject>(); + var Schedule = itemList.Where(i => i.date == DateTime.Now.ToString("yyyy-MM-dd")).FirstOrDefault(); + if (Schedule != null) + { + return Schedule.schedule; + } + else + { + return null; + } + + } + else + { + return null; + } + } + else + { + return null; + } + } + else + { + return null; + } + } + + } + + /// + /// 下载离线数据 + /// + /// + /// + bool done = false; + private bool DownLoadFiles(ScreenSavers resource) + { + if (!done) + { + done = true; + log.WriteLogFile("开始下载", "exelog"); + try + { + if (needDownLoad.Count > 0) + { + + //下载缺少的文件 + for (int i = 0; i < needDownLoad.Count; i++) + { + log.WriteLogFile(needDownLoad[i], "downfile"); + try + { + var httpPath = needDownLoad[i].Substring(0, needDownLoad[i].IndexOf("://") + 3); + var fileBackPath = needDownLoad[i].Substring(needDownLoad[i].IndexOf("://") + 3).Replace("//", "/").Replace("\\", "/"); + needDownLoad[i] = httpPath + fileBackPath; + string localFile = string.Empty; + if (needDownLoad[i].Contains("/")) + { + var names = needDownLoad[i].Split('/'); + if (names.Length > 0) + { + localFile = outLinePath + "/" + names[names.Length - 2] + names[names.Length - 1].Substring(names[names.Length - 1].LastIndexOf('.')); + } + else + { + localFile = outLinePath + needDownLoad[i].Substring(needDownLoad[i].LastIndexOf("/")); + } + } + + else + localFile = outLinePath + needDownLoad[i]; + + if (!File.Exists(localFile))//&& !File.Exists(localFile + ".temp") + { + log.WriteLogFile("开始下载" + localFile, "exelog"); + if (File.Exists(localFile + ".temp")) + File.Delete(localFile + ".temp"); + using (Stream fileStream = new FileStream(localFile + ".temp", FileMode.OpenOrCreate)) + { + try + { + //fileStream.Seek(fileStream.Length, SeekOrigin.Current); + //HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://" + app.HttpUrl + needDownLoad[i]); + HttpWebRequest request = (HttpWebRequest)WebRequest.Create(needDownLoad[i]); + request.AddRange(fileStream.Length); + + HttpWebResponse respone = (HttpWebResponse)request.GetResponse(); + using (Stream netStream = respone.GetResponseStream()) + { + long totalDownloadedByte = 0; + byte[] read = new byte[1024]; + int realReadLen = netStream.Read(read, 0, read.Length); + while (realReadLen > 0) + { + totalDownloadedByte = realReadLen + totalDownloadedByte; + + fileStream.Write(read, 0, realReadLen); + realReadLen = netStream.Read(read, 0, read.Length); + + System.Windows.Forms.Application.DoEvents(); + } + netStream.Close(); + } + if (fileStream.Length != respone.ContentLength) + { + log.WriteLogFile("文件未下载完毕", "文件"); + } + fileStream.Close(); + log.WriteLogFile("下载完成" + localFile, "exelog"); + File.Move(localFile + ".temp", localFile); + + } + catch (Exception ex) + { + log.WriteLogFile("下载失败" + localFile + ex.ToString(), "exelog"); + File.Delete(localFile + ".temp"); + log.WriteLogFile(ex.ToString(), "OutLineLog"); + done = false; + return false; + } + } + + } + } + catch (Exception ex) + { + log.WriteLogFile(ex.ToString(), "OutLineLog"); + done = false; + //MessageBox.Show("http://" + remoteAddress + needDownLoad[i]+"文件下载失败"+ex.ToString()); + return false; + } + } + } + + foreach (var item in resource.ResList) + { + item.img = item.img.Replace("\\", "/"); + if (item.img.Contains("/")) + { + var names = item.img.Split('/'); + if (names.Length > 0) + { + item.img = outLinePath + "/" + names[names.Length - 2] + names[names.Length - 1].Substring(names[names.Length - 1].LastIndexOf('.')); + } + else + { + item.img = outLinePath + item.img.Substring(item.img.LastIndexOf("/")); + } + } + + else + item.img = outLinePath + item.img; + //item.img = item.img.Replace("\\", "/"); + //if (item.img.Contains("/")) + // item.img = outLinePath + item.img.Substring(item.img.LastIndexOf("/")); + //else + // item.img = outLinePath + item.img; + } + if (resource.ResList.Count < 0) + { + done = false; + return false; + } + //string xmlPath = outLinePath + "/temp.xml"; + //if (File.Exists(xmlPath)) + // File.Delete(xmlPath); + + ////写入离线配置文件 + //using (Stream fs = new FileStream(xmlPath, FileMode.Create)) + //{ + // StreamWriter sw = new StreamWriter(fs); + // sw.Write(CommonMethod.SerializeXML(resource)); + // sw.Close(); + // fs.Close(); + //} + + ScreenSavers result = new ScreenSavers(); + if (File.Exists(outLinePath + "/temp.xml")) + { + using (StreamReader sr = new StreamReader(outLinePath + "/temp.xml")) + { + result = CommonMethod.DeserializeXML(sr.ReadToEnd()); + sr.Close(); + } + ScreenSavers result1 = new ScreenSavers(); + if (result != null) + { + if (!result.Equals(resource)) + { + string xmlPath = outLinePath + "/temp.xml"; + //if (File.Exists(xmlPath)) + // File.Delete(xmlPath); + + //写入离线配置文件 + using (Stream fs = new FileStream(xmlPath, FileMode.Create)) + { + StreamWriter sw = new StreamWriter(fs); + sw.Write(CommonMethod.SerializeXML(resource)); + sw.Close(); + fs.Close(); + } + App.Downloaddone = true; + } + } + else + { + string xmlPath = outLinePath + "/temp.xml"; + //if (File.Exists(xmlPath)) + // File.Delete(xmlPath); + + //写入离线配置文件 + using (Stream fs = new FileStream(xmlPath, FileMode.Create)) + { + StreamWriter sw = new StreamWriter(fs); + sw.Write(CommonMethod.SerializeXML(resource)); + sw.Close(); + fs.Close(); + } + App.Downloaddone = true; + } + } + else + { + string xmlPath = outLinePath + "/temp.xml"; + //if (File.Exists(xmlPath)) + // File.Delete(xmlPath); + + //写入离线配置文件 + using (Stream fs = new FileStream(xmlPath, FileMode.Create)) + { + StreamWriter sw = new StreamWriter(fs); + sw.Write(CommonMethod.SerializeXML(resource)); + sw.Close(); + fs.Close(); + } + App.Downloaddone = true; + } + done = false; + return true; + } + catch (Exception ex) + { + + log.WriteLogFile(ex.ToString(), "OutLineLog"); + done = false; + return false; + } + finally + { + done = false; + } + } + else + { + return false; + } + } + } +} diff --git a/Container/Business/PlayBackManage.cs b/Container/Business/PlayBackManage.cs new file mode 100644 index 0000000..ff44a14 --- /dev/null +++ b/Container/Business/PlayBackManage.cs @@ -0,0 +1,56 @@ +using Container.Common; +using Container.Model; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Transitionals; + +namespace Container.Business +{ + public class PlayBackManage + { + private JService jService = new JService(); + private OutLine outLine = OutLine.CreateInstance(); + //private static readonly ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); + Class_Log log = new Class_Log(); + App app = ((App)System.Windows.Application.Current); + /// + /// 获取后台图片或视频资源地址 + /// + public List GetResource() + { + //Action ac = new Action(() =>//静默下载离线文件 + //{ + // log.WriteLogFile("GetResource()下载离线文件", "exelog"); + // bool flag= jService.GetOutLineResource(); + //}); + //ac.BeginInvoke(null, null); + + return outLine.LoadScreenConfig(); + } + + public void DownResource() { + Action ac = new Action(() =>//静默下载离线文件 + { + log.WriteLogFile("GetResource()下载离线文件", "exelog"); + app.isStartGetProg = true; + bool flag = jService.GetOutLineResource(); + }); + ac.BeginInvoke(null, null); + } + + + ///// + ///// 获取屏保切换间隔 + ///// + ///// + //public int GetInterval() + //{ + // return jService.GetInterval(); + //} + + } +} diff --git a/Container/Business/RabbitHostedService.cs b/Container/Business/RabbitHostedService.cs new file mode 100644 index 0000000..a9bb520 --- /dev/null +++ b/Container/Business/RabbitHostedService.cs @@ -0,0 +1,432 @@ +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; + } + } +} diff --git a/Container/ChildWindows/BGPage.xaml b/Container/ChildWindows/BGPage.xaml new file mode 100644 index 0000000..6c0871c --- /dev/null +++ b/Container/ChildWindows/BGPage.xaml @@ -0,0 +1,11 @@ + + + + + diff --git a/Container/ChildWindows/BGPage.xaml.cs b/Container/ChildWindows/BGPage.xaml.cs new file mode 100644 index 0000000..cb0e9d3 --- /dev/null +++ b/Container/ChildWindows/BGPage.xaml.cs @@ -0,0 +1,91 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Runtime.InteropServices; +using System.Text; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Data; +using System.Windows.Documents; +using System.Windows.Input; +using System.Windows.Media; +using System.Windows.Media.Imaging; +using System.Windows.Shapes; +using Container.Common; + +namespace Container.ChildWindows +{ + /// + /// BGPage.xaml 的交互逻辑 + /// + public partial class BGPage : Window + { + Class_Log log = new Class_Log(); + App app = ((App)System.Windows.Application.Current); + [DllImport("user32.dll", SetLastError = true)] + static extern IntPtr FindWindow(string IpClassName, string IpWindowName); + [DllImport("user32.dll", SetLastError = true)] + static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int x, int y, int cx, int cy, uint uflags); + + public static readonly IntPtr HWND_TOPMOST = new IntPtr(-1); //窗体置顶 + public static readonly IntPtr HWND_NOTOPMOST = new IntPtr(-2); //取消窗体置顶 + public static readonly IntPtr HWND_BOTTOM = new IntPtr(1); //取消窗体置顶 + public const uint SWP_NOMOVE = 0x0002; //不调整窗体位置 + public const uint SWP_NOSIZE = 0x0001; //不调整窗体大小 + public BGPage() + { + InitializeComponent(); + + } + + public void LoadImage(string pageUrl) { + if (string.IsNullOrEmpty(pageUrl)) { + this.Width = 0; + this.Height = 0; + this.bgPage.Width = 0; + this.bgPage.Height = 0; + + this.WindowState = WindowState.Minimized; + } + else + { + this.Width = app.ScreenWidth; + this.Height = app.ScreenHeight; + this.bgPage.Width = app.ScreenWidth; + this.bgPage.Height = app.ScreenHeight; + this.WindowState = WindowState.Maximized; + if (File.Exists(pageUrl) == true) + { + + Uri uri = new Uri(pageUrl, UriKind.Absolute); + ImageBrush ib = new ImageBrush(); + ib.ImageSource = new BitmapImage(uri); + this.bgPage.Background = ib; + } + } + IntPtr WinMain = FindWindow(null, "MainWindow"); //Win_h5Page是我的程序中需要置顶的窗体的名字 + if (WinMain != null) + { + SetWindowPos(WinMain, HWND_BOTTOM, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE); + + } + IntPtr Win = FindWindow(null, "BGPage"); //Win_h5Page是我的程序中需要置顶的窗体的名字 + if (Win != null) + { + SetWindowPos(Win, HWND_BOTTOM, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE); + + } + } + + private void BGPage_Load(object sender, RoutedEventArgs e) + { + + + //log.WriteLogFile("信发是否启用:" + pcstart.ToString()); + // IntPtr Win = FindWindow(null, "ADInsert"); //取消置顶 + + } + } +} diff --git a/Container/ChildWindows/GetUrl.xaml b/Container/ChildWindows/GetUrl.xaml new file mode 100644 index 0000000..d2e02fc --- /dev/null +++ b/Container/ChildWindows/GetUrl.xaml @@ -0,0 +1,74 @@ + + + + + + + + + + + diff --git a/Container/ChildWindows/GetUrl.xaml.cs b/Container/ChildWindows/GetUrl.xaml.cs new file mode 100644 index 0000000..5655747 --- /dev/null +++ b/Container/ChildWindows/GetUrl.xaml.cs @@ -0,0 +1,190 @@ +using Container.Common; +using Container.Services; +using Microsoft.Win32; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Data; +using System.Windows.Documents; +using System.Windows.Input; +using System.Windows.Media; +using System.Windows.Media.Imaging; +using System.Windows.Shapes; + +namespace Container.ChildWindows +{ + /// + /// GetUrl.xaml 的交互逻辑 + /// + public partial class GetUrl : Window + { + App app = ((App)System.Windows.Application.Current); + Class_Config config = new Class_Config(); + Class_Log log = new Class_Log(); + public GetUrl() + { + InitializeComponent(); + this.WindowStartupLocation = System.Windows.WindowStartupLocation.CenterScreen; + } + + private void Button_Click(object sender, RoutedEventArgs e) + { + try + { + lab_msg.Visibility = System.Windows.Visibility.Hidden; + if (string.IsNullOrEmpty(this.Text_RegKey.Text)) + { + lab_msg.Content = "请填写商场激活码。"; + lab_msg.Visibility = System.Windows.Visibility.Visible; + return; + } + //if (string.IsNullOrEmpty(this.Text_HttpUrl.Text)) + //{ + // lab_msg.Content = "请填写Http地址。"; + // lab_msg.Visibility = System.Windows.Visibility.Visible; + // return; + //} + //if (string.IsNullOrEmpty(this.Text_WsUrl.Text)) + //{ + // lab_msg.Content = "请填写Websocket地址。"; + // lab_msg.Visibility = System.Windows.Visibility.Visible; + // return; + //} + if (string.IsNullOrEmpty(this.Text_ExePath.Text)) + { + //if (MessageBox.Show("确认不填写应用程序路径?", "提示", MessageBoxButton.YesNo) == MessageBoxResult.No) + //{ + // lab_msg.Content = "请填写应用程序路径。"; + // lab_msg.Visibility = System.Windows.Visibility.Visible; + // return; + //} + } + + else if (!File.Exists(this.Text_ExePath.Text.ToString()) && !this.Text_ExePath.Text.ToString().Contains("http")) + { + lab_msg.Content = "未找到应用程序,请确认路径是否正确。"; + lab_msg.Visibility = System.Windows.Visibility.Visible; + return; + } + app.mallRegKey = this.Text_RegKey.Text.ToString(); + //app.configurl = this.Text_HttpUrl.Text.ToString(); + //app.HttpUrl = this.Text_HttpUrl.Text.ToString(); + //app.configwebsocket = this.Text_WsUrl.Text.ToString(); + app.configstartexe = this.Text_ExePath.Text.ToString(); + HttpMessage httpclient = new HttpMessage(); + string Errorlog = string.Empty; + string mallCode = string.Empty; + var flag = httpclient.CheckMallRegKey(app.mallRegKey, ref mallCode, ref Errorlog); + if (!flag) + { + lab_msg.Content = Errorlog; + lab_msg.Visibility = System.Windows.Visibility.Visible; + } + else + { + lab_msg.Visibility = System.Windows.Visibility.Hidden; + app.mallCode = mallCode; + config.WriteToInitialConfig(); + ServiceInfo info = new ServiceInfo(); + this.ButtonOK.Visibility = System.Windows.Visibility.Hidden; + info.ShowDialog(); + if (info.DialogResult == true) + { + this.DialogResult = info.DialogResult; + } + else + { + this.ButtonOK.Visibility = System.Windows.Visibility.Visible; + } + } + + + } + catch (Exception ex) + { + log.WriteLogFile(ex.ToString(), "GetUrlErrorLog"); + } + } + + private void Services_Loaded(object sender, RoutedEventArgs e) + { + //this.Text_HttpUrl.Text = app.HttpUrl; + this.Text_RegKey.Text = app.mallRegKey; + //this.Text_WsUrl.Text = app.configwebsocket; + this.Text_ExePath.Text = app.configstartexe; + } + + private void Win_Closed(object sender, EventArgs e) + { + try + { + string startup = log.Writestart(); + if (string.IsNullOrEmpty(startup)) + { + MessageBox.Show("创建启动文件失败"); + return; + } + //string startup = System.Windows.Forms.Application.ExecutablePath; //取得程序路径 + RegistryKey rKey = Registry.LocalMachine; + //开机自动运行 + RegistryKey autoRun = rKey.CreateSubKey(@"SOFTWARE\wow6432node\microsoft\windows\currentversion\run"); + log.WriteLogFile(@"打开注册表SOFTWARE\wow6432node\microsoft\windows\currentversion\run成功", "RegistryKey"); + try + { + autoRun.SetValue("Container", startup); + rKey.Close(); + log.WriteLogFile(@"创建注册表启动项成功", "RegistryKey"); + } + catch (Exception exp) + { + + MessageBox.Show("创建开机自启动失败:" + exp.Message.ToString() + "请手动设置开机自启动"); + log.WriteLogFile(exp.Message.ToString(), "RegistryKey"); + } + int pp = startup.LastIndexOf("\\"); + startup = startup.Substring(0, pp); + } + catch (Exception ex) + { + MessageBox.Show("创建开机自启动失败:" + ex.Message.ToString() + "请手动设置开机自启动"); + //if (string.IsNullOrEmpty(ConfigurationManager.AppSettings["MessageShow"])) + //{ + // MessageBox.Show(ex.Message.ToString()); + //} + //else if (ConfigurationManager.AppSettings["MessageShow"].ToLower().Trim().Equals("true")) + //{ + // MessageBox.Show(ex.Message.ToString()); + //} + log.WriteLogFile(ex.Message.ToString(), "RegistryKey"); + + } + } + + private void ExeFile_Click(object sender, RoutedEventArgs e) + { + OpenFileDialog openFile = new OpenFileDialog();//实例化打开对话框对象 + openFile.Filter = "应用程序|*.bat;*.exe";//设置打开文件筛选器 + // openExcel.FileName = ""; + openFile.Multiselect = false;//设置打开对话框中不能多选 + openFile.CheckFileExists = true; //验证路径有效性 + openFile.CheckPathExists = true; //验证文件有效性 + string strName = string.Empty; + if (openFile.ShowDialog() == true) + { + strName = openFile.FileName; + } + + if (strName == "") + { + return; + } + + Text_ExePath.Text = openFile.FileName;//显示选择的Exe文件 + } + } +} diff --git a/Container/ChildWindows/GetUrlForLocal.xaml b/Container/ChildWindows/GetUrlForLocal.xaml new file mode 100644 index 0000000..ba69e30 --- /dev/null +++ b/Container/ChildWindows/GetUrlForLocal.xaml @@ -0,0 +1,69 @@ + + + + + + + + + diff --git a/Container/ChildWindows/GetUrlForLocal.xaml.cs b/Container/ChildWindows/GetUrlForLocal.xaml.cs new file mode 100644 index 0000000..907a118 --- /dev/null +++ b/Container/ChildWindows/GetUrlForLocal.xaml.cs @@ -0,0 +1,172 @@ +using Container.Common; +using Container.Services; +using Microsoft.Win32; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Data; +using System.Windows.Documents; +using System.Windows.Input; +using System.Windows.Media; +using System.Windows.Media.Imaging; +using System.Windows.Shapes; + +namespace Container.ChildWindows +{ + /// + /// GetUrlForLocal.xaml 的交互逻辑 + /// + public partial class GetUrlForLocal : Window + { + App app = ((App)System.Windows.Application.Current); + Class_Config config = new Class_Config(); + Class_Log log = new Class_Log(); + public GetUrlForLocal() + { + InitializeComponent(); + this.WindowStartupLocation = System.Windows.WindowStartupLocation.CenterScreen; + } + + private void Button_Click(object sender, RoutedEventArgs e) + { + try + { + lab_msg.Visibility = System.Windows.Visibility.Hidden; + if (string.IsNullOrEmpty(this.Text_HttpUrl.Text)) + { + lab_msg.Content = "请填写Http地址。"; + lab_msg.Visibility = System.Windows.Visibility.Visible; + return; + } + if (string.IsNullOrEmpty(this.Text_WsUrl.Text)) + { + lab_msg.Content = "请填写Websocket地址。"; + lab_msg.Visibility = System.Windows.Visibility.Visible; + return; + } + if (string.IsNullOrEmpty(this.Text_ExePath.Text)) + { + //if (MessageBox.Show("确认不填写应用程序路径?", "提示", MessageBoxButton.YesNo) == MessageBoxResult.No) + //{ + // lab_msg.Content = "请填写应用程序路径。"; + // lab_msg.Visibility = System.Windows.Visibility.Visible; + // return; + //} + } + + else if (!File.Exists(this.Text_ExePath.Text.ToString()) && !this.Text_ExePath.Text.ToString().Contains("http")) + { + lab_msg.Content = "未找到应用程序,请确认路径是否正确。"; + lab_msg.Visibility = System.Windows.Visibility.Visible; + return; + } + app.configurl = this.Text_HttpUrl.Text.ToString(); + app.HttpUrl = this.Text_HttpUrl.Text.ToString(); + app.configwebsocket = this.Text_WsUrl.Text.ToString(); + HttpMessage httpclient = new HttpMessage(); + string Errorlog = string.Empty; + string mallCode = string.Empty; + //var flag = httpclient.CheckMallRegKey(app.mallRegKey, ref mallCode, ref Errorlog); + app.mallCode = mallCode; + app.configstartexe = this.Text_ExePath.Text.ToString(); + config.WriteToInitialConfig(); + ServiceInfo info = new ServiceInfo(); + this.ButtonOK.Visibility = System.Windows.Visibility.Hidden; + info.ShowDialog(); + if (info.DialogResult == true) + { + this.DialogResult = info.DialogResult; + } + else + { + this.ButtonOK.Visibility = System.Windows.Visibility.Visible; + } + + } + catch (Exception ex) + { + log.WriteLogFile(ex.ToString(), "GetUrlErrorLog"); + } + } + + private void Services_Loaded(object sender, RoutedEventArgs e) + { + this.Text_HttpUrl.Text = app.HttpUrl; + this.Text_WsUrl.Text = app.configwebsocket; + this.Text_ExePath.Text = app.configstartexe; + } + + private void Win_Closed(object sender, EventArgs e) + { + try + { + string startup = log.Writestart(); + if (string.IsNullOrEmpty(startup)) + { + MessageBox.Show("创建启动文件失败"); + return; + } + //string startup = System.Windows.Forms.Application.ExecutablePath; //取得程序路径 + RegistryKey rKey = Registry.LocalMachine; + //开机自动运行 + RegistryKey autoRun = rKey.CreateSubKey(@"SOFTWARE\wow6432node\microsoft\windows\currentversion\run"); + log.WriteLogFile(@"打开注册表SOFTWARE\wow6432node\microsoft\windows\currentversion\run成功", "RegistryKey"); + try + { + autoRun.SetValue("Container", startup); + rKey.Close(); + log.WriteLogFile(@"创建注册表启动项成功", "RegistryKey"); + } + catch (Exception exp) + { + + MessageBox.Show("创建开机自启动失败:" + exp.Message.ToString() + "请手动设置开机自启动"); + log.WriteLogFile(exp.Message.ToString(), "RegistryKey"); + } + int pp = startup.LastIndexOf("\\"); + startup = startup.Substring(0, pp); + } + catch (Exception ex) + { + MessageBox.Show("创建开机自启动失败:" + ex.Message.ToString() + "请手动设置开机自启动"); + //if (string.IsNullOrEmpty(ConfigurationManager.AppSettings["MessageShow"])) + //{ + // MessageBox.Show(ex.Message.ToString()); + //} + //else if (ConfigurationManager.AppSettings["MessageShow"].ToLower().Trim().Equals("true")) + //{ + // MessageBox.Show(ex.Message.ToString()); + //} + log.WriteLogFile(ex.Message.ToString(), "RegistryKey"); + + } + } + + private void ExeFile_Click(object sender, RoutedEventArgs e) + { + OpenFileDialog openFile = new OpenFileDialog();//实例化打开对话框对象 + openFile.Filter = "应用程序|*.bat;*.exe";//设置打开文件筛选器 + // openExcel.FileName = ""; + openFile.Multiselect = false;//设置打开对话框中不能多选 + openFile.CheckFileExists = true; //验证路径有效性 + openFile.CheckPathExists = true; //验证文件有效性 + string strName = string.Empty; + if (openFile.ShowDialog() == true) + { + strName = openFile.FileName; + } + + if (strName == "") + { + return; + } + + Text_ExePath.Text = openFile.FileName;//显示选择的Exe文件 + } + } +} diff --git a/Container/ChildWindows/ScrollingTextControl.cs b/Container/ChildWindows/ScrollingTextControl.cs new file mode 100644 index 0000000..462633a --- /dev/null +++ b/Container/ChildWindows/ScrollingTextControl.cs @@ -0,0 +1,150 @@ +using System; +using System.ComponentModel; +using System.Drawing; +using System.Timers; +using System.Windows; +using System.Windows.Controls; + +namespace Container.ChildWindows +{ + /// + /// Label走马灯自定义控件 + /// + [ToolboxBitmap(typeof(Label))] //设置工具箱中显示的图标 + public class ScrollingTextControl : Label + { + /// + /// 定时器 + /// + Timer MarqueeTimer = new Timer(); + /// + /// 滚动文字源 + /// + String _TextSource = "滚动文字源"; + /// + /// 输出文本 + /// + String _OutText = string.Empty; + /// + /// 过度文本存储 + /// + string _TempString = string.Empty; + /// + /// 文字的滚动速度 + /// + double _RunSpeed = 500; + + DateTime _SignTime; + bool _IfFirst = true; + + /// + /// 滚动一循环字幕停留的秒数,单位为毫秒,默认值停留3秒 + /// + int _StopSecond = 10000; + + /// + /// 滚动一循环字幕停留的秒数,单位为毫秒,默认值停留3秒 + /// + public int StopSecond + { + get { return _StopSecond; } + set + { + _StopSecond = value; + } + } + + /// + /// 滚动的速度 + /// + [Description("文字滚动的速度")] //显示在属性设计视图中的描述 + public double RunSpeed + { + get { return _RunSpeed; } + set + { + _RunSpeed = value; + MarqueeTimer.Interval = _RunSpeed; + } + } + + /// + /// 滚动文字源 + /// + [Description("文字滚动的Text")] + public string TextSource + { + get { return _TextSource; } + set + { + _TextSource = value; + _TempString = _TextSource + " "; + _OutText = _TempString; + } + } + + private string SetContent + { + get { return Content.ToString(); } + set + { + Content = value; + } + } + + /// + /// 构造函数 + /// + public ScrollingTextControl() + { + MarqueeTimer.Interval = _RunSpeed;//文字移动的速度 + MarqueeTimer.Enabled = true; //开启定时触发事件 + MarqueeTimer.Elapsed += new ElapsedEventHandler(MarqueeTimer_Elapsed);//绑定定时事件 + this.Loaded += new RoutedEventHandler(ScrollingTextControl_Loaded);//绑定控件Loaded事件 + } + + + void ScrollingTextControl_Loaded(object sender, RoutedEventArgs e) + { + _TextSource = SetContent; + _TempString = _TextSource + " "; + _OutText = _TempString; + _SignTime = DateTime.Now; + } + + + void MarqueeTimer_Elapsed(object sender, ElapsedEventArgs e) + { + if (string.IsNullOrEmpty(_OutText)) return; + + if (_OutText.Substring(1) + _OutText[0] == _TempString) + { + if (_IfFirst) + { + _SignTime = DateTime.Now; + } + + if ((DateTime.Now - _SignTime).TotalMilliseconds > _StopSecond) + { + _IfFirst = true; ; + } + else + { + _IfFirst = false; + return; + } + } + + _OutText = _OutText.Substring(1) + _OutText[0]; + + + Dispatcher.BeginInvoke(new Action(() => + { + SetContent = _OutText; + })); + + + } + + } +} diff --git a/Container/ChildWindows/ServiceInfo.xaml b/Container/ChildWindows/ServiceInfo.xaml new file mode 100644 index 0000000..9c2b616 --- /dev/null +++ b/Container/ChildWindows/ServiceInfo.xaml @@ -0,0 +1,175 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Container/ChildWindows/ServiceInfo.xaml.cs b/Container/ChildWindows/ServiceInfo.xaml.cs new file mode 100644 index 0000000..07a786c --- /dev/null +++ b/Container/ChildWindows/ServiceInfo.xaml.cs @@ -0,0 +1,548 @@ +using Container.Common; +using Container.Model; +using Container.Services; +using Container.Viewmodel; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Linq; +using System.Net; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Data; +using System.Windows.Documents; +using System.Windows.Input; +using System.Windows.Media; +using System.Windows.Media.Imaging; +using System.Windows.Shapes; +using System.Windows.Threading; +using System.IO; +using Microsoft.Win32; +using System.Diagnostics; + +namespace Container.ChildWindows +{ + /// + /// ServiceInfo.xaml 的交互逻辑 + /// + public partial class ServiceInfo : Window + { + BackgroundWorker backgroundWorker; + DispatcherTimer timer = new DispatcherTimer(); + App app; + int type = 1; + string ErrorLog = ""; + private Class_Log log = new Class_Log(); + string BuildingName = ""; + string BuildingId = ""; + string FloorName = ""; + string FloorId = ""; + string DeviceType = ""; + string FileType = ""; + int second = 10; + public ServiceInfo() + { + InitializeComponent(); + this.WindowStartupLocation = System.Windows.WindowStartupLocation.CenterScreen; + } + //SelectBox mytest; + private void Services_Loaded(object sender, RoutedEventArgs e) + { + try + { + app = ((App)System.Windows.Application.Current); + + backgroundWorker = new BackgroundWorker(); + backgroundWorker.WorkerReportsProgress = true; + backgroundWorker.WorkerSupportsCancellation = true; + backgroundWorker.ProgressChanged += BackgroundWorker_ProgressChanged; + backgroundWorker.RunWorkerCompleted += BackgroundWorker_RunWorkerCompleted; + backgroundWorker.DoWork += BackgroundWorker_DoWork; + backgroundWorker.RunWorkerAsync(); + second = 60; + timer.Tick += new EventHandler(timer_Tick); + timer.Interval = TimeSpan.FromSeconds(1); + timer.Start(); + Text_Device.Text = app.devicemark = System.Net.Dns.GetHostName(); + this.Text_FilePath.Text = app.HttpUrl; + HttpMessage httpclient = new HttpMessage(); + string ErrorLog = ""; + if (httpclient.GetDeviceTypeList(ref ErrorLog)) { + if (app.DeviceTypeList.Count() > 0) + { + //app.Floors = list.ElementAt(0); + this.ComBox_Type.ItemsSource = (new BuildingOperate(3)).BuildingMenu; + ComBox_Type.SelectedValuePath = "code"; + ComBox_Type.DisplayMemberPath = "name"; + ComBox_Type.SelectedIndex = 0; + ComBox_Type.IsDropDownOpen = false; + } + } + + this.ComBox_File.ItemsSource = (new BuildingOperate(4)).BuildingMenu; + ComBox_File.SelectedValuePath = "code"; + ComBox_File.DisplayMemberPath = "code"; + ComBox_File.SelectedIndex = 0; + ComBox_File.IsDropDownOpen = false; + + } + catch (Exception ex) + { + log.WriteLogFile("异常" + ex.ToString(), "ServiceInfoError"); + } + + } + + //倒计时 + private void timer_Tick(object sender, EventArgs e) + { + if (second > 0) + { + second--; + if (Loading.Visibility == System.Windows.Visibility.Visible) + this.Time.Text = "倒计时" + second.ToString() + "s"; + } + else + { + if (Loading.Visibility == System.Windows.Visibility.Visible) + { + if (backgroundWorker.IsBusy == true) + { + timer.Stop(); + backgroundWorker.ReportProgress(1, null); + } + + + } + else if (UpdateSuccess.Visibility == System.Windows.Visibility.Visible) + { + timer.Stop(); + this.DialogResult = true; + } + } + } + private void Button_Click(object sender, RoutedEventArgs e) + { + lab_msg.Visibility = System.Windows.Visibility.Hidden; + + //if (type == 1) + //{ + BuildingName = ""; + BuildingId = ""; + + if (ComBox_Building.Text == "" || ComBox_Building.SelectedValue == null) + { + lab_msg.Content = "请先选择楼栋信息"; + lab_msg.Visibility = System.Windows.Visibility.Visible; + return; + } + + BuildingName = ComBox_Building.Text.ToString(); + BuildingId = ComBox_Building.SelectedValue.ToString(); + //} + //else if (type == 2) + //{ + FloorName = ""; + FloorId = ""; + if (ComBox_Building.Text == "" || ComBox_Building.SelectedValue == null) + { + lab_msg.Content = "请先选择楼层信息"; + lab_msg.Visibility = System.Windows.Visibility.Visible; + return; + } + FloorName = ComBox_Floor.Text.ToString(); + FloorId = ComBox_Floor.SelectedValue.ToString(); + log.WriteLogFile("ComBox_Type.Text="+ ComBox_Type.Text+ ";ComBox_Type.SelectedValue="+ ComBox_Type.SelectedValue, "123"); + if (ComBox_Type.Text == "" || ComBox_Type.SelectedValue == null) { + lab_msg.Content = "请选择设备类型"; + lab_msg.Visibility = System.Windows.Visibility.Visible; + return; + } + DeviceType = ComBox_Type.SelectedValue.ToString(); + if (ComBox_File.Text == "" || ComBox_File.SelectedValue == null) + { + lab_msg.Content = "请先选择文件存储"; + lab_msg.Visibility = System.Windows.Visibility.Visible; + return; + } + FileType= ComBox_File.SelectedValue.ToString(); + //if (Text_Device.Text.Trim() == "") + { + //lab_msg.Content = "请填写设备标识"; + //lab_msg.Visibility = System.Windows.Visibility.Visible; + //return; + app.devicemark = Text_Device.Text.Trim(); + } + switch (FileType) + { + case "本地部署": + app.FileServerPath = app.HttpUrl; + break; + case "前置离线": + app.FileServerPath = Text_FilePath.Text.Trim(); + break; + case "直联云": + app.FileServerPath = app.OBSPath; + break; + default: + break; + } + if (string.IsNullOrEmpty(app.FileServerPath)) + { + lab_msg.Content = "文件服务地址不能为空"; + lab_msg.Visibility = System.Windows.Visibility.Visible; + return; + } + //} + if (backgroundWorker.IsBusy) + { + lab_msg.Content = "线程正忙,请稍后再试"; + lab_msg.Visibility = System.Windows.Visibility.Visible; + } + else + { + type = 2; + this.deviceinfo.Visibility = System.Windows.Visibility.Hidden; + this.Loading.Visibility = System.Windows.Visibility.Visible; + string errorMsg = ""; + StartExE(app.configstartexe, (app.HttpUrl.Replace("http://", "")).Split('/')[0] + "|" + app.LocalIP + "|" + app.configwebsocket + "|1"); + HttpMessage httpmessage = new HttpMessage(); + httpmessage.LoadAppConfig(ref errorMsg); + httpmessage.LoadBG(); + httpmessage.LoadScreenTime(); + backgroundWorker.RunWorkerAsync(); + app.IsCanConnect = true; + + } + + } + + private void StartExE(string path, string param = "") + { + try + { + timer.Stop(); + if (!File.Exists(path) && !path.StartsWith("http:")) + { + if (!File.Exists(System.Windows.Forms.Application.ExecutablePath.Replace("\\", "/").Substring(0, System.Windows.Forms.Application.ExecutablePath.Replace("\\", "/").LastIndexOf("/")) + path)) + { + return; + } + else + { + path = System.Windows.Forms.Application.ExecutablePath.Replace("\\", "/").Substring(0, System.Windows.Forms.Application.ExecutablePath.Replace("\\", "/").LastIndexOf("/")) + path; + } + } + log.WriteLogFile(path.Substring(path.Length - 4, 4).ToLower(), "startlog"); + if (path.Substring(path.Length - 4, 4).ToLower().Equals(".bat")) + { + param = ""; + Process myprocess = new Process(); + ProcessStartInfo startInfo = new ProcessStartInfo(path, param); + path = path.Replace("\\", "/"); + startInfo.WorkingDirectory = path.Substring(0, path.LastIndexOf("/"));//设置应用程序在其所在目录 + startInfo.Verb = "runas"; + startInfo.CreateNoWindow = true; + myprocess.StartInfo = startInfo; + myprocess.StartInfo.UseShellExecute = false; + + myprocess.Start(); + app.AppPlayName = "chrome"; + app.CurAppPlayName = app.AppPlayName; + app.NowAppType = "bat"; + timer.Start(); + log.WriteLogFile("打开成功", "startlog"); + } + else + { + Process myprocess = new Process(); + ProcessStartInfo startInfo = new ProcessStartInfo(path, param); + path = path.Replace("\\", "/"); + startInfo.WorkingDirectory = path.Substring(0, path.LastIndexOf("/"));//设置应用程序在其所在目录 + startInfo.Verb = "runas"; + startInfo.CreateNoWindow = true; + myprocess.StartInfo = startInfo; + myprocess.StartInfo.UseShellExecute = false; + myprocess.Start(); + app.AppPlayName = myprocess.ProcessName; + app.CurAppPlayName = app.AppPlayName; + app.NowAppType = "exe"; + timer.Start(); + } + + } + catch (Exception ex) + { + log.WriteLogFile(ex.ToString()); + } + + } + + void BackgroundWorker_DoWork(object sender, DoWorkEventArgs e) + { + //BackgroundWorker worker = sender as BackgroundWorker; + HttpMessage httpclient = new HttpMessage(); + try + { + ErrorLog = ""; + if (type == 1) + { + if (httpclient.GetBuildinginfo(ref ErrorLog)) + { + if (app.Buildinginfo.Count > 0) + { + //查询成功 + backgroundWorker.ReportProgress(0, null); + } + else + { + if (ErrorLog.Trim() == "") + ErrorLog = "未查到楼栋相关记录";//未查到 + backgroundWorker.ReportProgress(1, null); + } + } + else + { + //ErrorLog = "连接服务器失败。"; + backgroundWorker.ReportProgress(1, null); + } + + } + else + { + int i = 0; + string AddressIP = string.Empty; + foreach (IPAddress _IPAddress in Dns.GetHostEntry(Dns.GetHostName()).AddressList) + { + if (_IPAddress.AddressFamily.ToString() == "InterNetwork") + { + AddressIP = _IPAddress.ToString(); + } + } + // string[] IP = AddressIP.Split('.'); + // if (IP.Count() == 4) + //app.deviceid = BuildingName + FloorName + IP[2] + IP[3]; + while (true) + { + + if (httpclient.UploadDeviceInfo(BuildingId, FloorId, DeviceType, ref ErrorLog)) + { + WebSocketManageForLive webForLive = new WebSocketManageForLive(); + webForLive.OpenWebSocket(); + backgroundWorker.ReportProgress(0, null);//上传成功 + break; + } + else + { + i++; + + if (i > 3) + { + //if (ErrorLog.Trim() == "") + // ErrorLog = "上传失败"; + backgroundWorker.ReportProgress(1, null); + break; + } + } + } + + } + } + catch (Exception ex) + { + ErrorLog = "操作失败"; + log.WriteLogFile("异常" + ex.ToString(),"ServiceInfoError"); + backgroundWorker.ReportProgress(1, null); + } + e.Cancel = true; + return; + } + void BackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) + { + + } + void BackgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e) + { + int progressPercentage = e.ProgressPercentage; + string userState = (string)e.UserState; + try + { + switch (progressPercentage) + { + case 0: + //reclient.Visibility = System.Windows.Visibility.Hidden; + if (type == 1) + { + timer.Stop(); + this.ComBox_Building.ItemsSource = app.Buildinginfo; + this.ComBox_Building.ItemsSource = (new BuildingOperate(type)).BuildingMenu; + ComBox_Building.SelectedValuePath = "code"; + ComBox_Building.DisplayMemberPath = "name"; + ComBox_Building.IsDropDownOpen = true; + this.Loading.Visibility = System.Windows.Visibility.Hidden; + this.deviceinfo.Visibility = Visibility.Visible; + } + else + { + second = 2; + this.Loading.Visibility = System.Windows.Visibility.Hidden; + this.UpdateSuccess.Visibility = System.Windows.Visibility.Visible; + timer.Start(); + } + backgroundWorker.CancelAsync(); + break; + case 1: + if (type == 1) + { + this.ConnectFailed.Visibility = System.Windows.Visibility.Visible; + this.Loading.Visibility = System.Windows.Visibility.Hidden; + } + else + { + UpdateErrorInfo.Text = ErrorLog; + UpdateErrorInfo.Visibility = System.Windows.Visibility.Visible; + this.UpdateFailed.Visibility = System.Windows.Visibility.Visible; + this.Loading.Visibility = System.Windows.Visibility.Hidden; + } + timer.Stop(); + lab_msg.Content = ErrorLog; + lab_msg.Visibility = System.Windows.Visibility.Visible; + backgroundWorker.CancelAsync(); + break; + case 2: + break; + default: break; + } + } + catch (System.Exception ex) + { + log.WriteLogFile("异常" + ex.ToString()); + } + } + + private void ButtonBack_Click(object sender, RoutedEventArgs e) + { + lab_msg.Visibility = System.Windows.Visibility.Hidden; + + if (backgroundWorker.IsBusy) + { + lab_msg.Content = "线程正忙,请稍后再试"; + lab_msg.Visibility = System.Windows.Visibility.Visible; + } + else + { + type = 1; + backgroundWorker.RunWorkerAsync(); + + } + } + + private void reclient_Click(object sender, RoutedEventArgs e) + { + Button_Click(null,null); + } + + private void Services_Closed(object sender, EventArgs e) + { + if (backgroundWorker.IsBusy) + backgroundWorker.CancelAsync(); + timer.Stop(); + + } + string buildingid = ""; + private void Combox_Building_changed(object sender, SelectionChangedEventArgs e) + { + this.ComBox_Floor.Text = ""; + this.ComBox_Floor.ItemsSource = null; + if (buildingid.Trim().Equals(this.ComBox_Building.SelectedValue.ToString().Trim())) + { + return; + } + else + { + buildingid = this.ComBox_Building.SelectedValue.ToString(); + } + + IEnumerable> list = (app.Buildinginfo.Where(i => i.code.ToString() == this.ComBox_Building.SelectedValue.ToString()).Select(i => i.floors)); + if (list.Count() > 0) + { + app.Floors = list.ElementAt(0); + this.ComBox_Floor.ItemsSource = (new BuildingOperate(2)).BuildingMenu; + ComBox_Floor.SelectedValuePath = "code"; + ComBox_Floor.DisplayMemberPath = "name"; + ComBox_Floor.IsDropDownOpen = true; + } + else + { + + } + } + + private void Combox_File_changed(object sender, SelectionChangedEventArgs e) + { + + if (this.ComBox_File.SelectedValue.ToString() == "前置离线") + { + Label_FilePath.Visibility = Visibility.Visible; + Text_FilePath.Visibility = Visibility.Visible; + } + else { + Label_FilePath.Visibility = Visibility.Hidden; + Text_FilePath.Visibility = Visibility.Hidden; + } + } + + private void Btn_ReConnection(object sender, RoutedEventArgs e) + { + this.Close(); + //if (backgroundWorker.IsBusy) + //{ + // ErrorInfo.Content = "线程正忙,请稍后再试"; + // ErrorInfo.Visibility = System.Windows.Visibility.Visible; + //} + //else + //{ + // ErrorInfo.Visibility = System.Windows.Visibility.Hidden; + // type = 1; + // second = 60; + // timer.Start(); + // this.ConnectFailed.Visibility = System.Windows.Visibility.Hidden; + // this.Loading.Visibility = System.Windows.Visibility.Visible; + // backgroundWorker.RunWorkerAsync(); + + //} + } + + private void Btn_ReUpdate(object sender, RoutedEventArgs e) + { + if (backgroundWorker.IsBusy) + { + this.UpdateErrorInfo.Text = "线程正忙,请稍后再试"; + UpdateErrorInfo.Visibility = System.Windows.Visibility.Visible; + } + else + { + //type = 2; + //second = 60; + //timer.Start(); + UpdateErrorInfo.Visibility = System.Windows.Visibility.Hidden; + this.UpdateFailed.Visibility = System.Windows.Visibility.Hidden; + this.Loading.Visibility = System.Windows.Visibility.Hidden; + deviceinfo.Visibility = System.Windows.Visibility.Visible; + //backgroundWorker.RunWorkerAsync(); + + } + } + + private void Combox_LeftButtonDown(object sender, MouseButtonEventArgs e) + { + ComboBox cm = (ComboBox)sender; + cm.IsDropDownOpen = true; + } + + } +} diff --git a/Container/ChildWindows/UCAppButton.xaml b/Container/ChildWindows/UCAppButton.xaml new file mode 100644 index 0000000..18586e4 --- /dev/null +++ b/Container/ChildWindows/UCAppButton.xaml @@ -0,0 +1,37 @@ + + + + + + + + + + + + + + + + + + + diff --git a/Container/ChildWindows/UCAppButton.xaml.cs b/Container/ChildWindows/UCAppButton.xaml.cs new file mode 100644 index 0000000..af36f3a --- /dev/null +++ b/Container/ChildWindows/UCAppButton.xaml.cs @@ -0,0 +1,254 @@ +using Container.Common; +using Container.Model; +using Container.Services; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Runtime.InteropServices; +using System.Text; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Data; +using System.Windows.Documents; +using System.Windows.Input; +using System.Windows.Media; +using System.Windows.Media.Imaging; +using System.Windows.Navigation; +using System.Windows.Shapes; + +namespace Container.ChildWindows +{ + /// + /// UCAppButton.xaml 的交互逻辑 + /// + public partial class UCAppButton : UserControl + { + + [DllImport("user32.dll", SetLastError = true)] + static extern int SetWindowLong(IntPtr hWnd, int nIndex, IntPtr dwNewLong); + [DllImport("user32.dll", SetLastError = true)] + static extern IntPtr FindWindow(string lpWindowClass, string lpWindowName); + [DllImport("user32.dll", SetLastError = true)] + static extern IntPtr FindWindowEx(IntPtr parentHandle, IntPtr childAfter, string className, string windowTitle); + const int GWL_HWNDPARENT = -8; + [DllImport("user32.dll")] + static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent); + [DllImport("user32.dll")] + public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int x, int y, int cx, int cy, uint uFlags); + + [DllImport("user32.dll", EntryPoint = "ShowWindow")] + public static extern bool ShowWindow(System.IntPtr hWnd, int nCmdShow); + public static int SW_SHOW = 5; + public static int SW_NORMAL = 1; + public static int SW_MAX = 3; + public static int SW_HIDE = 0; + public static readonly IntPtr HWND_TOPMOST = new IntPtr(-1); //窗体置顶 + public static readonly IntPtr HWND_NOTOPMOST = new IntPtr(-2); //取消窗体置顶 + public static readonly IntPtr HWND_BOTTOM = new IntPtr(1); //取消窗体置顶 + + + public const uint SWP_NOMOVE = 0x0002; //不调整窗体位置 + public const uint SWP_NOSIZE = 0x0001; //不调整窗体大小 + Class_Log log = new Class_Log(); + App app = ((App)System.Windows.Application.Current); + string ProcessName = ""; + AppListModel AppInfo = new AppListModel(); + public UCAppButton(AppListModel ExeInfo) + { + InitializeComponent(); + AppInfo = ExeInfo; + //this.DataContext = ExeInfo; + //this.mask.DataContext = ExeInfo; + Uri uri = new Uri(ExeInfo.Logo, UriKind.Relative); + //ImageBrush ib = new ImageBrush(); + //image.Source = new BitmapImage(uri); + //Uri uri = new Uri(logo, UriKind.Absolute); + this.image.Source = BitmapFrame.Create(uri); + txtName.Text = ExeInfo.Name; + this.MouseLeftButtonUp += new MouseButtonEventHandler(this_MouseLeftButtonDown); + } + + private void this_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) + { + Window w = ((Canvas)(((Canvas)this.Parent).Parent)).Parent as Window; + w.Close(); + //打开应用 + try + { + app.appClick = true; + if (!AppInfo.Code.Equals(app.AppPlayinfo.Code)) + { + if (app.NowAppType != "html" && app.NowAppType != "bat" && app.NowAppType != "") + { + killExE(); + } + ////else if (app.NowAppType == "html") + ////{ + //// app.winh5.WinClose(); + //// //app.winh5 = null; + ////} + string fileName = AppInfo.Startup; + //if (string.IsNullOrEmpty(AppInfo.Startup)) + //{ + // fileName = AppInfo.Startup; + //} + //else + //{ + // fileName = AppInfo.exestartname + "/" + AppInfo.exestartname; + //} + if (StartExE(fileName)) + { + app.AppPlayinfo = AppInfo; + //app.AppPlayName = ProcessName; + //app.AppPlayNameCH = ""; + //app.Appversion = ""; + IntPtr Win = FindWindow(null, "WindowButton"); //CustomBar是我的程序中需要置顶的窗体的名字 + if (Win != null) + { + SetWindowPos(Win, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE); + } + else + { + if (app.AppList != null && app.AppList.Count > 1) + { + WindowButton win = new WindowButton(); + win.Show(); + } + } + + + } + else + { + app.AppPlayName = ""; + app.CurAppPlayName = app.AppPlayName; + app.AppPlayNameCH = ""; + app.Appversion = ""; + //打开失败 + } + + } + } + catch(Exception ex) + { + // MessageBox.Show(ex.ToString()); + } + } + + /// + /// 打开外部exe应用程序 + /// 应用程序地址 + /// + private bool StartExE(string path,string param = "") + { + try + { + if (!File.Exists(path)) + { + //System.Windows.MessageBox.Show("应用程序打开失败:。。。" + path + " 文件不存在"); + log.WriteLogFile("应用程序打开失败:" + path + " 文件不存在","UCAppButtonlog"); + return false; + } + + if (path.Substring(path.Length - 4, 4).ToLower().Equals(".bat")) + { + param = ""; + Process myprocess = new Process(); + ProcessStartInfo startInfo = new ProcessStartInfo(path, param); + path = path.Replace("\\", "/"); + startInfo.WorkingDirectory = path.Substring(0, path.LastIndexOf("/"));//设置应用程序在其所在目录 + startInfo.Verb = "runas"; + startInfo.CreateNoWindow = true; + myprocess.StartInfo = startInfo; + myprocess.StartInfo.UseShellExecute = false; + myprocess.Start(); + //MyProcessName.Add("chrome"); + app.AppPlayName = "chrome"; + app.CurAppPlayName = app.AppPlayName; + app.NowAppType = "bat"; + //startexe = true; + //timer.Start(); + log.WriteLogFile("打开成功111", "startlog"); + } + else + { + Process myprocess = new Process(); + path = path.Replace("\\", "/").Replace("//", "/"); + ProcessStartInfo startInfo = new ProcessStartInfo(path, param); + startInfo.WorkingDirectory = path.Substring(0, path.LastIndexOf("/"));//设置应用程序在其所在目录 + startInfo.Verb = "runas"; + startInfo.CreateNoWindow = true; + myprocess.StartInfo = startInfo; + myprocess.StartInfo.UseShellExecute = false; + log.WriteLogFile(startInfo.WorkingDirectory); + log.WriteLogFile(startInfo.FileName); + myprocess.Start(); + //MyProcessName.Add(myprocess.ProcessName); + app.NowAppType = "exe"; + app.AppPlayName = myprocess.ProcessName; + app.CurAppPlayName = app.AppPlayName; + //startexe = true; + } + //Process myprocess = new Process(); + //ProcessStartInfo startInfo = new ProcessStartInfo(path, param); + //path = path.Replace("\\", "/"); + //startInfo.WorkingDirectory = path.Substring(0, path.LastIndexOf("/"));//设置应用程序在其所在目录工作 + //myprocess.StartInfo = startInfo; + //myprocess.StartInfo.UseShellExecute = false; + //myprocess.Start(); + //ProcessName = myprocess.ProcessName; + return true; + } + catch (Exception ex) + { + log.WriteLogFile(ex.ToString(), "UCAppButtonlog"); + return false; + + } + + } + /// + /// 关闭已打开外部应用程序 + /// + private bool killExE() + { + try + { + if (app.NowAppType == "exe") + { + Process[] pro = Process.GetProcesses(); + for (int i = 0; i < pro.Length; i++) + { + if (pro[i].ProcessName.ToLower() == app.AppPlayName.ToLower()) + { + pro[i].Kill();//结束进程 + + return true; + } + } + } + else if (app.NowAppType == "html") + { + //this.Dispatcher.Invoke(new Action(() => + //{ + // try + // { + // if (app.winh5 != null) + // app.winh5.Close(); + // } + // catch { } + //})); + } + } + catch (Exception ex) + { + log.WriteLogFile(ex.ToString(), "UCAppButtonlog"); + + } + return false; + } + } +} diff --git a/Container/ChildWindows/WinShow.xaml b/Container/ChildWindows/WinShow.xaml new file mode 100644 index 0000000..ec4804c --- /dev/null +++ b/Container/ChildWindows/WinShow.xaml @@ -0,0 +1,14 @@ + + + + + + + + diff --git a/Container/ChildWindows/WinShow.xaml.cs b/Container/ChildWindows/WinShow.xaml.cs new file mode 100644 index 0000000..7cb4793 --- /dev/null +++ b/Container/ChildWindows/WinShow.xaml.cs @@ -0,0 +1,32 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Data; +using System.Windows.Documents; +using System.Windows.Input; +using System.Windows.Media; +using System.Windows.Media.Imaging; +using System.Windows.Shapes; + +namespace Container.ChildWindows +{ + /// + /// WinShow.xaml 的交互逻辑 + /// + public partial class WinShow : Window + { + App app = ((App)System.Windows.Application.Current); + public WinShow() + { + InitializeComponent(); + this.Width = app.ScreenWidth; + this.Height = app.ScreenHeight; + this.Left = 0; + this.Top = 0; + } + } +} diff --git a/Container/ChildWindows/WindowAppChoose.xaml b/Container/ChildWindows/WindowAppChoose.xaml new file mode 100644 index 0000000..0c9a636 --- /dev/null +++ b/Container/ChildWindows/WindowAppChoose.xaml @@ -0,0 +1,33 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Container/ChildWindows/WindowAppChoose.xaml.cs b/Container/ChildWindows/WindowAppChoose.xaml.cs new file mode 100644 index 0000000..05e0006 --- /dev/null +++ b/Container/ChildWindows/WindowAppChoose.xaml.cs @@ -0,0 +1,134 @@ +using Container.Common; +using Container.Model; +using Container.Services; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Data; +using System.Windows.Documents; +using System.Windows.Input; +using System.Windows.Media; +using System.Windows.Media.Imaging; +using System.Windows.Shapes; + +namespace Container.ChildWindows +{ + /// + /// WindowAppChoose.xaml 的交互逻辑 + /// + public partial class WindowAppChoose : Window + { + //List AppList = new List(); + private int columnCount = 18; + private double widthSpace = 0;//横向间隔 + private double heightSpace = 0;//纵向间隔 + //private int rowCount = 0; + private double cvsGoodsMinHeight = 0.00; + App app = ((App)System.Windows.Application.Current); + Class_Log log = new Class_Log(); + public WindowAppChoose(double top, double left, double appwidth = 78) + { + InitializeComponent(); + //Class_Config config = new Class_Config(); + //config.ReadAppInfo(ref AppList); + + //if (left > SystemParameters.PrimaryScreenWidth / 2) + //{ + // AppButton.SetValue(LeftProperty, 0.00); + // //Ggif.SetValue(LeftProperty, this.Width - 96); + + //} + SetAppButton(); + //this.Width = 90 + this.AppButton.Width; + //Bborder.Width = this.Width; + //if (left > SystemParameters.PrimaryScreenWidth / 2) + //{ + // //AppButton.SetValue(LeftProperty, 0); + // Ggif.SetValue(LeftProperty, this.Width - 96); + + //} + //this.Top = top;//SystemParameters.PrimaryScreenHeight - this.Height - 50; + //if (left < 0) + //{ + // left = 0; + //} + //if (left - this.Width < 0) + //{ + // this.Left = 0; + //} + ////else if (left - this.Width > SystemParameters.PrimaryScreenWidth - this.Width) + //// this.Left = SystemParameters.PrimaryScreenWidth - this.Width + //else if (left <= SystemParameters.PrimaryScreenWidth / 2) + //{ + // this.Left = left - appwidth;// - this.Width + //} + //else + //{ + // this.Left = left - this.Width;// - this.Width + + //} + //SystemParameters.PrimaryScreenWidth - this.Width; + //this.Top = SystemParameters.PrimaryScreenHeight - this.Height - 50; + //this.Left = SystemParameters.PrimaryScreenWidth - this.Width; + + } + + private void Win_Load(object sender, RoutedEventArgs e) + { + + } + + public void SetAppButton() + { + //double goodWidth = 0; + this.AppButton.Height = app.AppList.Count * 120; + this.AppButton.Margin = new Thickness(0, 900 - this.AppButton.Height, 0, 0); + try + { + for (int i = 0; i < app.AppList.Count; i++) + { + //int rowIndex = i / columnCount; + //int columnIndex = i % columnCount; + UCAppButton AppInfo = new UCAppButton(app.AppList[i]); + //AppInfo.SetValue(Canvas.LeftProperty, 0); + //AppInfo.SetValue(Canvas.TopProperty, 300); + + this.AppButton.Children.Add(AppInfo); + + //if (goodWidth == 0) + // goodWidth = AppInfo.Width; + } + } + catch (Exception e) + { + + log.WriteLogFile("1111"+e.Message,"errrrrr"); + } + //this.AppButton.MinHeight = cvsGoodsMinHeight; + //this.AppButton.Width = app.AppList.Count * (goodWidth + widthSpace) + widthSpace; + } + + private void ButtonBack_Click(object sender, MouseButtonEventArgs e) + { + this.Close(); + + } + + private void mousedown(object sender, MouseButtonEventArgs e) + { + if (e.LeftButton == MouseButtonState.Pressed) + { + + this.DragMove(); + + } + } + + } +} diff --git a/Container/ChildWindows/WindowButton.xaml b/Container/ChildWindows/WindowButton.xaml new file mode 100644 index 0000000..6bdc3a9 --- /dev/null +++ b/Container/ChildWindows/WindowButton.xaml @@ -0,0 +1,26 @@ + + + + + + + + + diff --git a/Container/ChildWindows/WindowButton.xaml.cs b/Container/ChildWindows/WindowButton.xaml.cs new file mode 100644 index 0000000..ccd87a6 --- /dev/null +++ b/Container/ChildWindows/WindowButton.xaml.cs @@ -0,0 +1,275 @@ +using Container.Common; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Runtime.InteropServices; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Data; +using System.Windows.Documents; +using System.Windows.Input; +using System.Windows.Interop; +using System.Windows.Media; +using System.Windows.Media.Imaging; +using System.Windows.Shapes; +using System.Windows.Threading; + +namespace Container.ChildWindows +{ + /// + /// WindowButton.xaml 的交互逻辑 + /// + public partial class WindowButton : Window + { + Class_Log log = new Class_Log();//日志对象 + App app = ((App)System.Windows.Application.Current); + Point _TicstartPoint;//鼠标按下位置 + Point _TicendPoint;//鼠标抬起位置 + //Point mousePostion; + //初始化 + public WindowButton() + { + InitializeComponent(); + this.Top = app.ScreenHeight - this.Height - 50; + this.Left = app.ScreenWidth - this.Width-65; + mLastInputInfo = new LASTINPUTINFO(); + mLastInputInfo.cbSize = Marshal.SizeOf(mLastInputInfo); + + mIdleTimer = new System.Windows.Threading.DispatcherTimer(); + mIdleTimer.Tick += new EventHandler(IdleTime);//起个Timer一直获取当前时间 + mIdleTimer.Interval = new TimeSpan(0, 0, 0, 1, 0); +; + //mIdleTimer.Start(); + } + //窗体关闭事件 + private void Windows_Closed(object sender, EventArgs e) + { + + try + { + + Process[] process = Process.GetProcesses(); + foreach (Process prc in process) + { + if (prc.ProcessName.Equals(System.Diagnostics.Process.GetCurrentProcess().ProcessName)) + { + if (app.AppList != null && app.AppList.Count > 1) + { + WindowButton win = new WindowButton(); + win.Show(); + + } + } + } + } + catch (Exception ex) + { + log.WriteLogFile("窗体关闭异常:" + ex.ToString(), "MainWindowError"); + } + } + //鼠标按下事件 + private void UIElement_OnMouseLeftButtonDown(object sender, MouseButtonEventArgs e) + { + _TicstartPoint = new Point(this.Left, this.Top); + + if (e.LeftButton == MouseButtonState.Pressed) + { + + this.DragMove(); + //SendMessage(new WindowInteropHelper(this).Handle, WM_SYSCOMMAND, SC_MOVE + HTCAPTION, 0); + + } + + + } + //鼠标抬起事件 + private void Btn_MouseUp(object sender, MouseButtonEventArgs e) + { + try + { + _TicendPoint = new Point(this.Left, this.Top); + + //X轴滑动的距离 + double offsetY = _TicstartPoint.Y - _TicendPoint.Y; + double offsetX = _TicstartPoint.X - _TicendPoint.X; + if (offsetY < 2 && offsetY > -2 && offsetX > -5 && offsetX < 5) + { + this.Img.Visibility = System.Windows.Visibility.Hidden; + //this.GgifImage.Visibility = System.Windows.Visibility.Hidden; + this.Img.Visibility = System.Windows.Visibility.Hidden; + //this.GgifImage.Visibility = System.Windows.Visibility.Hidden; + WindowAppChoose win = new WindowAppChoose(this.Top, this.Left + this.Width, this.Width); + win.ShowDialog(); + //Thread.Sleep(1000); + //this.GgifImage.Visibility = System.Windows.Visibility.Visible; + this.Img.Visibility = System.Windows.Visibility.Visible; + //this.Left = SystemParameters.PrimaryScreenWidth - this.Width / 2 + 5; + + } + } + catch (Exception ex) + { + log.WriteLogFile(ex.ToString()); + } + } + //[DllImport("user32.dll")] + //public static extern bool ReleaseCapture(); + //[DllImport("user32.dll")] + //public static extern bool SetCapture(); + [DllImport("user32.dll")] + public static extern bool SendMessage(IntPtr hwnd, int wMsg, int wParam, int lParam); + public const int WM_SYSCOMMAND = 0x0112; + public const int SC_MOVE = 0xF010; + public const int HTCAPTION = 0x0002; + + [DllImport("user32.dll", SetLastError = true)] + static extern int SetWindowLong(IntPtr hWnd, int nIndex, IntPtr dwNewLong); + [DllImport("user32.dll", SetLastError = true)] + static extern IntPtr FindWindow(string lpWindowClass, string lpWindowName); + [DllImport("user32.dll", SetLastError = true)] + static extern IntPtr FindWindowEx(IntPtr parentHandle, IntPtr childAfter, string className, string windowTitle); + const int GWL_HWNDPARENT = -8; + [DllImport("user32.dll")] + static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent); + [DllImport("user32.dll")] + public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int x, int y, int cx, int cy, uint uFlags); + + [DllImport("user32.dll", EntryPoint = "ShowWindow")] + public static extern bool ShowWindow(System.IntPtr hWnd, int nCmdShow); + public static int SW_SHOW = 5; + public static int SW_NORMAL = 1; + public static int SW_MAX = 3; + public static int SW_HIDE = 0; + public static readonly IntPtr HWND_TOPMOST = new IntPtr(-1); //窗体置顶 + public static readonly IntPtr HWND_NOTOPMOST = new IntPtr(-2); //取消窗体置顶 + public const uint SWP_NOMOVE = 0x0002; //不调整窗体位置 + public const uint SWP_NOSIZE = 0x0001; //不调整窗体大小 + private void Form1_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e) + {//拖动窗体 + SendMessage(new WindowInteropHelper(this).Handle, WM_SYSCOMMAND, SC_MOVE + HTCAPTION, 0); + } + + #region 检测鼠标动作 + //定义结构体 + [StructLayout(LayoutKind.Sequential)] + struct LASTINPUTINFO + { + // 设置结构体块容量 + [MarshalAs(UnmanagedType.U4)] + public int cbSize; + // 捕获的时间 + [MarshalAs(UnmanagedType.U4)] + public uint dwTime; + } + + // 定义定时器,结构体对象等 + + private DispatcherTimer mIdleTimer; + private LASTINPUTINFO mLastInputInfo; + + [DllImport("user32.dll")] + private static extern bool GetLastInputInfo(ref LASTINPUTINFO plii); + + /*初始化 + mLastInputInfo = new LASTINPUTINFO(); + mLastInputInfo.cbSize = Marshal.SizeOf(mLastInputInfo); + + mIdleTimer = new System.Windows.Threading.DispatcherTimer(); + mIdleTimer.Tick += new EventHandler(IdleTime);//起个Timer一直获取当前时间 + mIdleTimer.Interval = new TimeSpan(0, 0, 0, 1, 0); + mIdleTimer.Start(); + */ + + //实现 + private void IdleTime(object sender, EventArgs e) + { + + if (!GetLastInputInfo(ref mLastInputInfo)) + { + //MessageBox.Show("GetLastInputInfo Failed!"); + //this.Top = SystemParameters.PrimaryScreenHeight - this.Height - 50; + //this.Left = SystemParameters.PrimaryScreenWidth - this.Width - 10; + } + else + { + if ((Environment.TickCount - (long)mLastInputInfo.dwTime) / 1000 > 10) + { + //MessageBox.Show("no operation for 5 minutes."); + //this.Top = SystemParameters.PrimaryScreenHeight - this.Height - 50; + this.Left = app.ScreenWidth - this.Width / 2 + 5; + } + } + + } + #endregion + + private void Win_MouseEnter(object sender, MouseEventArgs e) + { + + //if (this.Left > SystemParameters.PrimaryScreenWidth - this.Width) + //{ + // this.Left = SystemParameters.PrimaryScreenWidth - this.Width; + //} + } + + private void Win_MouseLeave(object sender, MouseEventArgs e) + { + //if (this.Left >= SystemParameters.PrimaryScreenWidth - this.Width-2) + //{ + + // this.Left = SystemParameters.PrimaryScreenWidth - this.Width / 2 + 5; + //} + } + + + + private void Btn_MouseDown(object sender, MouseButtonEventArgs e) + { + _TicstartPoint = e.GetPosition(App.Current.MainWindow); + } + + private void GgifImage_MouseDown(object sender, MouseButtonEventArgs e) + { + //_TicstartPoint = PointToScreen(e.GetPosition(this)); + _TicstartPoint = new Point(this.Left,this.Top); + + } + + private void GgifImage_MouseUp(object sender, MouseButtonEventArgs e) + { + try + { + _TicendPoint = new Point(this.Left, this.Top); + + //X轴滑动的距离 + double offsetY = _TicstartPoint.Y - _TicendPoint.Y; + double offsetX = _TicstartPoint.X - _TicendPoint.X; + if (offsetY < 2 && offsetY > -2 && offsetX > -5 && offsetX < 5) + { + this.Img.Visibility = System.Windows.Visibility.Hidden; + //this.GgifImage.Visibility = System.Windows.Visibility.Hidden; + this.Img.Visibility = System.Windows.Visibility.Hidden; + //this.GgifImage.Visibility = System.Windows.Visibility.Hidden; + WindowAppChoose win = new WindowAppChoose(this.Top, this.Left + this.Width, this.Width); + win.ShowDialog(); + //Thread.Sleep(1000); + //this.GgifImage.Visibility = System.Windows.Visibility.Visible; + this.Img.Visibility = System.Windows.Visibility.Visible; + //this.Left = SystemParameters.PrimaryScreenWidth - this.Width / 2 + 5; + + } + } + catch (Exception ex) + { + log.WriteLogFile(ex.ToString()); + } + } + + + + } +} diff --git a/Container/Common/ChatWebSocketMiddleware.cs b/Container/Common/ChatWebSocketMiddleware.cs new file mode 100644 index 0000000..a8e6ba5 --- /dev/null +++ b/Container/Common/ChatWebSocketMiddleware.cs @@ -0,0 +1,63 @@ +using Fleck; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Configuration; +using System.Linq; +using System.Text; +using System.Threading; +using System.Threading.Tasks; + +namespace Container.Common +{ + public class ChatWebSocketMiddleware + { + //public static ConcurrentDictionary _sockets = new ConcurrentDictionary(); + //public static List allSockets = new List(); + //static bool flag = true; + //private static Class_Log log = new Class_Log(); //日志记录文件 + //private static App app = ((App)System.Windows.Application.Current); + //Thread receiveThread; + //public void openSocket() + //{ + // try + // { + + + // FleckLog.Level = LogLevel.Debug; + // var ws = ConfigurationManager.AppSettings["websocketUrl"]; + // var server = new WebSocketServer(ws); + // //RecognizerCLR.setBeamDir(serialPortname, microAngle); + // server.Start(socket => + // { + // socket.OnOpen = () => //当建立Socket链接时执行此方法 + // { + // //var data = socket.ConnectionInfo; //通过data可以获得这个链接传递过来的Cookie信息,用来区分各个链接和用户之间的关系(如果需要后台主动推送信息到某个客户的时候,可以使用Cookie) + // //Console.WriteLine("Open!"); + // allSockets.Add(socket); + // ChatWebSocketMiddleware.allSockets.ToList().ForEach(s => s.Send(JsonConvert.SerializeObject(app.AppList))); + // }; + + // socket.OnClose = () =>// 当关闭Socket链接十执行此方法 + // { + + // //Console.WriteLine("Close!"); + // allSockets.Remove(socket); + // }; + + // socket.OnMessage = message =>// 接收客户端发送过来的信息 + // { + + // }; + // }); + // } + // catch (Exception e) + // { + + // log.WriteLogFile("异常了"+e.ToString(), "recorderror"); + // } + + //} + + } +} diff --git a/Container/Common/Class_Config.cs b/Container/Common/Class_Config.cs new file mode 100644 index 0000000..6d0ae31 --- /dev/null +++ b/Container/Common/Class_Config.cs @@ -0,0 +1,1747 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Navigation; +using System.Windows.Shapes; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Data; +using System.Windows.Documents; +using System.Windows.Input; +using System.Windows.Media; +using System.Windows.Media.Imaging; +using System.Xml; +using System.Xaml; +using System.IO; +using System.Collections; +using System.Net; +//using System.Net.Http; +using System.Text.RegularExpressions; +using System.Drawing; +using System.Windows.Forms; +using Container.Model; +using System.Xml.Serialization; +using Transitionals; +using System.Runtime.InteropServices; +using Container.Services; + +namespace Container.Common +{ + public static class CommonMethod + { + /// + /// 反序列化XML为类实例 + /// + /// + /// + /// + public static T DeserializeXML(string xmlObj) + { + try + { + XmlSerializer serializer = new XmlSerializer(typeof(T)); + using (StringReader reader = new StringReader(xmlObj)) + { + return (T)serializer.Deserialize(reader); + } + } + catch (Exception ex) + { + //MessageBox.Show(ex.ToString()); + return default(T); + } + } + + /// + /// 序列化类实例为XML + /// + /// + /// + /// + public static string SerializeXML(T obj) + { + try + { + using (StringWriter writer = new StringWriter()) + { + new XmlSerializer(obj.GetType()).Serialize((TextWriter)writer, obj); + return writer.ToString(); + } + } + catch + { + return string.Empty; + } + } + + /// + /// 切换效果 + /// + /// 百叶窗-0,遮帘 -1,淡化 - 2,渐变 -3,溶解 - 4,旋转 - 5 + /// + public static Transition GetTransition(string effect) + { + //所有的变换 + //Transitionals.Transitions.StarTransition //星 + //Transitionals.Transitions.RotateTransition //3d旋转 + //Transitionals.Transitions.VerticalWipeTransition//下拉 + //Transitionals.Transitions.PageTransition //翻页 + //Transitionals.Transitions.RollTransition //旋转出 + //Transitionals.Transitions.DiamondsTransition //棋盒棱形 + //Transitionals.Transitions.VerticalBlindsTransition //垂直百叶窗 + //Transitionals.Transitions.HorizontalWipeTransition //左拉 + //Transitionals.Transitions.FadeAndBlurTransition //淡入 + //Transitionals.Transitions.ExplosionTransition //球形散开 + //Transitionals.Transitions.CheckerboardTransition //棋盒方形 + //Transitionals.Transitions.TranslateTransition //飞入 + //Transitionals.Transitions.RotateWipeTransition //旋转擦除 + //Transitionals.Transitions.MeltTransition //柱状 + //Transitionals.Transitions.DiagonalWipeTransition //斜擦除 + //Transitionals.Transitions.FlipTransition //单面翻书 + //Transitionals.Transitions.DotsTransition //球状棋盒 + //Transitionals.Transitions.FadeAndGrowTransition //淡入 + //Transitionals.Transitions.DoubleRotateWipeTransition //双线擦除 + //Transitionals.Transitions.DoorTransition //门状 + //Transitionals.Transitions.HorizontalBlindsTransition //水平百叶窗 + //Transitionals.Transitions.FadeTransition //溶解 + + switch (effect) + { + case "马赛克": + return new Transitionals.Transitions.CheckerboardTransition(); + case "上下滑动": + return new Transitionals.Transitions.VerticalWipeTransition(); + case "左右滑动": + return new Transitionals.Transitions.HorizontalWipeTransition(); + case "渐入": + return new Transitionals.Transitions.FadeTransition(); + case "4": + return new Transitionals.Transitions.FadeTransition(); + case "5": + return new Transitionals.Transitions.RollTransition(); + default: + return new Transitionals.Transitions.FadeTransition(); + } + } + + ///// + ///// 以逆时针为方向对图像进行旋转 + ///// + ///// 位图流 + ///// 旋转角度[0,360](前台给的) + ///// + //public Bitmap RotateImg(System.Drawing.Image b, int angle) + //{ + // angle = angle % 360; + + // //弧度转换 + // double radian = angle * Math.PI / 180.0; + // double cos = Math.Cos(radian); + // double sin = Math.Sin(radian); + + // //原图的宽和高 + // int w = (int)b.Width; + // int h = (int)b.Height; + // int W = (int)(Math.Max(Math.Abs(w * cos - h * sin), Math.Abs(w * cos + h * sin))); + // int H = (int)(Math.Max(Math.Abs(w * sin - h * cos), Math.Abs(w * sin + h * cos))); + + // //目标位图 + // Bitmap dsImage = new Bitmap(W, H); + // System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(dsImage); + // g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.Bilinear; + // g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; + + // //计算偏移量 + // System.Drawing.Point Offset = new System.Drawing.Point((int)(W - w) / 2, (int)(H - h) / 2); + + // //构造图像显示区域:让图像的中心与窗口的中心点一致 + // System.Drawing.Rectangle rect = new System.Drawing.Rectangle(Offset.X, Offset.Y, w, h); + // System.Drawing.Point center = new System.Drawing.Point(rect.X + rect.Width / 2, rect.Y + rect.Height / 2); + // g.TranslateTransform(center.X, center.Y); + // g.RotateTransform(360 - angle); + + // //恢复图像在水平和垂直方向的平移 + // g.TranslateTransform(-center.X, -center.Y); + // g.DrawImage(b, rect); + + // //重至绘图的所有变换 + // g.ResetTransform(); + // g.Save(); + // g.Dispose(); + + // //保存旋转后的图片 + // b.Dispose(); + // //dsImage.Save("FocusPoint.jpg", System.Drawing.Imaging.ImageFormat.Jpeg); + // return dsImage; + + //} + + // 映射 DEVMODE 结构 + // 可以参照 DEVMODE结构的指针定义: + // http://msdn.microsoft.com/en-us/library/windows/desktop/dd183565(v=vs.85).aspx + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] + public struct DEVMODE + { + [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)] + public string dmDeviceName; + + public short dmSpecVersion; + public short dmDriverVersion; + public short dmSize; + public short dmDriverExtra; + public int dmFields; + public int dmPositionX; + public int dmPositionY; + public int dmDisplayOrientation; + public int dmDisplayFixedOutput; + public short dmColor; + public short dmDuplex; + public short dmYResolution; + public short dmTTOption; + public short dmCollate; + + [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)] + public string dmFormName; + + public short dmLogPixels; + public short dmBitsPerPel; + public int dmPelsWidth; + public int dmPelsHeight; + public int dmDisplayFlags; + public int dmDisplayFrequency; + public int dmICMMethod; + public int dmICMIntent; + public int dmMediaType; + public int dmDitherType; + public int dmReserved1; + public int dmReserved2; + public int dmPanningWidth; + public int dmPanningHeight; + }; + + // Win32 函数在托管环境下的声明 + public class NativeMethods + { + // 平台调用的申明 + [DllImport("user32.dll")] + public static extern int EnumDisplaySettings( + string deviceName, int modeNum, ref DEVMODE devMode); + [DllImport("user32.dll")] + public static extern int ChangeDisplaySettings( + ref DEVMODE devMode, int flags); + + // 控制改变屏幕分辨率的常量 + public const int ENUM_CURRENT_SETTINGS = -1; + public const int CDS_UPDATEREGISTRY = 0x01; + public const int CDS_TEST = 0x02; + public const int DISP_CHANGE_SUCCESSFUL = 0; + public const int DISP_CHANGE_RESTART = 1; + public const int DISP_CHANGE_FAILED = -1; + + // 控制改变方向的常量定义 + public const int DMDO_DEFAULT = 0; + public const int DMDO_90 = 1; + public const int DMDO_180 = 2; + public const int DMDO_270 = 3; + } + + /// + /// 改变分辨率 + /// + /// 0:切换横屏,1:切换竖屏 + public static int ChangeResolution(int displayOrientation) + { + // 初始化 DEVMODE结构 + DEVMODE devmode = new DEVMODE(); + devmode.dmDeviceName = new String(new char[32]); + devmode.dmFormName = new String(new char[32]); + devmode.dmSize = (short)Marshal.SizeOf(devmode); + + if (0 != NativeMethods.EnumDisplaySettings(null, NativeMethods.ENUM_CURRENT_SETTINGS, ref devmode)) + { + //// 改变屏幕分辨率 + //int iRet = NativeMethods.ChangeDisplaySettings(ref devmode, NativeMethods.CDS_TEST); + + //if (iRet == NativeMethods.DISP_CHANGE_FAILED) + //{ + // //MessageBox.Show("不能执行你的请求", "信息", MessageBoxButtons.OK, MessageBoxIcon.Information); + //} + //else + //{ + // int temp = devmode.dmPelsWidth; + // devmode.dmPelsWidth = devmode.dmPelsHeight; + // devmode.dmPelsHeight = temp; + // if (displayOrientation == 0) + // devmode.dmDisplayOrientation = NativeMethods.DMDO_90; + // else + // devmode.dmDisplayOrientation = NativeMethods.DMDO_DEFAULT; + + // iRet = NativeMethods.ChangeDisplaySettings(ref devmode, NativeMethods.CDS_UPDATEREGISTRY); + + // switch (iRet) + // { + // // 成功改变 + // case NativeMethods.DISP_CHANGE_SUCCESSFUL: + // { + // break; + // } + // case NativeMethods.DISP_CHANGE_RESTART: + // { + // // MessageBox.Show("你需要重新启动电脑设置才能生效", "信息", MessageBoxButtons.OK, MessageBoxIcon.Information); + // break; + // } + // default: + // { + // // MessageBox.Show("改变屏幕分辨率失败", "信息", MessageBoxButtons.OK, MessageBoxIcon.Information); + // break; + // } + // } + //} + } + + if (devmode.dmDisplayOrientation == 0) + return 0; + else if (devmode.dmDisplayOrientation == 1) + return 90; + else if (devmode.dmDisplayOrientation == 2) + return 180; + else + return -90; + } + + [DllImport("user32.dll")] + static extern void keybd_event + ( + byte bVk,// 虚拟键值 + byte bScan,// 硬件扫描码 + uint dwFlags,// 动作标识 + IntPtr dwExtraInfo// 与键盘动作关联的辅加信息 + ); + + } + class Class_Config + { + private Class_Log log = new Class_Log(); + private App app = ((App)System.Windows.Application.Current); + + + /// + /// 获取当前版本号 + /// + public string GetVersion() + { + string currentVersion = "v1.2.5"; + try + { + string localPath = Directory.GetCurrentDirectory() + "\\ScreenVersion.txt"; + + FileStream fs = new FileStream(localPath, FileMode.Open); + using (StreamReader sr = new StreamReader(fs)) + { + string temp = sr.ReadLine(); + currentVersion = temp.Substring(temp.LastIndexOf("V")); + } + fs.Close(); + } + catch + { + currentVersion = "v1.2.5"; + } + return currentVersion; + } + /// + /// 截屏 + /// + public static string PrintScreen(string imgname) + { + string path = Environment.CurrentDirectory + @"\Screen\" + imgname; + Bitmap bit = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height); + Graphics g = Graphics.FromImage(bit); + g.CopyFromScreen(new System.Drawing.Point(0, 0), new System.Drawing.Point(0, 0), bit.Size); + + try + { + if (File.Exists(path)) + File.Delete(path); + bit.Save(path); + } + catch(Exception ex) + { + // System.Windows.MessageBox.Show(ex.ToString()); + } + finally + { + g.Dispose(); + bit.Dispose(); + } + + return path; + } + /// + /// /加载配置 + /// + public void LoadConfig() + { + try + { + string AddressIP = string.Empty; + foreach (IPAddress _IPAddress in Dns.GetHostEntry(Dns.GetHostName()).AddressList) + { + if (_IPAddress.AddressFamily.ToString() == "InterNetwork") + { + AddressIP = _IPAddress.ToString(); + } + } + string fpath = Directory.GetCurrentDirectory() + "\\config\\"; + if (!Directory.Exists(fpath)) + { + DirectoryInfo directoryInfo = new DirectoryInfo(fpath); + directoryInfo.Create(); + } + string strConfigxml = AppDomain.CurrentDomain.BaseDirectory + "config//Config.xml"; + if (File.Exists(strConfigxml) == true) + { + XmlDocument doc = new XmlDocument(); + doc.Load(strConfigxml); + XmlNode xnFirst = doc.SelectSingleNode("Config"); + XmlNode xnSecond = xnFirst.SelectSingleNode("DeviceInfo"); + if (xnSecond == null) + { + log.WriteLogFile("配置文件错误-未发现DeviceInfo标签"); + return; + } + else + { + app.BuildingID = xnSecond.SelectSingleNode("BuildingID").InnerText; + app.Floor = xnSecond.SelectSingleNode("Floor").InnerText; + app.deviceid = xnSecond.SelectSingleNode("deviceid").InnerText; + app.devicemark = xnSecond.SelectSingleNode("devicemark").InnerText; + app.DeviceType = xnSecond.SelectSingleNode("devicetype").InnerText; + app.FileServerPath= xnSecond.SelectSingleNode("fileserverpath").InnerText; + } + log.WriteLogFile(app.deviceid,"config"); + xnSecond = xnFirst.SelectSingleNode("Http"); + if (xnSecond == null) + { + log.WriteLogFile("配置文件错误-未发现Http标签"); + return; + } + else + { + if (xnSecond.SelectSingleNode("Url").InnerText != "") + app.HttpUrl = xnSecond.SelectSingleNode("Url").InnerText; + log.WriteLogFile(xnSecond.SelectSingleNode("LocalIP").InnerText, "config"); + log.WriteLogFile(AddressIP, "config"); + if (xnSecond.SelectSingleNode("LocalIP").InnerText != "") + { + if (AddressIP != xnSecond.SelectSingleNode("LocalIP").InnerText&& AddressIP!="127.0.0.1") + { + app.LocalIP = ""; + app.BuildingID = ""; + app.Floor = ""; + app.devicemark = ""; + app.deviceid = ""; + app.HttpUrl = ""; + app.DeviceType = ""; + app.FileServerPath = ""; + } + else + { + app.LocalIP = xnSecond.SelectSingleNode("LocalIP").InnerText; + } + } + + + } + + xnSecond = xnFirst.SelectSingleNode("MQTT"); + if (xnSecond == null) + { + log.WriteLogFile("配置文件错误-未发现MQTT标签"); + return; + } + else + { + if (xnSecond.SelectSingleNode("UserName").InnerText != "") + app.rabbitMQ.UserName = xnSecond.SelectSingleNode("UserName").InnerText; + if (xnSecond.SelectSingleNode("Password").InnerText != "") + app.rabbitMQ.Password = xnSecond.SelectSingleNode("Password").InnerText; + if (xnSecond.SelectSingleNode("HostName").InnerText != "") + app.rabbitMQ.HostName = xnSecond.SelectSingleNode("HostName").InnerText; + if (xnSecond.SelectSingleNode("Port").InnerText != "") + app.rabbitMQ.Port =Convert.ToInt32( xnSecond.SelectSingleNode("Port").InnerText); + + + } + + } + else + { + XmlDocument doc = new XmlDocument(); // 创建dom对象 + XmlDeclaration xmldecl; + xmldecl = doc.CreateXmlDeclaration("1.0", "gb2312", null); + doc.AppendChild(xmldecl); + XmlElement root = doc.CreateElement("Config"); // 创建根节点 + + doc.AppendChild(root); // 加入到xml document + XmlElement FillItem; // 创建FillItem元素 + + FillItem = doc.CreateElement("DeviceInfo"); + root.AppendChild(FillItem); // 添加到xml document + + XmlElement Node = doc.CreateElement("BuildingID"); + Node.InnerText = app.BuildingID; + FillItem.AppendChild(Node); + + Node = doc.CreateElement("Floor"); + Node.InnerText = app.Floor; + FillItem.AppendChild(Node); + + Node = doc.CreateElement("deviceid"); + Node.InnerText = app.deviceid; + FillItem.AppendChild(Node); + + Node = doc.CreateElement("devicemark"); + Node.InnerText = app.deviceid; + FillItem.AppendChild(Node); + + Node = doc.CreateElement("devicetype"); + Node.InnerText = app.DeviceType; + FillItem.AppendChild(Node); + + FillItem = doc.CreateElement("Http"); + root.AppendChild(FillItem); // 添加到xml document + + Node = doc.CreateElement("LocalIP"); + Node.InnerText = app.LocalIP; + FillItem.AppendChild(Node); + + Node = doc.CreateElement("Url"); + Node.InnerText = app.HttpUrl; + FillItem.AppendChild(Node); + + + FillItem = doc.CreateElement("MQTT"); + root.AppendChild(FillItem); // 添加到xml document + + Node = doc.CreateElement("UserName"); + Node.InnerText = app.rabbitMQ.UserName; + FillItem.AppendChild(Node); + + Node = doc.CreateElement("Password"); + Node.InnerText = app.rabbitMQ.Password; + FillItem.AppendChild(Node); + + Node = doc.CreateElement("HostName"); + Node.InnerText = app.rabbitMQ.HostName; + FillItem.AppendChild(Node); + + Node = doc.CreateElement("Port"); + Node.InnerText = app.rabbitMQ.Port.ToString(); + FillItem.AppendChild(Node); + + MemoryStream stream = new MemoryStream(); + XmlTextWriter writer = new XmlTextWriter(stream, null); + writer.Formatting = System.Xml.Formatting.Indented; + doc.Save(writer); + StreamReader sr = new StreamReader(stream, Encoding.UTF8); + + stream.Position = 0; + + string XMLString = sr.ReadToEnd(); + doc.Save(@"config\\config.xml"); // 保存文件 + sr.Close(); + stream.Close(); + } + } + catch (Exception e) + { + log.WriteLogFile("LoadConfig:[" + e.ToString() + "]"); + } + } + + /// + /// /加载配置 + /// + public void LoadInitialConfig() + { + try + { + string fpath = Directory.GetCurrentDirectory() + "\\config\\"; + if (!Directory.Exists(fpath)) + { + DirectoryInfo directoryInfo = new DirectoryInfo(fpath); + directoryInfo.Create(); + } + string strConfigxml = AppDomain.CurrentDomain.BaseDirectory + "config//InitialConfig.xml"; + if (File.Exists(strConfigxml) == true) + { + XmlDocument doc = new XmlDocument(); + doc.Load(strConfigxml); + XmlNode xnFirst = doc.SelectSingleNode("Config"); + XmlNode xnSecond = xnFirst.SelectSingleNode("Http"); + if (xnSecond == null) + { + log.WriteLogFile("配置文件错误-未发现Http标签"); + return; + } + else + { + if (xnSecond.SelectSingleNode("HttpUrl").InnerText != "") + app.configurl = xnSecond.SelectSingleNode("HttpUrl").InnerText; + if (xnSecond.SelectSingleNode("WebSocketAddress").InnerText != "") + app.configwebsocket = xnSecond.SelectSingleNode("WebSocketAddress").InnerText; + if (xnSecond.SelectSingleNode("RegKey").InnerText != "") + app.mallRegKey = xnSecond.SelectSingleNode("RegKey").InnerText; + if (xnSecond.SelectSingleNode("Startexe").InnerText != "") + app.configstartexe = xnSecond.SelectSingleNode("Startexe").InnerText; + if (xnSecond.SelectSingleNode("Port").InnerText != "") + app.configport = xnSecond.SelectSingleNode("Port").InnerText; + if (xnSecond.SelectSingleNode("MallCode").InnerText != "") + app.mallCode = xnSecond.SelectSingleNode("MallCode").InnerText; + } + + + } + + } + catch (Exception e) + { + log.WriteLogFile("LoadInitialConfig:[" + e.ToString() + "]"); + } + } + /// + /// /修改配置 + /// + public void WriteToInitialConfig() + { + try + { + string fpath = Directory.GetCurrentDirectory() + "\\config\\"; + if (!Directory.Exists(fpath)) + { + DirectoryInfo directoryInfo = new DirectoryInfo(fpath); + directoryInfo.Create(); + } + string strConfigxml = AppDomain.CurrentDomain.BaseDirectory + "config//InitialConfig.xml"; + if (File.Exists(strConfigxml) == true) + { + XmlDocument doc = new XmlDocument(); + doc.Load(strConfigxml); + XmlNode xnFirst = doc.SelectSingleNode("Config"); + XmlNode xnSecond = xnFirst.SelectSingleNode("Http"); + if (xnSecond == null) + { + XmlElement HttpNode = doc.CreateElement("Http"); + HttpNode.InnerText = app.deviceid; + xnFirst.AppendChild(HttpNode); + + XmlElement Node = doc.CreateElement("HttpUrl"); + Node.InnerText = app.configurl; + HttpNode.AppendChild(Node); + + Node = doc.CreateElement("WebSocketAddress"); + Node.InnerText = app.configwebsocket; + HttpNode.AppendChild(Node); + + Node = doc.CreateElement("RegKey"); + Node.InnerText = app.mallRegKey; + HttpNode.AppendChild(Node); + + Node = doc.CreateElement("Startexe"); + Node.InnerText = app.configstartexe; + HttpNode.AppendChild(Node); + + Node = doc.CreateElement("Port"); + Node.InnerText = app.configport; + HttpNode.AppendChild(Node); + + Node = doc.CreateElement("MallCode"); + Node.InnerText = app.mallCode; + HttpNode.AppendChild(Node); + } + else + { + XmlNode xnnode = xnSecond.SelectSingleNode("HttpUrl"); + if (xnnode == null) + { + XmlElement Node = doc.CreateElement("HttpUrl"); + Node.InnerText = app.configurl; + xnSecond.AppendChild(Node); + } + else + { + xnSecond.SelectSingleNode("HttpUrl").InnerText = app.configurl; + } + + xnnode = xnSecond.SelectSingleNode("RegKey"); + if (xnnode == null) + { + XmlElement Node = doc.CreateElement("RegKey"); + Node.InnerText = app.mallRegKey; + xnSecond.AppendChild(Node); + } + else + { + xnSecond.SelectSingleNode("RegKey").InnerText = app.mallRegKey; + } + + xnnode = xnSecond.SelectSingleNode("WebSocketAddress"); + if (xnnode == null) + { + XmlElement Node = doc.CreateElement("WebSocketAddress"); + Node.InnerText = app.configwebsocket; + xnSecond.AppendChild(Node); + } + else + { + xnSecond.SelectSingleNode("WebSocketAddress").InnerText = app.configwebsocket; + } + + xnnode = xnSecond.SelectSingleNode("Startexe"); + if (xnnode == null) + { + XmlElement Node = doc.CreateElement("Startexe"); + Node.InnerText = app.configstartexe; + xnSecond.AppendChild(Node); + } + else + { + xnSecond.SelectSingleNode("Startexe").InnerText = app.configstartexe; + } + + xnnode = xnSecond.SelectSingleNode("Port"); + if (xnnode == null) + { + XmlElement Node = doc.CreateElement("Port"); + Node.InnerText = app.configport; + xnSecond.AppendChild(Node); + } + else + { + xnSecond.SelectSingleNode("Port").InnerText = app.configport; + } + + xnnode = xnSecond.SelectSingleNode("MallCode"); + if (xnnode == null) + { + XmlElement Node = doc.CreateElement("MallCode"); + Node.InnerText = app.mallCode; + xnSecond.AppendChild(Node); + } + else + { + xnSecond.SelectSingleNode("MallCode").InnerText = app.mallCode; + } + } + + doc.Save(strConfigxml); + } + else + { + XmlDocument doc = new XmlDocument(); // 创建dom对象 + XmlDeclaration xmldecl; + xmldecl = doc.CreateXmlDeclaration("1.0", "gb2312", null); + doc.AppendChild(xmldecl); + XmlElement root = doc.CreateElement("Config"); // 创建根节点 + + doc.AppendChild(root); // 加入到xml document + XmlElement HttpNode = doc.CreateElement("Http"); + HttpNode.InnerText = app.deviceid; + root.AppendChild(HttpNode); + + XmlElement Node = doc.CreateElement("HttpUrl"); + Node.InnerText = app.configurl; + HttpNode.AppendChild(Node); + + Node = doc.CreateElement("RegKey"); + Node.InnerText = app.mallRegKey; + HttpNode.AppendChild(Node); + + Node = doc.CreateElement("WebSocketAddress"); + Node.InnerText = app.configwebsocket; + HttpNode.AppendChild(Node); + + + Node = doc.CreateElement("Startexe"); + Node.InnerText = app.configstartexe; + HttpNode.AppendChild(Node); + + Node = doc.CreateElement("Port"); + Node.InnerText = app.configport; + HttpNode.AppendChild(Node); + + Node = doc.CreateElement("MallCode"); + Node.InnerText = app.mallCode; + HttpNode.AppendChild(Node); + + MemoryStream stream = new MemoryStream(); + XmlTextWriter writer = new XmlTextWriter(stream, null); + writer.Formatting = System.Xml.Formatting.Indented; + doc.Save(writer); + StreamReader sr = new StreamReader(stream, Encoding.UTF8); + + stream.Position = 0; + + string XMLString = sr.ReadToEnd(); + doc.Save(@"config\\InitialConfig.xml"); // 保存文件 + sr.Close(); + stream.Close(); + } + + + } + catch (Exception e) + { + log.WriteLogFile("WriteConfig:[" + e.ToString() + "]"); + } + } + public void WriteToConfig() + { + try + { + string fpath = Directory.GetCurrentDirectory() + "\\config\\"; + if (!Directory.Exists(fpath)) + { + DirectoryInfo directoryInfo = new DirectoryInfo(fpath); + directoryInfo.Create(); + } + string strConfigxml = AppDomain.CurrentDomain.BaseDirectory + "config//Config.xml"; + if (File.Exists(strConfigxml) == true) + { + XmlDocument doc = new XmlDocument(); + doc.Load(strConfigxml); + XmlNode xnFirst = doc.SelectSingleNode("Config"); + XmlNode xnSecond = xnFirst.SelectSingleNode("DeviceInfo"); + if (xnSecond == null) + { + log.WriteLogFile("配置文件错误-未发现DeviceInfo标签"); + return; + } + else + { + XmlNode xnnode = xnSecond.SelectSingleNode("BuildingID"); + if (xnnode == null) + { + XmlElement Node = doc.CreateElement("BuildingID"); + Node.InnerText = app.BuildingID; + xnSecond.AppendChild(Node); + } + else + { + xnSecond.SelectSingleNode("BuildingID").InnerText = app.BuildingID; + } + + xnnode = xnSecond.SelectSingleNode("Floor"); + if (xnnode == null) + { + XmlElement Node = doc.CreateElement("Floor"); + Node.InnerText = app.Floor; + xnSecond.AppendChild(Node); + } + else + { + xnSecond.SelectSingleNode("Floor").InnerText = app.Floor; + } + + xnnode = xnSecond.SelectSingleNode("deviceid"); + if (xnnode == null) + { + XmlElement Node = doc.CreateElement("deviceid"); + Node.InnerText = app.deviceid; + xnSecond.AppendChild(Node); + } + else + { + xnSecond.SelectSingleNode("deviceid").InnerText = app.deviceid; + } + + xnnode = xnSecond.SelectSingleNode("devicemark"); + if (xnnode == null) + { + XmlElement Node = doc.CreateElement("devicemark"); + Node.InnerText = app.devicemark; + xnSecond.AppendChild(Node); + } + else + { + xnSecond.SelectSingleNode("devicemark").InnerText = app.devicemark; + } + + xnnode = xnSecond.SelectSingleNode("devicetype"); + if (xnnode == null) + { + XmlElement Node = doc.CreateElement("devicetype"); + Node.InnerText = app.DeviceType; + xnSecond.AppendChild(Node); + } + else + { + xnSecond.SelectSingleNode("devicetype").InnerText = app.DeviceType; + } + + xnnode = xnSecond.SelectSingleNode("fileserverpath"); + if (xnnode == null) + { + XmlElement Node = doc.CreateElement("fileserverpath"); + Node.InnerText = app.FileServerPath; + xnSecond.AppendChild(Node); + } + else + { + xnSecond.SelectSingleNode("fileserverpath").InnerText = app.FileServerPath; + } + + } + xnSecond = xnFirst.SelectSingleNode("Http"); + if (xnSecond == null) + { + XmlElement HttpNode = doc.CreateElement("Http"); + HttpNode.InnerText = app.deviceid; + xnFirst.AppendChild(HttpNode); + + XmlElement Node = doc.CreateElement("LocalIP"); + Node.InnerText = app.LocalIP; + HttpNode.AppendChild(Node); + + Node = doc.CreateElement("Url"); + Node.InnerText = app.HttpUrl; + HttpNode.AppendChild(Node); + } + else + { + xnSecond.SelectSingleNode("LocalIP").InnerText = app.LocalIP; + xnSecond.SelectSingleNode("Url").InnerText = app.HttpUrl; + } + + xnSecond = xnFirst.SelectSingleNode("MQTT"); + if (xnSecond == null) + { + XmlElement HttpNode = doc.CreateElement("MQTT"); + HttpNode.InnerText = app.deviceid; + xnFirst.AppendChild(HttpNode); + + XmlElement Node = doc.CreateElement("UserName"); + Node.InnerText = app.rabbitMQ.UserName; + HttpNode.AppendChild(Node); + + Node = doc.CreateElement("Password"); + Node.InnerText = app.rabbitMQ.Password; + HttpNode.AppendChild(Node); + + Node = doc.CreateElement("HostName"); + Node.InnerText = app.rabbitMQ.HostName; + HttpNode.AppendChild(Node); + + Node = doc.CreateElement("Port"); + Node.InnerText = app.rabbitMQ.Port.ToString(); + HttpNode.AppendChild(Node); + } + else + { + xnSecond.SelectSingleNode("UserName").InnerText = app.rabbitMQ.UserName; + xnSecond.SelectSingleNode("Password").InnerText = app.rabbitMQ.Password; + xnSecond.SelectSingleNode("HostName").InnerText = app.rabbitMQ.HostName; + xnSecond.SelectSingleNode("Port").InnerText = app.rabbitMQ.Port.ToString(); + } + doc.Save(strConfigxml); + } + else + { + XmlDocument doc = new XmlDocument(); // 创建dom对象 + XmlDeclaration xmldecl; + xmldecl = doc.CreateXmlDeclaration("1.0", "gb2312", null); + doc.AppendChild(xmldecl); + XmlElement root = doc.CreateElement("Config"); // 创建根节点 + + doc.AppendChild(root); // 加入到xml document + XmlElement FillItem; // 创建FillItem元素 + XmlElement FillMQTTItem; // 创建FillItem元素 + + FillItem = doc.CreateElement("DeviceInfo"); + root.AppendChild(FillItem); // 添加到xml document + FillMQTTItem = doc.CreateElement("MQTT"); + root.AppendChild(FillMQTTItem); // 添加到xml document + + XmlElement Node = doc.CreateElement("BuildingID"); + Node.InnerText = app.BuildingID; + FillItem.AppendChild(Node); + + Node = doc.CreateElement("Floor"); + Node.InnerText = app.Floor; + FillItem.AppendChild(Node); + + Node = doc.CreateElement("deviceid"); + Node.InnerText = app.deviceid; + FillItem.AppendChild(Node); + + Node = doc.CreateElement("devicemark"); + Node.InnerText = app.devicemark; + FillItem.AppendChild(Node); + + Node = doc.CreateElement("devicetype"); + Node.InnerText = app.DeviceType; + FillItem.AppendChild(Node); + + Node = doc.CreateElement("fileserverpath"); + Node.InnerText = app.FileServerPath; + FillItem.AppendChild(Node); + + FillItem = doc.CreateElement("Http"); + root.AppendChild(FillItem); // 添加到xml document + + Node = doc.CreateElement("LocalIP"); + Node.InnerText = app.LocalIP; + FillItem.AppendChild(Node); + + Node = doc.CreateElement("Url"); + Node.InnerText = app.HttpUrl; + FillItem.AppendChild(Node); + + XmlElement NodeMQTT = doc.CreateElement("UserName"); + NodeMQTT.InnerText = app.rabbitMQ == null ? "" : app.rabbitMQ.UserName; + FillMQTTItem.AppendChild(NodeMQTT); + + NodeMQTT = doc.CreateElement("Password"); + NodeMQTT.InnerText = app.rabbitMQ == null ? "" : app.rabbitMQ.Password; + FillMQTTItem.AppendChild(NodeMQTT); + + NodeMQTT = doc.CreateElement("HostName"); + NodeMQTT.InnerText = app.rabbitMQ == null ? "" : app.rabbitMQ.HostName; + FillMQTTItem.AppendChild(NodeMQTT); + + NodeMQTT = doc.CreateElement("Port"); + NodeMQTT.InnerText = app.rabbitMQ == null ? "" : app.rabbitMQ.Port.ToString(); + FillMQTTItem.AppendChild(NodeMQTT); + + MemoryStream stream = new MemoryStream(); + XmlTextWriter writer = new XmlTextWriter(stream, null); + writer.Formatting = System.Xml.Formatting.Indented; + doc.Save(writer); + StreamReader sr = new StreamReader(stream, Encoding.UTF8); + + stream.Position = 0; + + string XMLString = sr.ReadToEnd(); + doc.Save(@"config\\config.xml"); // 保存文件 + sr.Close(); + stream.Close(); + } + + + } + catch (Exception e) + { + log.WriteLogFile("WriteConfig:[" + e.ToString() + "]"); + } + } + + + public bool WriteToExeConfig(AppListModel exeinfo) + { + try + { + string fpath = Directory.GetCurrentDirectory() + "\\config\\"; + if (!Directory.Exists(fpath)) + { + DirectoryInfo directoryInfo = new DirectoryInfo(fpath); + directoryInfo.Create(); + } + string strConfigxml = AppDomain.CurrentDomain.BaseDirectory + "config//ExeConfig.xml"; + if (File.Exists(strConfigxml) == true) + { + if (!UpdateExeConfig(exeinfo)) + { + + XmlDocument doc = new XmlDocument(); + doc.Load(strConfigxml); + XmlNode xnFirst = doc.SelectSingleNode("Root"); + XmlElement FillItem; // 创建FillItem元素 + + FillItem = doc.CreateElement("ExeInfo"); + // 添加到xml document + + XmlElement Node = doc.CreateElement("AppID"); + Node.InnerText = exeinfo.AppID; + FillItem.AppendChild(Node); + + Node = doc.CreateElement("AppType"); + Node.InnerText = exeinfo.AppType; + FillItem.AppendChild(Node); + + Node = doc.CreateElement("Code"); + Node.InnerText = exeinfo.Code; + FillItem.AppendChild(Node); + + Node = doc.CreateElement("Default"); + Node.InnerText = exeinfo.Default; + FillItem.AppendChild(Node); + + Node = doc.CreateElement("File"); + Node.InnerText = exeinfo.File; + FillItem.AppendChild(Node); + + Node = doc.CreateElement("Logo"); + Node.InnerText = exeinfo.Logo; + FillItem.AppendChild(Node); + + Node = doc.CreateElement("Name"); + Node.InnerText = exeinfo.Name; + FillItem.AppendChild(Node); + + Node = doc.CreateElement("PackageName"); + Node.InnerText = exeinfo.PackageName; + FillItem.AppendChild(Node); + + Node = doc.CreateElement("PlatformType"); + Node.InnerText = exeinfo.PlatformType; + FillItem.AppendChild(Node); + + Node = doc.CreateElement("ShelfTime"); + Node.InnerText = exeinfo.ShelfTime; + FillItem.AppendChild(Node); + + Node = doc.CreateElement("Startup"); + Node.InnerText = exeinfo.Startup; + FillItem.AppendChild(Node); + + Node = doc.CreateElement("Version"); + Node.InnerText = exeinfo.Version; + FillItem.AppendChild(Node); + + xnFirst.AppendChild(FillItem); + doc.Save(strConfigxml); + } + } + else + { + XmlDocument doc = new XmlDocument(); // 创建dom对象 + XmlDeclaration xmldecl; + xmldecl = doc.CreateXmlDeclaration("1.0", "gb2312", null); + doc.AppendChild(xmldecl); + XmlElement root = doc.CreateElement("Root"); // 创建根节点 + + doc.AppendChild(root); // 加入到xml document + XmlElement FillItem; // 创建FillItem元素 + + FillItem = doc.CreateElement("ExeInfo"); + // 添加到xml document + + XmlElement Node = doc.CreateElement("AppID"); + Node.InnerText = exeinfo.AppID; + FillItem.AppendChild(Node); + + Node = doc.CreateElement("AppType"); + Node.InnerText = exeinfo.AppType; + FillItem.AppendChild(Node); + + Node = doc.CreateElement("Code"); + Node.InnerText = exeinfo.Code; + FillItem.AppendChild(Node); + + Node = doc.CreateElement("Default"); + Node.InnerText = exeinfo.Default; + FillItem.AppendChild(Node); + + Node = doc.CreateElement("File"); + Node.InnerText = exeinfo.File; + FillItem.AppendChild(Node); + + Node = doc.CreateElement("Logo"); + Node.InnerText = exeinfo.Logo; + FillItem.AppendChild(Node); + + Node = doc.CreateElement("Name"); + Node.InnerText = exeinfo.Name; + FillItem.AppendChild(Node); + + Node = doc.CreateElement("PackageName"); + Node.InnerText = exeinfo.PackageName; + FillItem.AppendChild(Node); + + Node = doc.CreateElement("PlatformType"); + Node.InnerText = exeinfo.PlatformType; + FillItem.AppendChild(Node); + + Node = doc.CreateElement("ShelfTime"); + Node.InnerText = exeinfo.ShelfTime; + FillItem.AppendChild(Node); + + Node = doc.CreateElement("Startup"); + Node.InnerText = exeinfo.Startup; + FillItem.AppendChild(Node); + + Node = doc.CreateElement("Version"); + Node.InnerText = exeinfo.Version; + FillItem.AppendChild(Node); + + root.AppendChild(FillItem); + + MemoryStream stream = new MemoryStream(); + XmlTextWriter writer = new XmlTextWriter(stream, null); + writer.Formatting = System.Xml.Formatting.Indented; + doc.Save(writer); + StreamReader sr = new StreamReader(stream, Encoding.UTF8); + + stream.Position = 0; + + string XMLString = sr.ReadToEnd(); + doc.Save(@"config\\ExeConfig.xml"); // 保存配置文件 + sr.Close(); + stream.Close(); + } + return true; + + } + catch (Exception e) + { + log.WriteLogFile("WriteExeConfig:[" + e.ToString() + "]", "ExeConfigLog"); + return false; + } + } + public bool UpdateExeConfig(AppListModel exeinfo) + { + try + { + string fpath = Directory.GetCurrentDirectory() + "\\config\\ExeConfig.xml"; + if (!File.Exists(fpath)) + { + return WriteToExeConfig(exeinfo); + + } + string strConfigxml = AppDomain.CurrentDomain.BaseDirectory + "config//ExeConfig.xml"; + if (File.Exists(strConfigxml) == true) + { + XmlDocument doc = new XmlDocument(); + doc.Load(strConfigxml); + XmlNode xnFirst = doc.SelectSingleNode("Root"); + XmlNode xnSecond = xnFirst.SelectSingleNode("ExeInfo"); + if (xnSecond == null) + { + log.WriteLogFile("配置文件错误-未发现ExeInfo标签"); + return false; + } + XmlNodeList xnChildList = xnFirst.ChildNodes; + + + for (int i = 0; i < xnChildList.Count; i++) + { + XmlNode xnChild = xnChildList.Item(i); + XmlNodeList xnn = xnChild.ChildNodes; + + for (int j = 0; j < xnn.Count; j++) + { + XmlNode xnChildItem = xnn.Item(j); + if (xnChildItem.LocalName.Equals("Code")) + { + if (xnChildItem.InnerText.ToString().Trim().Equals(exeinfo.Code)) + { + xnChild.SelectSingleNode("AppID").InnerText = exeinfo.AppID; + xnChild.SelectSingleNode("AppType").InnerText = exeinfo.AppType; + xnChild.SelectSingleNode("Default").InnerText = exeinfo.Default; + xnChild.SelectSingleNode("File").InnerText = exeinfo.File; + xnChild.SelectSingleNode("Logo").InnerText = exeinfo.Logo; + xnChild.SelectSingleNode("Name").InnerText = exeinfo.Name; + xnChild.SelectSingleNode("PackageName").InnerText = exeinfo.PackageName; + xnChild.SelectSingleNode("PlatformType").InnerText = exeinfo.PlatformType; + xnChild.SelectSingleNode("ShelfTime").InnerText = exeinfo.ShelfTime; + xnChild.SelectSingleNode("Startup").InnerText = exeinfo.Startup; + xnChild.SelectSingleNode("Version").InnerText = exeinfo.Version; + doc.Save(strConfigxml); + return true; + } + + } + } + } + + + } + + } + catch (Exception e) + { + log.WriteLogFile("UpdateExeConfig:[" + e.ToString() + "]", "ExeConfigLog"); + + } + return false; + } + + public bool RemoveExeConfig(string code,ref string filePath,ref string logo,ref string startup) + { + try + { + string fpath = Directory.GetCurrentDirectory() + "\\config\\ExeConfig.xml"; + if (!File.Exists(fpath)) + { + log.WriteLogFile("配置文件错误-未发现ExeConfig.xml文件"); + return false; + + } + string strConfigxml = AppDomain.CurrentDomain.BaseDirectory + "config//ExeConfig.xml"; + if (File.Exists(strConfigxml) == true) + { + XmlDocument doc = new XmlDocument(); + doc.Load(strConfigxml); + XmlNode xnFirst = doc.SelectSingleNode("Root"); + XmlNode xnSecond = xnFirst.SelectSingleNode("ExeInfo"); + if (xnSecond == null) + { + log.WriteLogFile("配置文件错误-未发现ExeInfo标签"); + return false; + } + XmlNodeList xnChildList = xnFirst.ChildNodes; + + + for (int i = 0; i < xnChildList.Count; i++) + { + XmlNode xnChild = (XmlElement)xnChildList.Item(i); + XmlNodeList xnn = xnChild.ChildNodes; + + for (int j = 0; j < xnn.Count; j++) + { + XmlNode xnChildItem = xnn.Item(j); + if (xnChildItem.LocalName.Equals("Code")) + { + if (xnChildItem.InnerText.ToString().Trim().Equals(code)) + { + + xnFirst.RemoveChild(xnChild); + filePath= xnChild.SelectSingleNode("File").InnerText; + logo = xnChild.SelectSingleNode("Logo").InnerText; + startup= xnChild.SelectSingleNode("Startup").InnerText; + doc.Save(strConfigxml); + return true; + } + + } + } + } + + + } + + } + catch (Exception e) + { + log.WriteLogFile("UpdateExeConfig:[" + e.ToString() + "]", "ExeConfigLog"); + + } + return false; + } + + + public bool WriteToAppTimeConfig(List timeList) + { + try + { + string fpath = Directory.GetCurrentDirectory() + "\\config\\"; + if (!Directory.Exists(fpath)) + { + DirectoryInfo directoryInfo = new DirectoryInfo(fpath); + directoryInfo.Create(); + } + string strConfigxml = AppDomain.CurrentDomain.BaseDirectory + "config//AppTimeConfig.xml"; + if (File.Exists(strConfigxml)) + { + File.Delete(strConfigxml); + } + if (timeList.Count > 0) + { + XmlDocument doc = new XmlDocument(); // 创建dom对象 + XmlDeclaration xmldecl; + xmldecl = doc.CreateXmlDeclaration("1.0", "gb2312", null); + doc.AppendChild(xmldecl); + XmlElement root = doc.CreateElement("Root"); // 创建根节点 + + doc.AppendChild(root); // 加入到xml document + + foreach (var item in timeList) + { + XmlElement FillItem; // 创建FillItem元素 + + FillItem = doc.CreateElement("AppTimeInfo"); + // 添加到xml document + + XmlElement Node = doc.CreateElement("AppCode"); + Node.InnerText = item.AppCode; + FillItem.AppendChild(Node); + + Node = doc.CreateElement("BeginTimeSlot"); + Node.InnerText = item.BeginTimeSlot; + FillItem.AppendChild(Node); + + Node = doc.CreateElement("EndTimeSlot"); + Node.InnerText = item.EndTimeSlot; + FillItem.AppendChild(Node); + root.AppendChild(FillItem); + } + MemoryStream stream = new MemoryStream(); + XmlTextWriter writer = new XmlTextWriter(stream, null); + writer.Formatting = System.Xml.Formatting.Indented; + doc.Save(writer); + StreamReader sr = new StreamReader(stream, Encoding.UTF8); + + stream.Position = 0; + + string XMLString = sr.ReadToEnd(); + doc.Save(@"config\\AppTimeConfig.xml"); // 保存配置文件 + sr.Close(); + stream.Close(); + } + return true; + + } + catch (Exception e) + { + log.WriteLogFile("WriteToaAppTimeConfig:[" + e.ToString() + "]", "ExeConfigLog"); + return false; + } + } + + /// + /// 读取ExeConfig配置文件中的应用信息 + /// + public void ReadAppInfo(ref List AppList) + { + try + { + AppList.Clear(); + string fpath = Directory.GetCurrentDirectory() + "\\config\\ExeConfig.xml"; + if (!File.Exists(fpath)) + { + return; + } + string strConfigxml = AppDomain.CurrentDomain.BaseDirectory + "config//ExeConfig.xml"; + if (File.Exists(strConfigxml) == true) + { + XmlDocument doc = new XmlDocument(); + doc.Load(strConfigxml); + XmlNode xnFirst = doc.SelectSingleNode("Root"); + XmlNode xnSecond = xnFirst.SelectSingleNode("ExeInfo"); + if (xnSecond == null) + { + log.WriteLogFile("配置文件错误-未发现ExeInfo标签"); + return; + } + XmlNodeList xnChildList = xnFirst.ChildNodes; + + + for (int i = 0; i < xnChildList.Count; i++) + { + XmlNode xnChild = xnChildList.Item(i); + XmlNodeList xnn = xnChild.ChildNodes; + AppListModel appinfo = new AppListModel(); + if (xnn.Count > 0) + { + for (int j = 0; j < xnn.Count; j++) + { + XmlNode xnChildItem = xnn.Item(j); + if (xnChildItem.LocalName.Equals("AppID")) + { + appinfo.AppID = xnChildItem.InnerText.ToString(); + } + else if (xnChildItem.LocalName.Equals("AppType")) + { + appinfo.AppType = xnChildItem.InnerText.ToString(); + } + else if (xnChildItem.LocalName.Equals("Code")) + { + appinfo.Code = xnChildItem.InnerText.ToString(); + } + else if (xnChildItem.LocalName.Equals("Default")) + { + appinfo.Default = xnChildItem.InnerText.ToString(); + } + else if (xnChildItem.LocalName.Equals("File")) + { + appinfo.File = xnChildItem.InnerText.ToString(); + } + else if (xnChildItem.LocalName.Equals("Logo")) + { + appinfo.Logo = xnChildItem.InnerText.ToString(); + } + else if (xnChildItem.LocalName.Equals("Name")) + { + appinfo.Name = xnChildItem.InnerText.ToString(); + } + else if (xnChildItem.LocalName.Equals("PackageName")) + { + appinfo.PackageName = xnChildItem.InnerText.ToString(); + } + else if (xnChildItem.LocalName.Equals("PlatformType")) + { + appinfo.PlatformType = xnChildItem.InnerText.ToString(); + } + else if (xnChildItem.LocalName.Equals("ShelfTime")) + { + appinfo.ShelfTime = xnChildItem.InnerText.ToString(); + } + else if (xnChildItem.LocalName.Equals("Startup")) + { + appinfo.Startup = xnChildItem.InnerText.ToString(); + } + else if (xnChildItem.LocalName.Equals("Version")) + { + appinfo.Version = xnChildItem.InnerText.ToString(); + } + } + if (string.IsNullOrEmpty(appinfo.ShelfTime) || Convert.ToDateTime(appinfo.ShelfTime) > DateTime.Now.AddDays(-1)) + { + AppList.Add(appinfo); + } + } + } + } + } + catch (Exception ex) + { + log.WriteLogFile("读取ExeConfig配置文件失败"+ex.ToString(),"ExeConfigLog"); + } + } + + public void ReadAppTimeInfo(ref List AppTimeList) + { + try + { + AppTimeList.Clear(); + string fpath = Directory.GetCurrentDirectory() + "\\config\\AppTimeConfig.xml"; + if (!File.Exists(fpath)) + { + return; + } + string strConfigxml = AppDomain.CurrentDomain.BaseDirectory + "config//AppTimeConfig.xml"; + if (File.Exists(strConfigxml) == true) + { + XmlDocument doc = new XmlDocument(); + doc.Load(strConfigxml); + XmlNode xnFirst = doc.SelectSingleNode("Root"); + XmlNode xnSecond = xnFirst.SelectSingleNode("AppTimeInfo"); + if (xnSecond == null) + { + log.WriteLogFile("配置文件错误-未发现AppTimeInfo标签"); + return; + } + XmlNodeList xnChildList = xnFirst.ChildNodes; + + + for (int i = 0; i < xnChildList.Count; i++) + { + XmlNode xnChild = xnChildList.Item(i); + XmlNodeList xnn = xnChild.ChildNodes; + AppTimeModel appTime = new AppTimeModel(); + if (xnn.Count > 0) + { + for (int j = 0; j < xnn.Count; j++) + { + XmlNode xnChildItem = xnn.Item(j); + if (xnChildItem.LocalName.Equals("AppCode")) + { + appTime.AppCode = xnChildItem.InnerText.ToString(); + } + else if (xnChildItem.LocalName.Equals("BeginTimeSlot")) + { + appTime.BeginTimeSlot = xnChildItem.InnerText.ToString(); + } + else if (xnChildItem.LocalName.Equals("EndTimeSlot")) + { + appTime.EndTimeSlot = xnChildItem.InnerText.ToString(); + } + + } + AppTimeList.Add(appTime); + } + } + } + } + catch (Exception ex) + { + log.WriteLogFile("读取AppTimeInfo配置文件失败" + ex.ToString(), "AppTimeInfoLog"); + } + } + + public bool UpdateConfig(string devNum) + { + try + { + string fpath = Directory.GetCurrentDirectory() + "\\config\\config.xml"; + if (!File.Exists(fpath)) + { + DirectoryInfo directoryInfo = new DirectoryInfo(fpath); + directoryInfo.Create(); + + } + string strConfigxml = AppDomain.CurrentDomain.BaseDirectory + "config//config.xml"; + if (File.Exists(strConfigxml) == true) + { + XmlDocument doc = new XmlDocument(); + doc.Load(strConfigxml); + XmlNode xnFirst = doc.SelectSingleNode("Config"); + XmlNode xnSecond = xnFirst.SelectSingleNode("DeviceInfo"); + if (xnSecond == null) + { + log.WriteLogFile("配置文件错误-未发现DeviceInfo标签"); + return false; + } + else { + XmlNode xnnode = xnSecond.SelectSingleNode("devicemark"); + if (xnnode != null) + { + xnSecond.SelectSingleNode("devicemark").InnerText = app.devicemark; + } + } + doc.Save(strConfigxml); + return true; + } + + } + catch (Exception e) + { + log.WriteLogFile("UpdateConfig:[" + e.ToString() + "]", "ExeConfigLog"); + + } + return false; + } + + public void WriteToScreenConfig(string touchType, string screenEffect,string screenFilePath, string effectType) + { + try + { + string fpath = Directory.GetCurrentDirectory() + "\\exefile\\"; + if (!Directory.Exists(fpath)) + { + DirectoryInfo directoryInfo = new DirectoryInfo(fpath); + directoryInfo.Create(); + } + fpath = Directory.GetCurrentDirectory() + "\\exefile\\PCScreen\\"; + if (!Directory.Exists(fpath)) + { + DirectoryInfo directoryInfo = new DirectoryInfo(fpath); + directoryInfo.Create(); + } + fpath = Directory.GetCurrentDirectory() + "\\exefile\\PCScreen\\config\\"; + if (!Directory.Exists(fpath)) + { + DirectoryInfo directoryInfo = new DirectoryInfo(fpath); + directoryInfo.Create(); + } + string strConfigxml = AppDomain.CurrentDomain.BaseDirectory + "exefile//PCScreen//config//Screensaver.xml"; + if (File.Exists(strConfigxml) == true) + { + XmlDocument doc = new XmlDocument(); + doc.Load(strConfigxml); + XmlNode xnFirst = doc.SelectSingleNode("Config"); + XmlNode xnSecond = xnFirst.SelectSingleNode("Parameter"); + if (xnSecond == null) + { + log.WriteLogFile("配置文件错误-未发现Parameter标签"); + return; + } + else + { + XmlNode xnnode = xnSecond.SelectSingleNode("TouchType"); + if (xnnode == null) + { + XmlElement Node = doc.CreateElement("TouchType"); + Node.InnerText = touchType; + xnSecond.AppendChild(Node); + } + else + { + xnSecond.SelectSingleNode("TouchType").InnerText = touchType; + } + + xnnode = xnSecond.SelectSingleNode("ScreenEffect"); + if (xnnode == null) + { + XmlElement Node = doc.CreateElement("ScreenEffect"); + Node.InnerText = screenEffect; + xnSecond.AppendChild(Node); + } + else + { + xnSecond.SelectSingleNode("ScreenEffect").InnerText = screenEffect; + } + + xnnode = xnSecond.SelectSingleNode("ScreenFilePath"); + if (xnnode == null) + { + XmlElement Node = doc.CreateElement("ScreenFilePath"); + Node.InnerText = screenFilePath; + xnSecond.AppendChild(Node); + } + else + { + xnSecond.SelectSingleNode("ScreenFilePath").InnerText = screenFilePath; + } + + xnnode = xnSecond.SelectSingleNode("EffectType"); + if (xnnode == null) + { + XmlElement Node = doc.CreateElement("EffectType"); + Node.InnerText = effectType; + xnSecond.AppendChild(Node); + } + else + { + xnSecond.SelectSingleNode("EffectType").InnerText = effectType; + } + } + + doc.Save(strConfigxml); + } + else + { + XmlDocument doc = new XmlDocument(); // 创建dom对象 + XmlDeclaration xmldecl; + xmldecl = doc.CreateXmlDeclaration("1.0", "gb2312", null); + doc.AppendChild(xmldecl); + XmlElement root = doc.CreateElement("Config"); // 创建根节点 + + doc.AppendChild(root); // 加入到xml document + XmlElement FillItem; // 创建FillItem元素 + + FillItem = doc.CreateElement("Parameter"); + root.AppendChild(FillItem); // 添加到xml document + + XmlElement Node = doc.CreateElement("TouchType"); + Node.InnerText = touchType; + FillItem.AppendChild(Node); + + Node = doc.CreateElement("ScreenEffect"); + Node.InnerText = screenEffect; + FillItem.AppendChild(Node); + + Node = doc.CreateElement("ScreenFilePath"); + Node.InnerText = screenFilePath; + FillItem.AppendChild(Node); + + Node = doc.CreateElement("EffectType"); + Node.InnerText = effectType; + FillItem.AppendChild(Node); + + MemoryStream stream = new MemoryStream(); + XmlTextWriter writer = new XmlTextWriter(stream, null); + writer.Formatting = System.Xml.Formatting.Indented; + doc.Save(writer); + StreamReader sr = new StreamReader(stream, Encoding.UTF8); + + stream.Position = 0; + + string XMLString = sr.ReadToEnd(); + doc.Save(@"exefile//PCScreen//config//Screensaver.xml"); // 保存文件 + sr.Close(); + stream.Close(); + } + + + } + catch (Exception e) + { + log.WriteLogFile("WriteToScreenConfig:[" + e.ToString() + "]"); + } + } + } +} diff --git a/Container/Common/Class_Log.cs b/Container/Common/Class_Log.cs new file mode 100644 index 0000000..5a04661 --- /dev/null +++ b/Container/Common/Class_Log.cs @@ -0,0 +1,424 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.IO; +using Microsoft.Win32; + +namespace Container.Common +{ + class Class_Log + { + /**/ + /// + /// 写入日志文件 + /// + /// + public void WriteLogFile(string input,string strfileName="Errlog") + { + try + { + /**/ + ///指定日志文件的目录 + strfileName = strfileName + DateTime.Now.ToString("yyyy-MM-dd"); + string fpath = Directory.GetCurrentDirectory() + "\\log\\" + DateTime.Now.ToString("yyyy-MM-dd") + "\\"; + if (!Directory.Exists(fpath)) + { + DirectoryInfo directoryInfo = new DirectoryInfo(fpath); + directoryInfo.Create(); + } + + string fname = Directory.GetCurrentDirectory() + "\\log\\" + DateTime.Now.ToString("yyyy-MM-dd") + "\\" + strfileName + ".txt"; + + /**/ + ///定义文件信息对象 + /// + FileInfo finfo = new FileInfo(fname); + if (!finfo.Exists) + { + FileStream fs = new FileStream(fname, FileMode.Create, FileAccess.Write); + //fs = File.Create(fname); + fs.Close(); + finfo = new FileInfo(fname); + } + /**/ + ///判断文件是否存在以及是否大于2K + if (finfo.Length > 1024 * 1024 * 10) + { + /**/ + ///文件超过10MB则重命名 + File.Move(Directory.GetCurrentDirectory() + "\\LogFile.txt", Directory.GetCurrentDirectory() + DateTime.Now.TimeOfDay + "\\LogFile.txt"); + /**/ + ///删除该文件 + //finfo.Delete(); + } + //finfo.AppendText(); + /**/ + ///创建只写文件流 + + using (FileStream fs = finfo.OpenWrite()) + { + /**/ + ///根据上面创建的文件流创建写数据流 + StreamWriter w = new StreamWriter(fs); + + /**/ + ///设置写数据流的起始位置为文件流的末尾 + w.BaseStream.Seek(0, SeekOrigin.End); + /**/ + ///写入“Log Entry : ” + w.Write("\n\rLog Entry : "); + /**/ + ///写入当前系统时间并换行 + w.Write("{0} {1} \n\r", DateTime.Now.ToLongTimeString(), + DateTime.Now.ToLongDateString()); + /**/ + ///写入日志内容并换行 + w.Write(input + "\n\r"); + /**/ + ///写入------------------------------------“并换行 + w.Write("------------------------------------\n\r"); + /**/ + ///清空缓冲区内容,并把缓冲区内容写入基础流 + w.Flush(); + /**/ + ///关闭写数据流 + w.Close(); + } + } + catch{} + + } + + /**/ + /// + /// 写入日志文件 + /// + /// + public string Writestart() + { + try + { + /**/ + ///指定日志文件的目录 + string fpath = Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath); + if (!Directory.Exists(fpath)) + { + DirectoryInfo directoryInfo = new DirectoryInfo(fpath); + directoryInfo.Create(); + } + + string fname = fpath + "\\start.bat"; + + /**/ + ///定义文件信息对象 + /// + FileInfo finfo = new FileInfo(fname); + if (!finfo.Exists) + { + FileStream fs = new FileStream(fname, FileMode.Create, FileAccess.Write); + //fs = File.Create(fname); + fs.Close(); + finfo = new FileInfo(fname); + } + using (FileStream fs = new FileStream(fname, FileMode.Create)) + { + /**/ + ///根据上面创建的文件流创建写数据流 + StreamWriter w = new StreamWriter(fs,Encoding.Default); + + /**/ + ///设置写数据流的起始位置为文件流的末尾 + w.BaseStream.Seek(0, SeekOrigin.End); + /**/ + ///写入“start.bat : ” + w.Write("\n\r%1 mshta vbscript:CreateObject(\"WScript.Shell\").Run(\"%~s0 ::\",0,FALSE)(window.close)&&exit"); + + w.WriteLine(Environment.NewLine); + + w.Write("\n\r Timeout 60"); + /**/ + w.WriteLine(Environment.NewLine); + w.Write("\n\r" + Path.GetPathRoot(System.Windows.Forms.Application.ExecutablePath).Replace("\\", "/").TrimEnd('/')); + /**/ + w.WriteLine(Environment.NewLine); + w.Write("cd " + Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath)); + /**/ + w.WriteLine(Environment.NewLine); + w.Write("start " + Path.GetFileName(System.Windows.Forms.Application.ExecutablePath)); + /**/ + /**/ + w.Flush(); + /**/ + ///关闭写数据流 + w.Close(); + } + return fname; + } + catch { } + return ""; + + } + /// + /// 删除 month 个月之前的 strFileName日志 + /// + /// + /// + public static void DeleteLogFile(string strFileName = "ErrLog", int month = 1) + { + try + { + string logPath = Directory.GetCurrentDirectory() + "\\log\\" + strFileName; + if (!Directory.Exists(logPath))//若文件夹不存在则返回 + return; + else + logPath += "\\"; + DirectoryInfo theFolder = new DirectoryInfo(@logPath); + FileInfo[] fileInfo = theFolder.GetFiles(); + foreach (FileInfo NextFile in fileInfo) //遍历文件 + { + DateTime dt1 = Convert.ToDateTime(NextFile.Name.Substring(strFileName.Length, NextFile.Name.Length - strFileName.Length - 4) + " 00:00:00"); + DateTime dt2 = DateTime.Now.AddMonths(-month); + if (dt1 < dt2) + { + NextFile.Delete(); + } + } + } + catch + { + } + + + } + + public void DeleteFiles(string fileName = "") + { + try + { + if (string.IsNullOrEmpty(fileName)) + fileName = Directory.GetCurrentDirectory() + "\\log"; + if (!Directory.Exists(fileName))//若文件夹不存在则返回 + return; + DirectoryInfo dir = new DirectoryInfo(fileName);//new DirectoryInfo(Directory.GetCurrentDirectory() + "\\log"); + //不是目录 + + if (dir == null) + return; + //DateTime DT = dir.CreationTime; + + FileSystemInfo[] files = dir.GetFileSystemInfos(); + for (int i = 0; i < files.Length; i++) + { + FileInfo file = files[i] as FileInfo; + //是文件 + if (file != null) + { + DateTime DT = file.CreationTime; + if (DateTime.Now.Month - DT.Month >= 1) + { + file.Delete(); + } + } + else + { + DirectoryInfo dir1 = files[i] as DirectoryInfo; + if (dir1 != null) + { + DateTime DT = dir1.CreationTime; + if (DateTime.Now.Month - DT.Month >= 1) + { + //dir1.Delete(); + System.IO.Directory.Delete(fileName + "\\" + dir1.Name, true); + } + } + } + } + } + catch + { + } + + } + + + /**/ + /// + /// 写入日志文件 + /// + /// + public string WriteAppStart(string name,string url) + { + try + { + /**/ + ///指定日志文件的目录 + string fpath = Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath); + if (!Directory.Exists(fpath)) + { + DirectoryInfo directoryInfo = new DirectoryInfo(fpath); + directoryInfo.Create(); + } + fpath = fpath + "\\exefile"; + if (!Directory.Exists(fpath)) + { + DirectoryInfo directoryInfo = new DirectoryInfo(fpath); + directoryInfo.Create(); + } + + string fname = fpath + "\\"+name+".bat"; + + /**/ + ///定义文件信息对象 + /// + FileInfo finfo = new FileInfo(fname); + if (!finfo.Exists) + { + FileStream fs = new FileStream(fname, FileMode.Create, FileAccess.Write); + //fs = File.Create(fname); + fs.Close(); + finfo = new FileInfo(fname); + } + using (FileStream fs = new FileStream(fname, FileMode.Create)) + { + /**/ + ///根据上面创建的文件流创建写数据流 + StreamWriter w = new StreamWriter(fs, Encoding.Default); + + /**/ + ///设置写数据流的起始位置为文件流的末尾 + w.BaseStream.Seek(0, SeekOrigin.End); + /**/ + ///写入“start.bat : ” + w.Write("\n\r%1 mshta vbscript:CreateObject(\"WScript.Shell\").Run(\"%~s0 ::\",0,FALSE)(window.close)&&exit"); + w.WriteLine(Environment.NewLine); + w.Write("\n\r setx GOOGLE_API_KEY \"no\""); + w.WriteLine(Environment.NewLine); + w.Write("\n\r setx GOOGLE_DEFAULT_CLIENT_ID \"no\""); + w.WriteLine(Environment.NewLine); + w.Write("\n\r setx GOOGLE_DEFAULT_CLIENT_SECRET \"no\""); + /**/ + w.WriteLine(Environment.NewLine); + string ChromiumPath = GetChromiumPath(); + if (string.IsNullOrEmpty(ChromiumPath)) { + return ""; + } + w.Write("\n\r \""+ChromiumPath+ "\" -incognito --disable-background-networking --kiosk --disable-pinch \"" + url+"\""); + /**/ + /**/ + w.Flush(); + /**/ + ///关闭写数据流 + w.Close(); + } + return fname; + } + catch { } + return ""; + + } + + private string GetChromiumPath() + { + string path = string.Empty; + try + { + //string softName = textBox1.Text.ToString(); + string strKeyName = "InstallerSuccessLaunchCmdLine"; + string softPath = @"SOFTWARE\Chromium"; + RegistryKey regKey = Registry.CurrentUser; + RegistryKey regSubKey = regKey.OpenSubKey(softPath, false); + + object objResult = regSubKey.GetValue(strKeyName); + RegistryValueKind regValueKind = regSubKey.GetValueKind(strKeyName); + if (regValueKind == Microsoft.Win32.RegistryValueKind.String) + { + path = objResult.ToString(); + } + } + catch (Exception e) + { + string s = e.Message; + //this.label3.Text = "朋友,获取程序路径失败!"; + } + return path; + } + + /**/ + /// + /// 写入日志文件 + /// + /// + public void WriteRecordToFile(string programCode, string time) + { + try + { + string fpath = Directory.GetCurrentDirectory() + "\\record\\"; + if (!Directory.Exists(fpath)) + { + DirectoryInfo directoryInfo = new DirectoryInfo(fpath); + directoryInfo.Create(); + } + + string fname = Directory.GetCurrentDirectory() + "\\record\\Record.txt"; + + /**/ + ///定义文件信息对象 + /// + FileInfo finfo = new FileInfo(fname); + if (!finfo.Exists) + { + FileStream fs = new FileStream(fname, FileMode.Create, FileAccess.Write); + //fs = File.Create(fname); + fs.Close(); + finfo = new FileInfo(fname); + } + //finfo.AppendText(); + /**/ + ///创建只写文件流 + + using (FileStream fs = finfo.OpenWrite()) + { + /**/ + ///根据上面创建的文件流创建写数据流 + StreamWriter w = new StreamWriter(fs); + + /**/ + ///设置写数据流的起始位置为文件流的末尾 + w.BaseStream.Seek(0, SeekOrigin.End); + /**/ + ///写入“Log Entry : ” + /// + if (finfo.Length > 10) + { + w.Write(","); + } + string wir = "{\"ProgramCode\": \"" + programCode + "\",\"Time\": " + time + ",\"PlayTime\":\"" + DateTime.Now.ToString("G") + "\" }"; + w.Write(wir); + /**/ + ///写入当前系统时间并换行 + // w.Write("{0} {1} \n\r", DateTime.Now.ToLongTimeString(),DateTime.Now.ToLongDateString()); + /**/ + ///写入日志内容并换行 + // w.Write(input + "\n\r"); + /**/ + ///写入------------------------------------“并换行 + // w.Write("------------------------------------\n\r"); + /**/ + ///清空缓冲区内容,并把缓冲区内容写入基础流 + w.Flush(); + /**/ + ///关闭写数据流 + w.Close(); + } + } + catch (Exception e) + { + WriteLogFile(e.Message, "11111111"); + } + + } + + } +} diff --git a/Container/Common/CommonLib.cs b/Container/Common/CommonLib.cs new file mode 100644 index 0000000..eb4a36d --- /dev/null +++ b/Container/Common/CommonLib.cs @@ -0,0 +1,86 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Container.Common +{ + /// + /// 公共类库 + /// + public class CommonLib + { + + /// + /// 日期转换为时间戳(时间戳单位秒) + /// + /// + /// + public static long ConvertToTimeStamp(DateTime time) + { + DateTime Jan1st1970 = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); + return (long)(time.AddHours(-8) - Jan1st1970).TotalSeconds; + } + /// + /// 获取当前时间戳 + /// + /// + public static long CurrentTime() + { + DateTime Jan1st1970 = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); + return (long)(DateTime.Now.AddHours(-8) - Jan1st1970).TotalSeconds; + } + /// + /// 时间戳转换为日期(时间戳/单位秒) + /// + /// + /// + public static DateTime ConvertToDateTime(long timeStamp) + { + var start = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); + return start.AddMilliseconds(timeStamp).AddHours(8); + } + /// + /// 生成随机数字 + /// + /// 生成长度 + /// 是否要在生成前将当前线程阻止以避免重复 + public static string Number(int Length, bool Sleep) + { + if (Sleep) System.Threading.Thread.Sleep(3); + string result = ""; + System.Random random = new Random(); + for (int i = 0; i < Length; i++) + { + result += random.Next(10).ToString(); + } + return result; + } + + /// + /// 解密(反转再base64解码),常规配置,例如密码 + /// + /// + /// + public static string StringDecode(string str) + { + string result = string.Empty; + try + { + if (!string.IsNullOrEmpty(str)) + { + char[] arr = str.ToCharArray(); + Array.Reverse(arr); + result = Encoding.UTF8.GetString(Convert.FromBase64String(new string(arr))); + } + } + catch (Exception ex) + { + + } + return result; + } + + } +} diff --git a/Container/Common/DeviceInfo.cs b/Container/Common/DeviceInfo.cs new file mode 100644 index 0000000..c990a88 --- /dev/null +++ b/Container/Common/DeviceInfo.cs @@ -0,0 +1,539 @@ +using Microsoft.Win32; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Management; +using System.Runtime.InteropServices; +using System.Text; +using System.Threading.Tasks; + +namespace Container.Common +{ + class DeviceInfo + { + /// + /// 获取硬盘容量 + /// + public string GetDiskSize() + { + string result = string.Empty; + StringBuilder sb = new StringBuilder(); + try + { + string hdId = string.Empty; + ManagementClass hardDisk = new ManagementClass(WindowsAPIType.win32_DiskDrive.ToString()); + ManagementObjectCollection hardDiskC = hardDisk.GetInstances(); + foreach (ManagementObject m in hardDiskC) + { + long capacity = Convert.ToInt64(m[WindowsAPIKeys.Size.ToString()].ToString()); + sb.Append(CommonUtlity.ToGB(capacity, 1000.0) + "+"); + } + result = sb.ToString().TrimEnd('+'); + } + catch + { + + } + return result; + } + + } + public class CommonUtlity + { + /// + /// 将字节转换为GB + /// + /// 字节值 + /// 除数,硬盘除以1000,内存除以1024 + /// + public static string ToGB(double size, double mod) + { + String[] units = new String[] { "B", "KB", "MB", "GB", "TB", "PB" }; + int i = 0; + while (size >= mod) + { + size /= mod; + i++; + } + return Math.Round(size) + units[i]; + } + } + /// + /// windows api 名称 + /// + public enum WindowsAPIType + { + /// + /// 内存 + /// + Win32_PhysicalMemory, + /// + /// cpu + /// + Win32_Processor, + /// + /// 硬盘 + /// + win32_DiskDrive, + /// + /// 电脑型号 + /// + Win32_ComputerSystemProduct, + /// + /// 分辨率 + /// + Win32_DesktopMonitor, + /// + /// 显卡 + /// + Win32_VideoController, + /// + /// 操作系统 + /// + Win32_OperatingSystem + + } + + public enum WindowsAPIKeys + { + /// + /// 名称 + /// + Name, + /// + /// 显卡芯片 + /// + VideoProcessor, + /// + /// 显存大小 + /// + AdapterRAM, + /// + /// 分辨率宽 + /// + ScreenWidth, + /// + /// 分辨率高 + /// + ScreenHeight, + /// + /// 电脑型号 + /// + Version, + /// + /// 硬盘容量 + /// + Size, + /// + /// 内存容量 + /// + Capacity, + /// + /// cpu核心数 + /// + NumberOfCores + } + + + /// + /// 电脑信息类 单例 + /// + public class Computer + { + private static Computer _instance; + private static readonly object _lock = new object(); + //private Computer() + //{ } + //public static Computer CreateComputer() + //{ + // if (_instance == null) + // { + // lock (_lock) + // { + // if (_instance == null) + // { + // _instance = new Computer(); + // } + // } + // } + // return _instance; + //} + /// + /// 查找cpu的名称,主频, 核心数 + /// + /// + public Tuple GetCPU() + { + Tuple result = null; + try + { + string str = string.Empty; + ManagementClass mcCPU = new ManagementClass(WindowsAPIType.Win32_Processor.ToString()); + ManagementObjectCollection mocCPU = mcCPU.GetInstances(); + foreach (ManagementObject m in mocCPU) + { + string name = m[WindowsAPIKeys.Name.ToString()].ToString(); + string[] parts = name.Split('@'); + result = new Tuple(parts[0].Split('-')[0] + "处理器", parts[1]); + break; + } + + } + catch + { + + } + return result; + } + + + /// + /// 获取cpu核心数 + /// + /// + public string GetCPU_Count() + { + string str = "查询失败"; + try + { + int coreCount = 0; + foreach (var item in new System.Management.ManagementObjectSearcher("Select * from " + + WindowsAPIType.Win32_Processor.ToString()).Get()) + { + coreCount += int.Parse(item[WindowsAPIKeys.NumberOfCores.ToString()].ToString()); + } + if (coreCount == 2) + { + return "双核"; + } + str = coreCount.ToString() + "核"; + } + catch + { + + } + return str; + } + + /// + /// 获取系统内存大小 + /// + /// 内存大小(单位M) + public string GetPhisicalMemory() + { + ManagementObjectSearcher searcher = new ManagementObjectSearcher(); //用于查询一些如系统信息的管理对象 + searcher.Query = new SelectQuery(WindowsAPIType.Win32_PhysicalMemory.ToString(), "", + new string[] { WindowsAPIKeys.Capacity.ToString() });//设置查询条件 + ManagementObjectCollection collection = searcher.Get(); //获取内存容量 + ManagementObjectCollection.ManagementObjectEnumerator em = collection.GetEnumerator(); + + long capacity = 0; + while (em.MoveNext()) + { + ManagementBaseObject baseObj = em.Current; + if (baseObj.Properties[WindowsAPIKeys.Capacity.ToString()].Value != null) + { + try + { + capacity += long.Parse(baseObj.Properties[WindowsAPIKeys.Capacity.ToString()].Value.ToString()); + } + catch + { + return "查询失败"; + } + } + } + return CommonUtlity.ToGB((double)capacity, 1024.0); + } + + /// + /// 获取硬盘容量 + /// + public string GetDiskSize() + { + string result = string.Empty; + StringBuilder sb = new StringBuilder(); + try + { + string hdId = string.Empty; + ManagementClass hardDisk = new ManagementClass(WindowsAPIType.win32_DiskDrive.ToString()); + ManagementObjectCollection hardDiskC = hardDisk.GetInstances(); + foreach (ManagementObject m in hardDiskC) + { + long capacity = Convert.ToInt64(m[WindowsAPIKeys.Size.ToString()].ToString()); + sb.Append(CommonUtlity.ToGB(capacity, 1000.0) + "+"); + } + result = sb.ToString().TrimEnd('+'); + } + catch + { + + } + return result; + } + /// + /// 电脑型号 + /// + public string GetVersion() + { + string str = "查询失败"; + try + { + string hdId = string.Empty; + ManagementClass hardDisk = new ManagementClass(WindowsAPIType.Win32_ComputerSystemProduct.ToString()); + ManagementObjectCollection hardDiskC = hardDisk.GetInstances(); + foreach (ManagementObject m in hardDiskC) + { + str = m[WindowsAPIKeys.Version.ToString()].ToString(); break; + } + } + catch + { + + } + return str; + } + /// + /// 获取分辨率 + /// + public string GetFenbianlv() + { + string result = "1920*1080"; + try + { + string hdId = string.Empty; + ManagementClass hardDisk = new ManagementClass(WindowsAPIType.Win32_DesktopMonitor.ToString()); + ManagementObjectCollection hardDiskC = hardDisk.GetInstances(); + foreach (ManagementObject m in hardDiskC) + { + result = m[WindowsAPIKeys.ScreenWidth.ToString()].ToString() + "*" + +m[WindowsAPIKeys.ScreenHeight.ToString()].ToString(); + break; + } + } + catch + { + + } + return result; + } + /// + /// 显卡 芯片,显存大小 + /// + public Tuple GetVideoController() + { + Tuple result = null; + try + { + + ManagementClass hardDisk = new ManagementClass(WindowsAPIType.Win32_VideoController.ToString()); + ManagementObjectCollection hardDiskC = hardDisk.GetInstances(); + foreach (ManagementObject m in hardDiskC) + { + result = new Tuple(m[WindowsAPIKeys.VideoProcessor.ToString()].ToString() +.Replace("Family", ""), CommonUtlity.ToGB(Convert.ToInt64(m[WindowsAPIKeys.AdapterRAM.ToString()].ToString()), 1024.0)); + break; + } + } + catch + { + + } + return result; + } + + /// + /// 操作系统版本 + /// + public string GetOS_Version() + { + string str = "Windows 10"; + try + { + string hdId = string.Empty; + ManagementClass hardDisk = new ManagementClass(WindowsAPIType.Win32_OperatingSystem.ToString()); + ManagementObjectCollection hardDiskC = hardDisk.GetInstances(); + foreach (ManagementObject m in hardDiskC) + { + str = m[WindowsAPIKeys.Name.ToString()].ToString().Split('|')[0].Replace("Microsoft", ""); + break; + } + } + catch + { + + } + return str; + } + + + [DllImport("Kernel32.dll")] + public static extern void GlobalMemoryStatus(ref MEMORY_INFO meminfo); + [StructLayout(LayoutKind.Sequential)] + public struct MEMORY_INFO + { + public uint dwLength; + public uint dwMemoryLoad; + public uint dwTotalPhys; + public uint dwAvailPhys; + public uint dwTotalPageFile; + public uint dwAvailPageFile; + public uint dwTotalVirtual; + public uint dwAvailVirtual; + } + + + MEMORY_INFO MemInfo = new MEMORY_INFO(); + + + /// + /// 获取当前CPU温度、内存使用率 + /// + public string GetNow_WindowsState() + { + string str = ""; + Double CPUtprt = 0; + ManagementObjectSearcher mos = new ManagementObjectSearcher(@"root\WMI", @"Select * From MSAcpi_ThermalZoneTemperature"); + foreach (ManagementObject mo in mos.Get()) + { + CPUtprt = Convert.ToDouble(Convert.ToDouble(mo.GetPropertyValue("CurrentTemperature").ToString()) - 2732) / 10; + + } + str = "CPU温度:" + CPUtprt.ToString() + "℃ 内存使用率:" + MemInfo.dwMemoryLoad.ToString() + "%"; + return str; + } + + + /// + /// 获取当前Windows版本、序列号 + /// + public string WindowsInfo() + { + RegistryKey rk; + rk = Registry.LocalMachine.OpenSubKey("Software\\Microsoft\\Windows NT\\CurrentVersion"); + string s = ""; + if (rk.GetValue("ProductName") != null) + { + s = "当前操作系统版本:" + rk.GetValue("ProductName").ToString(); + } + else + return ""; + + if (rk.GetValue("CSDVersion") != null) + { + s = s + "\r\n" + rk.GetValue("CSDVersion").ToString(); + } + if (rk.GetValue("ProductId") != null) + { + s = s + "\r\n当前操作系统安装序列号:\r\n" + rk.GetValue("ProductId").ToString(); + } + if (rk.GetValue("CurrentBuildNumber") != null) + { + s = s + "\r\n当前系统版本号:" + rk.GetValue("CurrentBuildNumber").ToString(); + } + + rk.Close(); + return s; + } + + /// + /// 获取操作系统位数(x32/64) + /// + /// int + public static int GetOSBit() + { + try + { + string addressWidth = String.Empty; + ConnectionOptions mConnOption = new ConnectionOptions(); + ManagementScope mMs = new ManagementScope(@"\\localhost", mConnOption); + ObjectQuery mQuery = new ObjectQuery("select AddressWidth from Win32_Processor"); + ManagementObjectSearcher mSearcher = new ManagementObjectSearcher(mMs, mQuery); + ManagementObjectCollection mObjectCollection = mSearcher.Get(); + foreach (ManagementObject mObject in mObjectCollection) + { + addressWidth = mObject["AddressWidth"].ToString(); + } + return Int32.Parse(addressWidth); + } + catch (Exception ex) + { + Console.WriteLine(ex.ToString()); + return 32; + } + } + + + string GetWindowsLanguage() + { + string lg = ""; + + int lcid = System.Globalization.CultureInfo.CurrentCulture.LCID; + string LanguageName = System.Globalization.CultureInfo.CurrentCulture.NativeName; + string LangName = System.Globalization.RegionInfo.CurrentRegion.NativeName; + System.Console.WriteLine("Lcid:" + lcid.ToString()); + lg = "Lcid:" + lcid.ToString(); + System.Console.WriteLine("区域语言:" + LanguageName); + lg += "区域语言:" + LanguageName; + System.Console.WriteLine("区域语言2:" + LangName); + lg += "区域语言2:" + LangName; + return lg; + //try + //{ + // Process MyProcess = new Process(); + // //设定程序名 + // MyProcess.StartInfo.FileName = "cmd.exe"; + + // //关闭Shell的使用 + // MyProcess.StartInfo.UseShellExecute = false; + // //重定向标准输入 + // MyProcess.StartInfo.RedirectStandardInput = true; + // //重定向标准输出 + // MyProcess.StartInfo.RedirectStandardOutput = true; + // //重定向错误输出 + // MyProcess.StartInfo.RedirectStandardError = true; + // //设置不显示窗口 + // MyProcess.StartInfo.CreateNoWindow = true; + // MyProcess.StartInfo.Arguments = "/c C:\\Windows\\System32\\cmd.exe"; + + + + // string cmdtext = string.Empty; + // cmdtext = "slmgr.vbs /xpr" ; //关机 + + // Console.WriteLine(cmdtext); + // //执行VER命令 + // MyProcess.Start(); + // MyProcess.StandardInput.WriteLine(cmdtext); + // //MessageBox.Show(MyProcess.StandardOutput.ReadToEnd()); + // //MessageBox.Show(MyProcess.StandardError.ReadToEnd()); + // string output = ""; + // char[] outl = new char[2048]; + // string error = ""; + // using (System.IO.StreamReader myOutput = MyProcess.StandardOutput) + // { + // myOutput.Read(outl, 0, 2048); + // output = new string(outl); + // log.WriteLogFile(output, "cmdexelog"); + + // } + // using (System.IO.StreamReader myError = MyProcess.StandardError) + // { + + // myError.Read(outl, 0, 1024); + // error = new string(outl); + // log.WriteLogFile(error, "cmdexelog"); + // } + // } + // } + //} + //catch (Exception ex) + //{ + // log.WriteLogFile(ex.ToString()); + //} + + } + + } +} diff --git a/Container/Common/FileTypeJudgment.cs b/Container/Common/FileTypeJudgment.cs new file mode 100644 index 0000000..1fc021a --- /dev/null +++ b/Container/Common/FileTypeJudgment.cs @@ -0,0 +1,23 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Container.Common +{ + /// + /// 文件类型判断 + /// + internal sealed class FileTypeJudgment + { + //实现类型判断的接口 + public IJudgeFileType TypeTarget { get; set; } + + //返回判断结果 + public bool Judge(string ext) + { + return this.TypeTarget.JudgeFileType(ext); + } + } +} diff --git a/Container/Common/IJudgeFileType.cs b/Container/Common/IJudgeFileType.cs new file mode 100644 index 0000000..113968d --- /dev/null +++ b/Container/Common/IJudgeFileType.cs @@ -0,0 +1,16 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Container.Common +{ + /// + /// 接口用于判断文件类型 + /// + interface IJudgeFileType + { + bool JudgeFileType(string ext); + } +} diff --git a/Container/Common/IatNativeMethods.cs b/Container/Common/IatNativeMethods.cs new file mode 100644 index 0000000..e2c4fe6 --- /dev/null +++ b/Container/Common/IatNativeMethods.cs @@ -0,0 +1,795 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.InteropServices; +using System.Text; +using System.Threading; +using System.Threading.Tasks; + +namespace Container.Common +{ + static class IatNativeMethods + { + [DllImport("msc_x64.dll", CharSet = CharSet.Ansi)] + public extern static int MSPLogin(string usr, string pwd, string @params); + + [DllImport("msc_x64.dll", CharSet = CharSet.Ansi)] + public extern static IntPtr QISRSessionBegin(string grammarList, string @params, ref int errorCode); + + [DllImport("msc_x64.dll", CharSet = CharSet.Ansi)] + public extern static int QISRAudioWrite(IntPtr sessionID, byte[] waveData, uint waveLen, int audioStatus, + ref int epStatus, ref int recogStatus); + [DllImport("msc_x64.dll", CharSet = CharSet.Ansi)] + public extern static int QISRAudioWrite(IntPtr sessionID, IntPtr waveData, uint waveLen, int audioStatus, + ref int epStatus, ref int recogStatus); + [DllImport("msc_x64.dll", CharSet = CharSet.Ansi)] + public extern static IntPtr QISRGetResult(IntPtr sessionID, ref int rsltStatus, int waitTime, ref int errorCode); + + [DllImport("msc_x64.dll", CharSet = CharSet.Ansi)] + public extern static int QISRSessionEnd(IntPtr sessionID, string hints); + + [DllImport("msc_x64.dll")] + public extern static int MSPLogout(); + + public static string user = ""; + public static string pwd = ""; + public static string loginparam = "appid = 5c2055f8"; + public static IntPtr session_id = IntPtr.Zero; + public static int FRAME_LEN = 640; + /// + /// 初始化语音账号 + /// + public static void initVoice() + { + int ret = IatNativeMethods.MSPLogin(user, pwd, loginparam); + if ((int)Errors.MSP_SUCCESS != ret) + { + Console.WriteLine("MSPLogin failed, error code is:" + ret); + } + } + /// + /// 实时录制识别 + /// + /// + /// + /// + public static string audio_iat(byte[] audio_content, int aud_stat, int ep_stat, int rec_stat, int errcode) + { + if (audio_content == null || audio_content.Length == 0) + return ""; + StringBuilder result = new StringBuilder();//存储最终识别的结果 + //var aud_stat = AudioStatus.MSP_AUDIO_SAMPLE_CONTINUE;//音频状态 + //var ep_stat = EpStatus.MSP_EP_LOOKING_FOR_SPEECH;//端点状态 + //var rec_stat = RecogStatus.MSP_REC_STATUS_SUCCESS;//识别状态 + //int errcode = (int)Errors.MSP_SUCCESS; + //byte[] audio_content; //用来存储音频文件的二进制数据 + int totalLength = 0;//用来记录总的识别后的结果的长度,判断是否超过缓存最大值 + //try + //{ + // audio_content = System.IO.File.ReadAllBytes(audio_path); + // //SoundPlayer player = new SoundPlayer(audio_path); + // //player.Play(); + //} + //catch (Exception e) + //{ + // //Console.WriteLine(e); + // System.Diagnostics.Debug.WriteLine(e.Message); + // audio_content = null; + //} + try + { + if (audio_content == null) + throw new Exception("没有读取到任何内容"); + + + int res = IatNativeMethods.QISRAudioWrite(session_id, audio_content, (uint)audio_content.Length, AudioStatus.MSP_AUDIO_SAMPLE_FIRST, ref ep_stat, ref rec_stat); + if (res != (int)Errors.MSP_SUCCESS) + return ("写入识别的音频失败!" + res); + res = IatNativeMethods.QISRAudioWrite(session_id, null, 0, AudioStatus.MSP_AUDIO_SAMPLE_LAST, ref ep_stat, ref rec_stat); + if (res != (int)Errors.MSP_SUCCESS) + return ("写入音频失败!" + res); + while (RecogStatus.MSP_REC_STATUS_COMPLETE != rec_stat) + { + IntPtr now_result = IatNativeMethods.QISRGetResult(session_id, ref rec_stat, 0, ref errcode); + if (errcode != (int)Errors.MSP_SUCCESS) + return ("获取结果失败:" + errcode); + if (now_result != null) + { + int length = now_result.ToString().Length; + totalLength += length; + if (totalLength > 4096) + return ("缓存空间不够" + totalLength); + result.Append(Marshal.PtrToStringAnsi(now_result)); + } + Thread.Sleep(150);//防止频繁占用cpu + } + } + catch (Exception ex) + { + System.Diagnostics.Debug.WriteLine(ex.Message); + } + finally + { + Console.WriteLine("语音听写结束"); + Console.WriteLine("听写结果: "); + Console.WriteLine(result); + int ret = IatNativeMethods.QISRSessionEnd(session_id, "normal end"); + if (errcode != (int)Errors.MSP_SUCCESS) + { + result.Append("QISRSessionEnd failed, error code is: %d" + ret); + } + } + return result.ToString(); + } + /// + /// 本地文件识别 + /// + /// + /// + /// + public static string localaudio_iat(string audio_path, string session_begin_params = "sub=iat,domain=iat,language=zh_cn,accent=mandarin,sample_rate=16000,result_type=plain,result_encoding=gb2312") + { + if (audio_path == null || audio_path == "") + return ""; + IntPtr session_id = IntPtr.Zero; + StringBuilder result = new StringBuilder();//存储最终识别的结果 + var aud_stat = AudioStatus.MSP_AUDIO_SAMPLE_CONTINUE;//音频状态 + var ep_stat = EpStatus.MSP_EP_LOOKING_FOR_SPEECH;//端点状态 + var rec_stat = RecogStatus.MSP_REC_STATUS_SUCCESS;//识别状态 + int errcode = (int)Errors.MSP_SUCCESS; + byte[] audio_content; //用来存储音频文件的二进制数据 + int totalLength = 0;//用来记录总的识别后的结果的长度,判断是否超过缓存最大值 + try + { + audio_content = System.IO.File.ReadAllBytes(audio_path); + //SoundPlayer player = new SoundPlayer(audio_path); + //player.Play(); + } + catch (Exception e) + { + //Console.WriteLine(e); + System.Diagnostics.Debug.WriteLine(e.Message); + audio_content = null; + } + try + { + if (audio_content == null) + throw new Exception("没有读取到任何内容"); + //Console.WriteLine("开始进行语音听写......."); + session_id = IatNativeMethods.QISRSessionBegin(null, session_begin_params, ref errcode); + if (errcode != (int)Errors.MSP_SUCCESS) + return ("开始一次语音识别失败!"); + int res = IatNativeMethods.QISRAudioWrite(session_id, audio_content, (uint)audio_content.Length, AudioStatus.MSP_AUDIO_SAMPLE_FIRST, ref ep_stat, ref rec_stat); + if (res != (int)Errors.MSP_SUCCESS) + return ("写入识别的音频失败!" + res); + res = IatNativeMethods.QISRAudioWrite(session_id, null, 0, AudioStatus.MSP_AUDIO_SAMPLE_LAST, ref ep_stat, ref rec_stat); + if (res != (int)Errors.MSP_SUCCESS) + return ("写入音频失败!" + res); + while (RecogStatus.MSP_REC_STATUS_COMPLETE != rec_stat) + { + IntPtr now_result = IatNativeMethods.QISRGetResult(session_id, ref rec_stat, 0, ref errcode); + if (errcode != (int)Errors.MSP_SUCCESS) + return ("获取结果失败:" + errcode); + if (now_result != null) + { + int length = now_result.ToString().Length; + totalLength += length; + if (totalLength > 4096) + return ("缓存空间不够" + totalLength); + result.Append(Marshal.PtrToStringAnsi(now_result)); + } + Thread.Sleep(150);//防止频繁占用cpu + } + } + catch (Exception ex) + { + System.Diagnostics.Debug.WriteLine(ex.Message); + } + finally + { + Console.WriteLine("语音听写结束"); + Console.WriteLine("听写结果: "); + Console.WriteLine(result); + int ret = IatNativeMethods.QISRSessionEnd(session_id, "normal end"); + if (errcode != (int)Errors.MSP_SUCCESS) + { + result.Append("QISRSessionEnd failed, error code is: %d" + ret); + } + } + return result.ToString(); + } + + } + + public class AudioStatus + { + + public static int MSP_AUDIO_SAMPLE_INIT = 0; + public static int MSP_AUDIO_SAMPLE_FIRST = 1; + public static int MSP_AUDIO_SAMPLE_CONTINUE = 2; + public static int MSP_AUDIO_SAMPLE_LAST = 4; + } + + public class EpStatus + { + public static int MSP_EP_LOOKING_FOR_SPEECH = 0; + public static int MSP_EP_IN_SPEECH = 1; + public static int MSP_EP_AFTER_SPEECH = 3; + public static int MSP_EP_TIMEOUT = 4; + public static int MSP_EP_ERROR = 5; + public static int MSP_EP_MAX_SPEECH = 6; + public static int MSP_EP_IDLE = 7; + } + public class RecogStatus + { + public static int MSP_REC_STATUS_SUCCESS = 0; + public static int MSP_REC_STATUS_NO_MATCH = 1; + public static int MSP_REC_STATUS_INCOMPLETE = 2; + public static int MSP_REC_STATUS_NON_SPEECH_DETECTED = 3; + public static int MSP_REC_STATUS_SPEECH_DETECTED = 4; + public static int MSP_REC_STATUS_COMPLETE = 5; + public static int MSP_REC_STATUS_MAX_CPU_TIME = 6; + public static int MSP_REC_STATUS_MAX_SPEECH = 7; + public static int MSP_REC_STATUS_STOPPED = 8; + public static int MSP_REC_STATUS_REJECTED = 9; + public static int MSP_REC_STATUS_NO_SPEECH_FOUND = 10; + public static int MSP_REC_STATUS_FAILURE = MSP_REC_STATUS_NO_MATCH; + } + + public enum Errors + { + MSP_SUCCESS = 0, + MSP_ERROR_FAIL = -1, + MSP_ERROR_EXCEPTION = -2, + + /* General errors 10100(0x2774) */ + MSP_ERROR_GENERAL = 10100, /* 0x2774 */ + MSP_ERROR_OUT_OF_MEMORY = 10101, /* 0x2775 */ + MSP_ERROR_FILE_NOT_FOUND = 10102, /* 0x2776 */ + MSP_ERROR_NOT_SUPPORT = 10103, /* 0x2777 */ + MSP_ERROR_NOT_IMPLEMENT = 10104, /* 0x2778 */ + MSP_ERROR_ACCESS = 10105, /* 0x2779 */ + MSP_ERROR_INVALID_PARA = 10106, /* 0x277A */ /* 缺少参数 */ + MSP_ERROR_INVALID_PARA_VALUE = 10107, /* 0x277B */ /* 无效参数值 */ + MSP_ERROR_INVALID_HANDLE = 10108, /* 0x277C */ + MSP_ERROR_INVALID_DATA = 10109, /* 0x277D */ + MSP_ERROR_NO_LICENSE = 10110, /* 0x277E */ /* 引擎授权不足 */ + MSP_ERROR_NOT_INIT = 10111, /* 0x277F */ /* 引擎未初始化,可能是引擎崩溃 */ + MSP_ERROR_NULL_HANDLE = 10112, /* 0x2780 */ + MSP_ERROR_OVERFLOW = 10113, /* 0x2781 */ /* 单用户下模型数超上限(10个), */ + /* 只出现在测试时对一个用户进行并发注册 */ + MSP_ERROR_TIME_OUT = 10114, /* 0x2782 */ /* 超时 */ + MSP_ERROR_OPEN_FILE = 10115, /* 0x2783 */ + MSP_ERROR_NOT_FOUND = 10116, /* 0x2784 */ /* 数据库中模型不存在 */ + MSP_ERROR_NO_ENOUGH_BUFFER = 10117, /* 0x2785 */ + MSP_ERROR_NO_DATA = 10118, /* 0x2786 */ /* 从客户端读音频或从引擎段获取结果时无数据 */ + MSP_ERROR_NO_MORE_DATA = 10119, /* 0x2787 */ + MSP_ERROR_NO_RESPONSE_DATA = 10120, /* 0x2788 */ + MSP_ERROR_ALREADY_EXIST = 10121, /* 0x2789 */ /* 数据库中模型已存在 */ + MSP_ERROR_LOAD_MODULE = 10122, /* 0x278A */ + MSP_ERROR_BUSY = 10123, /* 0x278B */ + MSP_ERROR_INVALID_CONFIG = 10124, /* 0x278C */ + MSP_ERROR_VERSION_CHECK = 10125, /* 0x278D */ + MSP_ERROR_CANCELED = 10126, /* 0x278E */ + MSP_ERROR_INVALID_MEDIA_TYPE = 10127, /* 0x278F */ + MSP_ERROR_CONFIG_INITIALIZE = 10128, /* 0x2790 */ + MSP_ERROR_CREATE_HANDLE = 10129, /* 0x2791 */ + MSP_ERROR_CODING_LIB_NOT_LOAD = 10130, /* 0x2792 */ + MSP_ERROR_USER_CANCELLED = 10131, /* 0x2793 */ + MSP_ERROR_INVALID_OPERATION = 10132, /* 0x2794 */ + MSP_ERROR_MESSAGE_NOT_COMPLETE = 10133, /* 0x2795 */ /* flash */ + MSP_ERROR_NO_EID = 10134, /* 0x2795 */ + MSP_ERROE_OVER_REQ = 10135, /* 0x2797 */ /* client Redundancy request */ + MSP_ERROR_USER_ACTIVE_ABORT = 10136, /* 0x2798 */ /* user abort */ + MSP_ERROR_BUSY_GRMBUILDING = 10137, /* 0x2799 */ + MSP_ERROR_BUSY_LEXUPDATING = 10138, /* 0x279A */ + MSP_ERROR_SESSION_RESET = 10139, /* 0x279B */ /* msc主动终止会话,准备重传 */ + MSP_ERROR_BOS_TIMEOUT = 10140, /* 0x279C */ /* VAD前端点超时 */ + MSP_ERROR_STREAM_FILTER = 10141, /* 0X279D */ /* AIUI当前Stream被过滤 */ + MSP_ERROR_STREAM_CLEAR = 10142, /* 0X279E */ /* AIUI当前Stream被清理 */ + + /* Error codes of network 10200(0x27D8)*/ + MSP_ERROR_NET_GENERAL = 10200, /* 0x27D8 */ + MSP_ERROR_NET_OPENSOCK = 10201, /* 0x27D9 */ /* Open socket */ + MSP_ERROR_NET_CONNECTSOCK = 10202, /* 0x27DA */ /* Connect socket */ + MSP_ERROR_NET_ACCEPTSOCK = 10203, /* 0x27DB */ /* Accept socket */ + MSP_ERROR_NET_SENDSOCK = 10204, /* 0x27DC */ /* Send socket data */ + MSP_ERROR_NET_RECVSOCK = 10205, /* 0x27DD */ /* Recv socket data */ + MSP_ERROR_NET_INVALIDSOCK = 10206, /* 0x27DE */ /* Invalid socket handle */ + MSP_ERROR_NET_BADADDRESS = 10207, /* 0x27EF */ /* Bad network address */ + MSP_ERROR_NET_BINDSEQUENCE = 10208, /* 0x27E0 */ /* Bind after listen/connect */ + MSP_ERROR_NET_NOTOPENSOCK = 10209, /* 0x27E1 */ /* Socket is not opened */ + MSP_ERROR_NET_NOTBIND = 10210, /* 0x27E2 */ /* Socket is not bind to an address */ + MSP_ERROR_NET_NOTLISTEN = 10211, /* 0x27E3 */ /* Socket is not listening */ + MSP_ERROR_NET_CONNECTCLOSE = 10212, /* 0x27E4 */ /* The other side of connection is closed */ + MSP_ERROR_NET_NOTDGRAMSOCK = 10213, /* 0x27E5 */ /* The socket is not datagram type */ + MSP_ERROR_NET_DNS = 10214, /* 0x27E6 */ /* domain name is invalid or dns server does not function well */ + MSP_ERROR_NET_INIT = 10215, /* 0x27E7 */ /* ssl ctx create failed */ + + /*nfl error*/ + MSP_ERROR_NFL_INNER_ERROR = 10216, /* NFL inner error */ + MSP_ERROR_MSS_TIME_OUT = 10217, /* MSS TIMEOUT */ + MSP_ERROT_CLIENT_TIME_OUT = 10218, /* CLIENT TIMEOUT */ + MSP_ERROR_CLIENT_CLOSE = 10219, /* CLIENT CLOSED CONNECTION */ + + MSP_ERROR_CLIENT_AREA_CHANGE = 10220, + MSP_ERROR_NET_SSL_HANDSHAKE = 10221, + MSP_ERROR_NET_INVALID_ROOT_CERT = 10222, + MSP_ERROR_NET_INVALID_CLIENT_CERT = 10223, + MSP_ERROR_NET_INVALID_SERVER_CERT = 10224, + MSP_ERROR_NET_INVALID_KEY = 10225, + MSP_ERROR_NET_CERT_VERIFY_FAILED = 10226, + MSP_ERROR_NET_WOULDBLOCK = 10227, + MSP_ERROR_NET_NOTBLOCK = 10228, + + /* Error codes of mssp message 10300(0x283C) */ + MSP_ERROR_MSG_GENERAL = 10300, /* 0x283C */ + MSP_ERROR_MSG_PARSE_ERROR = 10301, /* 0x283D */ + MSP_ERROR_MSG_BUILD_ERROR = 10302, /* 0x283E */ + MSP_ERROR_MSG_PARAM_ERROR = 10303, /* 0x283F */ + MSP_ERROR_MSG_CONTENT_EMPTY = 10304, /* 0x2840 */ + MSP_ERROR_MSG_INVALID_CONTENT_TYPE = 10305, /* 0x2841 */ + MSP_ERROR_MSG_INVALID_CONTENT_LENGTH = 10306, /* 0x2842 */ + MSP_ERROR_MSG_INVALID_CONTENT_ENCODE = 10307, /* 0x2843 */ + MSP_ERROR_MSG_INVALID_KEY = 10308, /* 0x2844 */ + MSP_ERROR_MSG_KEY_EMPTY = 10309, /* 0x2845 */ + MSP_ERROR_MSG_SESSION_ID_EMPTY = 10310, /* 0x2846 */ /* 会话ID为空 */ + MSP_ERROR_MSG_LOGIN_ID_EMPTY = 10311, /* 0x2847 */ /* 音频序列ID为空 */ + MSP_ERROR_MSG_SYNC_ID_EMPTY = 10312, /* 0x2848 */ + MSP_ERROR_MSG_APP_ID_EMPTY = 10313, /* 0x2849 */ + MSP_ERROR_MSG_EXTERN_ID_EMPTY = 10314, /* 0x284A */ + MSP_ERROR_MSG_INVALID_CMD = 10315, /* 0x284B */ + MSP_ERROR_MSG_INVALID_SUBJECT = 10316, /* 0x284C */ + MSP_ERROR_MSG_INVALID_VERSION = 10317, /* 0x284D */ + MSP_ERROR_MSG_NO_CMD = 10318, /* 0x284E */ + MSP_ERROR_MSG_NO_SUBJECT = 10319, /* 0x284F */ + MSP_ERROR_MSG_NO_VERSION = 10320, /* 0x2850 */ + MSP_ERROR_MSG_MSSP_EMPTY = 10321, /* 0x2851 */ + MSP_ERROR_MSG_NEW_RESPONSE = 10322, /* 0x2852 */ + MSP_ERROR_MSG_NEW_CONTENT = 10323, /* 0x2853 */ + MSP_ERROR_MSG_INVALID_SESSION_ID = 10324, /* 0x2854 */ /* 无效的会话ID(sid) */ + MSP_ERROR_MSG_INVALID_CONTENT = 10325, /* 0x2855 */ + + /* Error codes of DataBase 10400(0x28A0)*/ + MSP_ERROR_DB_GENERAL = 10400, /* 0x28A0 */ /* 数据库异常 */ + MSP_ERROR_DB_EXCEPTION = 10401, /* 0x28A1 */ + MSP_ERROR_DB_NO_RESULT = 10402, /* 0x28A2 */ /* redis中没有找到会话ID(sid) */ + MSP_ERROR_DB_INVALID_USER = 10403, /* 0x28A3 */ + MSP_ERROR_DB_INVALID_PWD = 10404, /* 0x28A4 */ + MSP_ERROR_DB_CONNECT = 10405, /* 0x28A5 */ + MSP_ERROR_DB_INVALID_SQL = 10406, /* 0x28A6 */ + MSP_ERROR_DB_INVALID_APPID = 10407, /* 0x28A7 */ + MSP_ERROR_DB_NO_UID = 10408, + + /* Error codes of Resource 10500(0x2904)*/ + MSP_ERROR_RES_GENERAL = 10500, /* 0x2904 */ + MSP_ERROR_RES_LOAD = 10501, /* 0x2905 */ /* Load resource */ + MSP_ERROR_RES_FREE = 10502, /* 0x2906 */ /* Free resource */ + MSP_ERROR_RES_MISSING = 10503, /* 0x2907 */ /* Resource File Missing */ + MSP_ERROR_RES_INVALID_NAME = 10504, /* 0x2908 */ /* Invalid resource file name */ + MSP_ERROR_RES_INVALID_ID = 10505, /* 0x2909 */ /* Invalid resource ID */ + MSP_ERROR_RES_INVALID_IMG = 10506, /* 0x290A */ /* Invalid resource image pointer */ + MSP_ERROR_RES_WRITE = 10507, /* 0x290B */ /* Write read-only resource */ + MSP_ERROR_RES_LEAK = 10508, /* 0x290C */ /* Resource leak out */ + MSP_ERROR_RES_HEAD = 10509, /* 0x290D */ /* Resource head currupt */ + MSP_ERROR_RES_DATA = 10510, /* 0x290E */ /* Resource data currupt */ + MSP_ERROR_RES_SKIP = 10511, /* 0x290F */ /* Resource file skipped */ + + /* Error codes of TTS 10600(0x2968)*/ + MSP_ERROR_TTS_GENERAL = 10600, /* 0x2968 */ + MSP_ERROR_TTS_TEXTEND = 10601, /* 0x2969 */ /* Meet text end */ + MSP_ERROR_TTS_TEXT_EMPTY = 10602, /* 0x296A */ /* no synth text */ + MSP_ERROR_TTS_LTTS_ERROR = 10603, /* 0x296B */ + + /* Error codes of Recognizer 10700(0x29CC) */ + MSP_ERROR_REC_GENERAL = 10700, /* 0x29CC */ /* 引擎异常 */ + MSP_ERROR_REC_INACTIVE = 10701, /* 0x29CD */ + MSP_ERROR_REC_GRAMMAR_ERROR = 10702, /* 0x29CE */ + MSP_ERROR_REC_NO_ACTIVE_GRAMMARS = 10703, /* 0x29CF */ + MSP_ERROR_REC_DUPLICATE_GRAMMAR = 10704, /* 0x29D0 */ + MSP_ERROR_REC_INVALID_MEDIA_TYPE = 10705, /* 0x29D1 */ + MSP_ERROR_REC_INVALID_LANGUAGE = 10706, /* 0x29D2 */ + MSP_ERROR_REC_URI_NOT_FOUND = 10707, /* 0x29D3 */ + MSP_ERROR_REC_URI_TIMEOUT = 10708, /* 0x29D4 */ + MSP_ERROR_REC_URI_FETCH_ERROR = 10709, /* 0x29D5 */ + MSP_ERROR_REC_PROC_MOD = 10710, /* 0x29D6 */ + + + /* Error codes of Speech Detector 10800(0x2A30) */ + MSP_ERROR_EP_GENERAL = 10800, /* 0x2A30 */ + MSP_ERROR_EP_NO_SESSION_NAME = 10801, /* 0x2A31 */ + MSP_ERROR_EP_INACTIVE = 10802, /* 0x2A32 */ + MSP_ERROR_EP_INITIALIZED = 10803, /* 0x2A33 */ + + /* Error codes of TUV */ + MSP_ERROR_TUV_GENERAL = 10900, /* 0x2A94 */ + MSP_ERROR_TUV_GETHIDPARAM = 10901, /* 0x2A95 */ /* Get Busin Param huanid*/ + MSP_ERROR_TUV_TOKEN = 10902, /* 0x2A96 */ /* Get Token */ + MSP_ERROR_TUV_CFGFILE = 10903, /* 0x2A97 */ /* Open cfg file */ + MSP_ERROR_TUV_RECV_CONTENT = 10904, /* 0x2A98 */ /* received content is error */ + MSP_ERROR_TUV_VERFAIL = 10905, /* 0x2A99 */ /* Verify failure */ + + /* Error codes of IMTV */ + MSP_ERROR_LOGIN_SUCCESS = 11000, /* 0x2AF8 */ /* 成功 */ + MSP_ERROR_LOGIN_NO_LICENSE = 11001, /* 0x2AF9 */ /* 试用次数结束,用户需要付费 */ + MSP_ERROR_LOGIN_SESSIONID_INVALID = 11002, /* 0x2AFA */ /* SessionId失效,需要重新登录通行证 */ + MSP_ERROR_LOGIN_SESSIONID_ERROR = 11003, /* 0x2AFB */ /* SessionId为空,或者非法 */ + MSP_ERROR_LOGIN_UNLOGIN = 11004, /* 0x2AFC */ /* 未登录通行证 */ + MSP_ERROR_LOGIN_INVALID_USER = 11005, /* 0x2AFD */ /* 用户ID无效 */ + MSP_ERROR_LOGIN_INVALID_PWD = 11006, /* 0x2AFE */ /* 用户密码无效 */ + MSP_ERROR_LOGIN_SYSTEM_ERROR = 11099, /* 0x2B5B */ /* 系统错误 */ + + /* Error codes of HCR */ + MSP_ERROR_HCR_GENERAL = 11100, + MSP_ERROR_HCR_RESOURCE_NOT_EXIST = 11101, + MSP_ERROR_HCR_CREATE = 11102, + MSP_ERROR_HCR_DESTROY = 11103, + MSP_ERROR_HCR_START = 11104, + MSP_ERROR_HCR_APPEND_STROKES = 11105, + MSP_ERROR_HCR_INIT = 11106, + MSP_ERROR_HCR_POINT_DECODE = 11107, + MSP_ERROR_HCR_DISPATCH = 11108, + MSP_ERROR_HCR_GETRESULT = 11109, + MSP_ERROR_HCR_RESOURCE = 11110, + + /* Error Codes using in local engine */ + MSP_ERROR_AUTH_NO_LICENSE = 11200, /* 0x2BC0 */ /* 无授权 */ + MSP_ERROR_AUTH_NO_ENOUGH_LICENSE = 11201, /* 0x2BC1 */ /* 授权不足 */ + MSP_ERROR_AUTH_INVALID_LICENSE = 11202, /* 0x2BC2 */ /* 无效的授权 */ + MSP_ERROR_AUTH_LICENSE_EXPIRED = 11203, /* 0x2BC3 */ /* 授权过期 */ + MSP_ERROR_AUTH_NEED_MORE_DATA = 11204, /* 0x2BC4 */ /* 无设备信息 */ + MSP_ERROR_AUTH_LICENSE_TO_BE_EXPIRED = 11205, /* 0x2BC5 */ /* 授权即将过期,警告性错误码 */ + MSP_ERROR_AUTH_INVALID_MACHINE_ID = 11206, /* 0x2BC6 */ /* 无效的机器码 */ + MSP_ERROR_AUTH_LOCAL_ASR_FORBIDDEN = 11207, /* 0x2BC7 */ /* 禁止使用本地识别引擎 */ + MSP_ERROR_AUTH_LOCAL_TTS_FORBIDDEN = 11208, /* 0x2BC8 */ /* 禁止使用本地合成引擎 */ + MSP_ERROR_AUTH_LOCAL_IVW_FORBIDDEN = 11209, /* 0x2BC9 */ /* 禁止使用本地唤醒引擎 */ + MSP_ERROR_AUTH_APPID_NOT_MATCH = 11210, /* 0x2BCA */ /* 资源appid和应用appid不匹配 */ + MSP_ERROR_AUTH_UID_NOT_MATCH = 11211, /* 0x2BCB */ /* 资源uid和登录用户uid不匹配 */ + MSP_ERROR_AUTH_TRIAL_EXPIRED = 11212, /* 0x2BCC */ /* 试用资源过期 */ + MSP_ERROR_AUTH_LOCAL_IFD_FORBIDDEN = 11213, /* 0x2BC9 */ /* 禁止使用本地人脸引擎 */ + + MSP_ERROR_AIUI_NO_ENOUGH_LICENSE = 11216, /* 0x2BD0 */ /* AIUI授权不足 */ + /*Error Codes of Authorization*/ + MSP_ERROR_AUTH_DVC_NO_LICENSE = 11300, + MSP_ERROR_AUTH_DVC_NO_ENOUGH_LICENSE = 11301, + MSP_ERROR_AUTH_DVC_INVALID_LICENSE = 11302, + MSP_ERROR_AUTH_DVC_LICENSE_EXPIRED = 11303, + MSP_ERROR_AUTH_DVC_NEED_MORE_DATA = 11304, + MSP_ERROR_AUTH_DVC_LICENSE_TO_BE_EXPIRED = 11305, + MSP_ERROR_AUTH_DVC_EXCEED_LICENSE = 11306, + + /* Error codes of Ise */ + + MSP_ERROR_ASE_EXCEP_SILENCE = 11401, + MSP_ERROR_ASE_EXCEP_SNRATIO = 11402, + MSP_ERROR_ASE_EXCEP_PAPERDATA = 11403, + MSP_ERROR_ASE_EXCEP_PAPERCONTENTS = 11404, + MSP_ERROR_ASE_EXCEP_NOTMONO = 11405, + MSP_ERROR_ASE_EXCEP_OTHERS = 11406, + MSP_ERROR_ASE_EXCEP_PAPERFMT = 11407, + MSP_ERROR_ASE_EXCEP_ULISTWORD = 11408, + + /* Error codes of Iot */ + MSP_ERROR_IOT_BASE = 11500, + MSP_ERROR_IOT_PARAM_ERROR = 11501, // param error + MSP_ERROR_IOT_INVALID_SERVICE = 11502, // invalid service for iot ProTranServer + MSP_ERROR_IOT_INVALID_PRODUCTID = 11503, // invalid productid for ProTranServer + MSP_EEROR_IOT_INVALID_ATTR = 11504, // invalid attr value for one product in ProTranServer + MSP_ERROR_IOT_INVALID_PLATFORM = 11505, // invalid platform for ProTranServer + MSP_ERROR_IOT_DID_NOT_FOUND = 11506, // not found device id in semantic + + /* Error codes of IVP */ + MSP_ERROR_IVP_GENERAL = 11600, // 内核异常 + MSP_ERROR_IVP_EXTRA_RGN_SOPPORT = 11601, // 注册时向引擎所写音频条数超过上限(9次) + MSP_ERROR_IVP_TRUNCATED = 11602, // 音频截幅(因信号波形的幅度太大,而超出系统的线性范围),如记录尖叫声的音频 + MSP_ERROR_IVP_MUCH_NOISE = 11603, // 音频信噪比过低 + MSP_ERROR_IVP_TOO_LOW = 11604, // 音频能量过低 + MSP_ERROR_IVP_ZERO_AUDIO = 11605, // 无音频 + MSP_ERROR_IVP_UTTER_TOO_SHORT = 11606, // 音频太短 + MSP_ERROR_IVP_TEXT_NOT_MATCH = 11607, // 1.音频和文本不匹配,常见原因1.抢读(在按下录音键之前读) + // 2.录音机的启动电流被录入表现在音频上是在音频首有冲击电流 3.确实不匹配" + MSP_ERROR_IVP_NO_ENOUGH_AUDIO = 11608, // 音频不够,注册自由说,而写入的音频又不够长时会报,告诉调用者继续传音频 + MSP_ERROR_IVP_MODEL_NOT_FOUND_IN_HBASE = 11610, // 模型在hbase中没找到 + + /* Error codes of Face */ + + MSP_ERROR_IFR_NOT_FACE_IMAGE = 11700, // 【无人脸,对应的引擎错误码是20200 】 + MSP_ERROR_FACE_IMAGE_FULL_LEFT = 11701, // 【人脸向左,对应的引擎错误码是20201】 + MSP_ERROR_FACE_IMAGE_FULL_RIGHT = 11702, // 【人脸向右,对应的引擎错误码是20202】 + MSP_ERROR_IMAGE_CLOCKWISE_WHIRL = 11703, // 【顺时针旋转,对应的引擎错误码是20203】 + MSP_ERROR_IMAGE_COUNTET_CLOCKWISE_WHIRL = 11704, // 【逆时针旋转,对应的引擎错误码是20204】 + MSP_ERROR_VALID_IMAGE_SIZE = 11705, // 【图片大小异常 ,对应的引擎错误码是20205】 + MSP_ERROR_ILLUMINATION = 11706, // 【光照异常,对应的引擎错误码是20206】 + MSP_ERROR_FACE_OCCULTATION = 11707, // 【人脸被遮挡,对应的引擎错误码是20207】 + MSP_ERROR_FACE_INVALID_MODEL = 11708, // 【非法模型数据,对应的引擎错误码是20208】 + MSP_ERROR_FUSION_INVALID_INPUT_TYPE = 11709, // 【输入数据类型非法,对应的引擎错误码是20300】 + MSP_ERROR_FUSION_NO_ENOUGH_DATA = 11710, // 【输入的数据不完整,对应的引擎错误码是20301】 + MSP_ERROR_FUSION_ENOUGH_DATA = 11711, // 【输入的数据过多,对应的引擎错误码是20302】 + + /*Error Codes of AIUI*/ + MSP_ERROR_AIUI_CID_EXPIRED = 11800, + + /*Error Codes of Encoder*/ + MSP_ERROR_ICT_ENCODER = 11900, + + /* Error codes of http 12000(0x2EE0) */ + MSP_ERROR_HTTP_BASE = 12000, /* 0x2EE0 */ + MSP_ERROR_HTTP_400 = 12400, + MSP_ERROR_HTTP_401 = 12401, + MSP_ERROR_HTTP_402 = 12402, + MSP_ERROR_HTTP_403 = 12403, + MSP_ERROR_HTTP_404 = 12404, + MSP_ERROR_HTTP_405 = 12405, + MSP_ERROR_HTTP_406 = 12406, + MSP_ERROR_HTTP_407 = 12407, + MSP_ERROR_HTTP_408 = 12408, + MSP_ERROR_HTTP_409 = 12409, + MSP_ERROR_HTTP_410 = 12410, + MSP_ERROR_HTTP_411 = 12411, + MSP_ERROR_HTTP_412 = 12412, + MSP_ERROR_HTTP_413 = 12413, + MSP_ERROR_HTTP_414 = 12414, + MSP_ERROR_HTTP_415 = 12415, + MSP_ERROR_HTTP_416 = 12416, + MSP_ERROR_HTTP_417 = 12417, + MSP_ERROR_HTTP_500 = 12500, + MSP_ERROR_HTTP_501 = 12501, + MSP_ERROR_HTTP_502 = 12502, + MSP_ERROR_HTTP_503 = 12503, + MSP_ERROR_HTTP_504 = 12504, + MSP_ERROR_HTTP_505 = 12505, + /*Error codes of ISV */ + MSP_ERROR_ISV_NO_USER = 13000, /* 32C8 */ /* the user doesn't exist */ + + /* Error codes of Lua scripts */ + MSP_ERROR_LUA_BASE = 14000, /* 0x36B0 */ + MSP_ERROR_LUA_YIELD = 14001, /* 0x36B1 */ + MSP_ERROR_LUA_ERRRUN = 14002, /* 0x36B2 */ + MSP_ERROR_LUA_ERRSYNTAX = 14003, /* 0x36B3 */ + MSP_ERROR_LUA_ERRMEM = 14004, /* 0x36B4 */ + MSP_ERROR_LUA_ERRERR = 14005, /* 0x36B5 */ + MSP_ERROR_LUA_INVALID_PARAM = 14006, /* 0x36B6 */ + + /* Error codes of MMP */ + MSP_ERROR_MMP_BASE = 15000, /* 0x3A98 */ + MSP_ERROR_MMP_MYSQL_INITFAIL = 15001, /* 0x3A99 */ + MSP_ERROR_MMP_REDIS_INITFAIL = 15002, /* 0x3A9A */ + MSP_ERROR_MMP_NETDSS_INITFAIL = 15003, /* 0x3A9B */ + MSP_ERROR_MMP_TAIR_INITFAIL = 15004, /* 0x3A9C */ + MSP_ERROR_MMP_MAIL_SESSION_FAIL = 15006, /* 0x3A9E */ /* 邮件登陆服务器时,会话错误。*/ + MSP_ERROR_MMP_MAIL_LOGON_FAIL = 15007, /* 0x3A9F */ /* 邮件登陆服务器时,拒绝登陆。*/ + MSP_ERROR_MMP_MAIL_USER_ILLEGAL = 15008, /* 0x3AA0 */ /* 邮件登陆服务器时,用户名非法。*/ + MSP_ERROR_MMP_MAIL_PWD_ERR = 15009, /* 0x3AA1 */ /* 邮件登陆服务器时,密码错误。*/ + MSP_ERROR_MMP_MAIL_SOCKET_ERR = 15010, /* 0x3AA2 */ /* 邮件发送过程中套接字错误*/ + MSP_ERROR_MMP_MAIL_INIT_FAIL = 15011, /* 0x3AA3 */ /* 邮件初始化错误*/ + MSP_ERROR_MMP_STORE_MNR_NO_INIT = 15012, /* 0x3AA4 */ /* store_manager未初始化,或初始化失败*/ + MSP_ERROR_MMP_STORE_MNR_POOL_FULL = 15013, /* 0x3AA5 */ /* store_manager的连接池满了*/ + MSP_ERROR_MMP_STRATGY_PARAM_ILLEGAL = 15014, /* 0x3AA6 */ /* 报警策略表达式非法*/ + MSP_ERROR_MMP_STRATGY_PARAM_TOOLOOG = 15015, /* 0x3AA7 */ /* 报警策略表达式太长*/ + MSP_ERROR_MMP_PARAM_NULL = 15016, /* 0x3AA8 */ /* 函数参数为空*/ + MSP_ERROR_MMP_ERR_MORE_TOTAL = 15017, /* 0x3AA9 */ /* pms插入数据库中错误汇总表的数据,错误次数 > 总次数。*/ + MSP_ERROR_MMP_PROC_THRESHOLD = 15018, /* 0x3AAA */ /* 进程监控阀值设置错误*/ + MSP_ERROR_MMP_SERVER_THRESHOLD = 15019, /* 0x3AAB */ /* 服务器监控阀值设置错误*/ + MSP_ERROR_MMP_PYTHON_NO_EXIST = 15020, /* 0x3AAC */ /* python脚本文件不存在 */ + MSP_ERROR_MMP_PYTHON_IMPORT_FAILED = 15021, /* 0x3AAD */ /* python脚本导入出错 */ + MSP_ERROR_MMP_PYTHON_BAD_FUNC = 15022, /* 0x3AAE */ /* python脚本函数格式错误 */ + MSP_ERROR_MMP_DB_DATA_ILLEGAL = 15023, /* 0x3AAF */ /* 插入数据库中的数据格式有误 */ + MSP_ERROR_MMP_REDIS_NOT_CONN = 15024, /* 0x3AB0 */ /* redis没有连接到服务端 */ + MSP_ERROR_MMP_PMA_NOT_FOUND_STRATEGY = 15025, /* 0x3AB1 */ /* 没有找到报警策略 */ + MSP_ERROR_MMP_TAIR_CONNECT = 15026, /* 0x3AB2 */ /* 连接tair集群失败 */ + MSP_ERROR_MMP_PMC_SERVINFO_INVALID = 15027, /* Ox3AB3 */ /* 此pmc的服务器信息已经无效 */ + MSP_ERROR_MMP_ALARM_GROUP_NULL = 15028, /* Ox3AB4 */ /* 服务器报警的短信报警组与邮件报警组均为空 */ + MSP_ERROR_MMP_ALARM_CONTXT_NULL = 15029, /* Ox3AB5 */ /* 服务器报警的报警内容为空 */ + + /* Error codes of MSC(lmod loader) */ + MSP_ERROR_LMOD_BASE = 16000, /* 0x3E80 */ + MSP_ERROR_LMOD_NOT_FOUND = 16001, /* 0x3E81 */ /* 没找到lmod文件 */ + MSP_ERROR_LMOD_UNEXPECTED_BIN = 16002, /* 0x3E82 */ /* 无效的lmod */ + MSP_ERROR_LMOD_LOADCODE = 16003, /* 0x3E83 */ /* 加载lmod指令失败 */ + MSP_ERROR_LMOD_PRECALL = 16004, /* 0x3E84 */ /* 初始化lmod失败 */ + MSP_ERROR_LMOD_RUNTIME_EXCEPTION = 16005, /* 0x3E85 */ /* lmod运行时异常 */ + MSP_ERROR_LMOD_ALREADY_LOADED = 16006, /* 0x3E86 */ /* lmod重复加载 */ + + // Error code of Third Business + MSP_ERROR_BIZ_BASE = 17000, /* 0x4268 */ /* 三方业务错误码 */ + + //Error of Nginx errlog file increase exception + MSP_ERROR_NGX_LOG_MORE_TOTEL_SIZE = 18000, /*nginx错误日志大小异常*/ + + //Error of Flash client when network checking + MSP_ERROR_FLASH_NETWORK_CONNECT_FIALED = 19000, /*flash服务端网络连接失败*/ + MSP_ERROR_FLASH_NETWORK_CHECK_FIALED = 19001, /*flash服务端响应了异常消息*/ + MSP_ERROR_FLASH_NETWORK_CHECK_TIMEOUT = 19002, /*flash服务端网络超时*/ + MSP_ERROR_FLASH_NETWORK_CLOSED_EXCEPTION = 19003, /*flash服务端网络异常关闭*/ + + /*Error Code Of Speech plus*/ + + SPEECH_ERROR_NO_NETWORK = 20001, /* 无有效的网络连接*/ + SPEECH_ERROR_NETWORK_TIMEOUT = 20002, /* 网络连接超时*/ + SPEECH_ERROR_NET_EXPECTION = 20003, /* 网络异常*/ + SPEECH_ERROR_INVALID_RESULT = 20004, /* 无有效的结果*/ + SPEECH_ERROR_NO_MATCH = 20005, /* 无匹配结果 */ + SPEECH_ERROR_AUDIO_RECORD = 20006, /* 录音失败 */ + SPEECH_ERROR_NO_SPPECH = 20007, /* 未检测到语音*/ + + SPEECH_ERROR_SPEECH_TIMEOUT = 20008, /* 音频输入超时*/ + SPEECH_ERROR_EMPTY_UTTERANCE = 20009, /* 无效的文本输入 */ + SPEECH_ERROR_FILE_ACCESS = 20010, /* 文件读写失败 */ + SPEECH_ERROR_PLAY_MEDIA = 20011, /* 音频播放失败 */ + + SPEECH_ERROR_INVALID_PARAM = 20012, /* 无效的参数*/ + SPEECH_ERROR_TEXT_OVERFLOW = 20013, /* 文本溢出 */ + SPEECH_ERROR_INVALID_DATA = 20014, /* 无效数据 */ + SPEECH_ERROR_LOGIN = 20015, /* 用户未登陆*/ + SPEECH_ERROR_PERMISSION_DENIED = 20016, /* 无效授权 */ + SPEECH_ERROR_INTERRUPT = 20017, /* 被异常打断 */ + + SPEECH_ERROR_VERSION_LOWER = 20018, /* 版本过低 */ + SPEECH_CLIENT_ERROR_ISUSING = 20019, /* 录音机被占用(iOS平台) */ + SPEECH_ERROR_SYSTEM_PREINSTALL = 20020, /* 系统预置版本 */ + SPEECH_ERROR_UNSATISFIED_LINK = 20021, /* 未实现的Native函数引用 */ + SPEECH_ERROR_UNKNOWN = 20999, /* 未知错误 */ + + + SPEECH_ERROR_COMPONENT_NOT_INSTALLED = 21001, /* 没有安装语音组件 */ + SPEECH_ERROR_ENGINE_NOT_SUPPORTED = 21002, /* 引擎不支持 */ + SPEECH_ERROR_ENGINE_INIT_FAIL = 21003, /* 初始化失败 */ + SPEECH_ERROR_ENGINE_CALL_FAIL = 21004, /* 调用失败 */ + SPEECH_ERROR_ENGINE_BUSY = 21005, /* 引擎繁忙 */ + + SPEECH_ERROR_LOCAL_NO_INIT = 22001, /* 本地引擎未初始化 */ + SPEECH_ERROR_LOCAL_RESOURCE = 22002, /* 本地引擎无资源 */ + SPEECH_ERROR_LOCAL_ENGINE = 22003, /* 本地引擎内部错误 */ + SPEECH_ERROR_IVW_INTERRUPT = 22004, /* 本地唤醒引擎被异常打断 */ + + + /*Error Code Of Local iflytek Engines*/ + + /*Error Code Of AiTalk*/ + + /*Error Code Of AiTalk Operation*/ + SPEECH_SUCCESS = 0, // ivErr_OK = 0 /*成功状态*/ + + SPEECH_ERROR_ASR_CLIENT = 23000, /*客户端应用程序错误*///????????? + SPEECH_ERROR_ASR_INVALID_PARA = 23001, /*无效的参数*/ + SPEECH_ERROR_ASR_INVALID_PARA_VALUE = 23002, /*无效的参数值*/ + SPEECH_ERROR_ASR_OUT_OF_MEMORY = 23003, /*内存耗尽*/ + SPEECH_ERROR_ASR_CREATE_HANDLE_FAILED = 23004, /*创建句柄失败*/ + SPEECH_ERROR_ASR_ENGINE_INIT_FAILED = 23005, /*引擎初始化失败*/ + SPEECH_ERROR_ASR_ENGINE_STARTED = 23006, /*引擎已经启动*/ + SPEECH_ERROR_ASR_ENGINE_UNINIT = 23007, /*引擎未初始化*/ + SPEECH_ERROR_ASR_SPEECH_TIMEOUT = 23008, /*识别超时(VAD没开启或没有检测到后端点)*/ + SPEECH_ERROR_ASR_NO_RECOGNIZED_RESULT = 23009, /*无识别结果*/ + SPEECH_ERROR_ASR_INVALID_HANDLE = 23010, /*无效的句柄*/ + SPEECH_ERROR_ASR_FILE_ACCESS = 23011, /*打开文件失败*/ + + /*Error Code Of AiTalk Engine*/ + SPEECH_ERROR_AITALK_FALSE = 23100, // ivErr_FALSE = 1 + + /* For license check */ + SPEECH_ERROR_AITALK_PERMISSION_DENIED = 23101, // ivErr_InvSN = 2 + + /* General */ + SPEECH_ERROR_AITALK_INVALID_PARA = 23102, // ivErr_InvArg = 3 + SPEECH_ERROR_AITALK_BUFFER_OVERFLOW = 23103, // ivErr_BufferFull = 4 /*音频数据缓冲区已满*/ + SPEECH_ERROR_AITALK_FAILED = 23104, // ivErr_Failed = 5 + SPEECH_ERROR_AITALK_NOT_SUPPORTED = 23105, // ivErr_NotSupport = 6 /*引擎不支持*/ + SPEECH_ERROR_AITALK_OUT_OF_MEMORY = 23106, // ivErr_OutOfMemory = 7 + SPEECH_ERROR_AITALK_INVALID_RESOURCE = 23107, // ivErr_InvResource = 8 /*资源无效*/ + SPEECH_ERROR_AITALK_NOT_FOUND = 23108, // ivErr_NotFound = 9 /*打开文件失败*/ + SPEECH_ERROR_AITALK_INVALID_GRAMMAR = 23109, // ivErr_InvGrmr = 10 /*识别语法错误*/ + + /* For object status */ + SPEECH_ERROR_AITALK_INVALID_CALL = 23110, // ivErr_InvCall = 11 /*无效调用*/ + + /* For ASR Input */ + SPEECH_ERROR_AITALK_SYNTAX_ERROR = 23111, // ivErr_InvCall = 12 + + /* For Message Call Back */ + SPEECH_ERROR_AITALK_RESET = 23112, // ivErr_Reset = 13 + SPEECH_ERROR_AITALK_ENDED = 23113, // ivErr_Ended = 14 + SPEECH_ERROR_AITALK_IDLE = 23114, // ivErr_Idle = 15 + SPEECH_ERROR_AITALK_CANNOT_SAVE_FILE = 23115, // ivErr_CanNotSaveFile = 16 + + /* For Lexicon name */ + SPEECH_ERROR_AITALK_INVALID_GRAMMAR_NAME = 23116, // ivErr_InvName = 17 /*文法或词典名称非法*/ + + SPEECH_ERROR_AITALK_BUFFER_EMPTY = 23117, // ivErr_BufferEmpty = 18 + + SPEECH_ERROR_AITALK_GET_RESULT = 23118, // ivErr_GetResult = 19 + + SPEECH_ERROR_AITALK_REACT_OUT_TIME = 23119, // ivErr_ReactOutTime = 20 /*反应超时*/ + SPEECH_ERROR_AITALK_SPEECH_OUT_TIME = 23120, // ivErr_SpeechOutTime = 21 /*语音超时*/ + + SPEECH_ERROR_AITALK_AUDIO_CUT = 23121, // ivErr_CUT = 22 /*录音质量过高*/ + SPEECH_ERROR_AITALK_AUDIO_LOWER = 23122, // ivErr_LOWER = 23 /*录音质量过低*/ + + SPEECH_ERROR_AITALK_INSUFFICIENT_PERMISSIONS = 23123, // ivErr_Limitted = 24 /*授权不够*/ + SPEECH_ERROR_AITALK_RESULT_ERROR = 23124, // ivErr_ResultError = 25 /*解码器Wfst输出后,依然有cmd输出*/ + SPEECH_ERROR_AITALK_SHORT_PAUSE = 23125, // ivErr_ShortPause = 26 + SPEECH_ERROR_AITALK_BUSY = 23126, // ivErr_Busy = 27 + SPEECH_ERROR_AITALK_GRM_NOT_UPDATE = 23127, // ivErr_GrmNotUpdate = 28 /*语法未更新*/ + SPEECH_ERROR_AITALK_STARTED = 23128, // ivErr_Started = 29 + SPEECH_ERROR_AITALK_STOPPED = 23129, // ivErr_Stopped = 30 + SPEECH_ERROR_AITALK_ALREADY_STARTED = 23130, // ivErr_AlreadyStarted = 31 + SPEECH_ERROR_AITALK_ALREADY_STOPPED = 23131, // ivErr_AlreadyStopped = 32 + SPEECH_ERROR_AITALK_TOO_MANY_COMMAND = 23132, // ivErr_TooManyCmd = 33 + SPEECH_ERROR_AITALK_WAIT = 23133, // ivErr_Wait = 34 /*程序可能在做一些操作,主线程需要等待*/ + SPEECH_ERROR_AITALK_MAE_RIGHT = 23134, // ivErr_MAERight = 35 + SPEECH_ERROR_AITALK_MAE_WRONG = 23135, // ivErr_MAEWrong = 36 + + SPEECH_ERROR_AITALK_GRM_ERR = 23300, // 语法错误 + + + + /*Error Code Of AiSound*/ + + /*Error Code Of AiSound Operation*/ + SPEECH_ERROR_TTS_INVALID_PARA = 24000, /* 错误参数 */ + SPEECH_ERROR_TTS_INVALID_PARA_VALUE = 24001, /* 无效的参数值*/ + SPEECH_ERROR_TTS_OUT_OF_MEMORY = 24002, /* 内存不足*/ + SPEECH_ERROR_TTS_INVALID_HANDLE = 24003, /* 无效的句柄*/ + SPEECH_ERROR_TTS_CREATE_HANDLE_FAILED = 24004, /* 创建句柄失败*/ + SPEECH_ERROR_TTS_INVALID_RESOURCE = 24005, /* 无效资源 */ + SPEECH_ERROR_TTS_INVALID_VOICE_NAME = 24006, /* 无效发言人*/ + SPEECH_ERROR_TTS_ENGINE_UNINIT = 24007, /* 引擎未初始化 */ + SPEECH_ERROR_TTS_ENGINE_INIT_FAILED = 24008, /* 引擎初始化失败 */ + SPEECH_ERROR_TTS_ENGINE_BUSY = 24009, /* 引擎忙 */ + + + /*Error Code Of AiSound Engine*/ + SPEECH_ERROR_AISOUND_BASE = 24100, + SPEECH_ERROR_AISOUND_UNIMPEMENTED = 24100, /* unimplemented function */ + SPEECH_ERROR_AISOUND_UNSUPPORTED = 24101, /* unsupported on this platform */ + SPEECH_ERROR_AISOUND_INVALID_HANDLE = 24102, /* invalid handle */ + SPEECH_ERROR_AISOUND_INVALID_PARA = 24103, /* invalid parameter(s) */ + SPEECH_ERROR_AISOUND_INSUFFICIENT_HEAP = 24104, /* insufficient heap size */ + SPEECH_ERROR_AISOUND_STATE_REFUSE = 24105, /* refuse to do in current state */ + SPEECH_ERROR_AISOUND_INVALID_PARA_ID = 24106, /* invalid parameter ID */ + SPEECH_ERROR_AISOUND_INVALID_PARA_VALUE = 24107, /* invalid parameter value */ + SPEECH_ERROR_AISOUND_RESOURCE = 24108, /* Resource is error */ + SPEECH_ERROR_AISOUND_RESOURCE_READ = 24109, /* read resource error */ + SPEECH_ERROR_AISOUND_LBENDIAN = 24110, /* the Endian of SDK is error */ + SPEECH_ERROR_AISOUND_HEADFILE = 24111, /* the HeadFile is different of the SDK */ + SPEECH_ERROR_AISOUND_BUFFER_OVERFLOW = 24112, /* get data size exceed the data buffer */ + SPEECH_ERROR_AISOUND_INVALID_ISAMPA = 24113, /* !Invalid iSampa format or input iSampa text contain invalid alphabet*/ + SPEECH_ERROR_AISOUND_INVALID_CSSML = 24114, /* !Invalid cssml format */ + + + /*Error Code Of ivw*/ + + /*Error Code Of ivw Operation*/ + SPEECH_ERROR_IVW_ENGINE_UNINI = 25000, /* 引擎未初始化 */ + SPEECH_ERROR_IVW_RESVER_NOMATCH = 25001, /* 资源版本不匹配 */ + SPEECH_ERROR_IVW_BUFFERED_AUDIOD_LITTLE = 25002, /* 唤醒加识别缓存音频过少 */ + SPEECH_ERROR_IVW_INVALID_RESTYPE = 25003, /* 不合法的资源类型 */ + SPEECH_ERROR_IVW_INVALID_RESHEADVER = 25004, /* 不合法的资源头部版本号 */ + + /*Error Code Of ivw Engine*/ + SPEECH_ERROR_IVW_INVALID_CALL = 25101, // IvwErr_InvCal = 1 + SPEECH_ERROR_IVW_INVALID_ARG = 25102, // IvwErr_InvArg = 2 + SPEECH_ERROR_IVW_TELL_SIZE = 25103, // IvwErr_TellSize = 3 + SPEECH_ERROR_IVW_OUT_OF_MEMORY = 25104, // IvwErr_OutOfMemory = 4 + SPEECH_ERROR_IVW_OUT_BUFFER_FULL = 25105, // IvwErr_BufferFull = 5 + SPEECH_ERROR_IVW_OUT_BUFFER_EMPTY = 25106, // IvwErr_BufferEmpty = 6 + SPEECH_ERROR_IVW_INVALID_RESOURCE = 25107, // IvwErr_InvRes = 7 + SPEECH_ERROR_IVW_REPETITIOPN_ENTER = 25108, // IvwErr_ReEnter = 8 + SPEECH_ERROR_IVW_NOT_SUPPORT = 25109, // IvwErr_NotSupport = 9 + SPEECH_ERROR_IVW_NOT_FOUND = 25110, // IvwErr_NotFound = 10 + SPEECH_ERROR_IVW_INVALID_SN = 25111, // IvwErr_InvSN = 11 + SPEECH_ERROR_IVW_LIMITTED = 25112, // IvwErr_Limitted = 12 + SPEECH_ERROR_IVW_TIME_OUT = 25113, // IvwErr_TimeOut = 13 + + SPEECH_ERROR_IVW_ENROLL1_SUCESS = 25114, // IvwErr_Enroll1_Success = 14 + SPEECH_ERROR_IVW_ENROLL1_FAILED = 25115, // IvwErr_Enroll1_Failed = 15 + SPEECH_ERROR_IVW_ENROLL2_SUCESS = 25116, // IvwErr_Enroll2_Success = 16 + SPEECH_ERROR_IVW_ENROLL2_FAILED = 25117, // IvwErr_Enroll2_Failed = 17 + SPEECH_ERROR_IVW_ENROLL3_SUCESS = 25118, // IvwErr_Enroll3_Success = 18 + SPEECH_ERROR_IVW_ENROLL3_FAILED = 25119, // IvwErr_Enroll3_Failed = 19 + SPEECH_ERROR_IVW_SPEECH_TOO_SHORT = 25120, // IvwErr_SpeechTooShort = 20 + SPEECH_ERROR_IVW_SPEECH_STOP = 25121, // IvwErr_SpeechStop = 21 + + /* 非实时转写错误码:26000~26999 */ + SPEECH_ERROR_LFASR_BASE = 26000, /* 非实时转写错误码基码 */ + }; +} diff --git a/Container/Common/MouseHook.cs b/Container/Common/MouseHook.cs new file mode 100644 index 0000000..cc8e6bd --- /dev/null +++ b/Container/Common/MouseHook.cs @@ -0,0 +1,89 @@ +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Linq; +using System.Runtime.InteropServices; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace Container.Common +{ + public class MouseHook + { + private Point point; + private Point Point + { + get { return point; } + set + { + if (point != value) + { + point = value; + if (MouseMoveEvent != null) + { + var e = new MouseEventArgs(MouseButtons.None, 0, point.X, point.Y, 0); + MouseMoveEvent(this, e); + } + } + } + } + private int hHook; + private const int WM_LBUTTONDOWN = 0x201; + private const int WM_RBUTTONDOWN = 0x204; + public const int WH_MOUSE_LL = 14; + public Win32Api.HookProc hProc; + public MouseHook() + { + this.Point = new Point(); + } + public int SetHook() + { + hProc = new Win32Api.HookProc(MouseHookProc); + hHook = Win32Api.SetWindowsHookEx(WH_MOUSE_LL, hProc, IntPtr.Zero, 0); + return hHook; + } + public void UnHook() + { + Win32Api.UnhookWindowsHookEx(hHook); + } + private int MouseHookProc(int nCode, IntPtr wParam, IntPtr lParam) + { + Win32Api.MouseHookStruct MyMouseHookStruct = (Win32Api.MouseHookStruct)Marshal.PtrToStructure(lParam, typeof(Win32Api.MouseHookStruct)); + if (nCode < 0) + { + return Win32Api.CallNextHookEx(hHook, nCode, wParam, lParam); + } + else + { + if (MouseClickEvent != null) + { + MouseButtons button = MouseButtons.None; + int clickCount = 0; + switch ((Int32)wParam) + { + case WM_LBUTTONDOWN: + button = MouseButtons.Left; + clickCount = 1; + break; + case WM_RBUTTONDOWN: + button = MouseButtons.Right; + clickCount = 1; + break; + } + + var e = new MouseEventArgs(button, clickCount, point.X, point.Y, 0); + MouseClickEvent(this, e); + } + this.Point = new Point(MyMouseHookStruct.pt.x, MyMouseHookStruct.pt.y); + return Win32Api.CallNextHookEx(hHook, nCode, wParam, lParam); + } + } + + public delegate void MouseMoveHandler(object sender, MouseEventArgs e); + public event MouseMoveHandler MouseMoveEvent; + + public delegate void MouseClickHandler(object sender, MouseEventArgs e); + public event MouseClickHandler MouseClickEvent; + } +} diff --git a/Container/Common/MyHttpClient.cs b/Container/Common/MyHttpClient.cs new file mode 100644 index 0000000..aef29bc --- /dev/null +++ b/Container/Common/MyHttpClient.cs @@ -0,0 +1,220 @@ +using Container.Services; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Net; +using System.Web; +using System.Windows; + +namespace Container.Common +{ + public class MyHttpClient + { + private static App app = ((App)Application.Current); + private static Class_Log Mylog = new Class_Log(); + private static void init_Request(ref HttpWebRequest request) + { + request.Accept = "text/json,*/*;q=0.5"; + request.Headers.Add("Accept-Charset", "utf-8;q=0.7,*;q=0.7"); + request.Headers.Add("Accept-Encoding", "gzip, deflate, x-gzip, identity; q=0.9"); + request.AutomaticDecompression = DecompressionMethods.GZip; + request.Timeout = 60000; + } + public static string Get(string url) + { + try + { + var request = (HttpWebRequest)WebRequest.Create(url); + { + string retval; + init_Request(ref request); + using (var response = request.GetResponse()) + { + using (var reader = new System.IO.StreamReader(response.GetResponseStream() ?? throw new InvalidOperationException(), System.Text.Encoding.UTF8)) + { + retval = reader.ReadToEnd(); + } + } + return retval; + } + } + catch + { + // ignored + } + + return null; + } + + //判断链接可用 + public static bool IsCanConnect(string url, int timeout = 1000) + { + HttpWebRequest req = null; + HttpWebResponse res = null; + bool CanCn = true; + try + { + req = (HttpWebRequest)WebRequest.Create(url); + req.Method = "HEAD"; + req.Timeout = timeout; + res = (HttpWebResponse)req.GetResponse(); + CanCn = res.StatusCode.ToString() == "OK"; + } + catch (Exception ex) + { + CanCn = false; //无法连接 + } + finally + { + if (res != null) + { + res.Close(); + } + } + return CanCn; + } + public static string Post(string url, string data, string contentType = "application/x-www-form-urlencoded; charset=utf-8", Dictionary headers = null) + { + try + { + var request = (HttpWebRequest)WebRequest.Create(url); + { + string retval; + init_Request(ref request); + request.Method = "POST"; + //request.Timeout = 5000; + request.ContentType = contentType; + if (headers != null && headers.Count > 0) + { + foreach (var h in headers) + { + request.Headers.Add(h.Key, h.Value); + } + } + var bytes = System.Text.Encoding.UTF8.GetBytes(data); + request.ContentLength = bytes.Length; + using (var stream = request.GetRequestStream()) + { + stream.Write(bytes, 0, bytes.Length); + } + using (var response = request.GetResponse()) + { + using (var reader = new System.IO.StreamReader(response.GetResponseStream() ?? throw new InvalidOperationException())) + { + retval = reader.ReadToEnd(); + + } + if (!app.isCheckServerTime) + { + Class_Log log = new Class_Log(); + string[] dates = response.Headers.GetValues("Date"); + if (dates.Length > 0) + { + app.isCheckServerTime = true; + string serverTime = GMT2Local(dates[0]).ToString(); + log.WriteLogFile(serverTime, "date"); + WebSocketManageForLive.SetLocalTimeByStr(serverTime); + } + } + } + + return retval; + } + } + catch (WebException ex) + { + var lo = ex.Response.Headers["Location"]; + if (!string.IsNullOrEmpty(lo)) + return lo; + return "request error:" + ex.Message; + } + + } + + /// + /// GMT时间转成本地时间 + /// + /// 字符串形式的GMT时间 + /// + public static DateTime GMT2Local(string gmt) + { + DateTime dt = DateTime.MinValue; + try + { + string pattern = ""; + if (gmt.IndexOf("+0") != -1) + { + gmt = gmt.Replace("GMT", ""); + pattern = "ddd, dd MMM yyyy HH':'mm':'ss zzz"; + } + if (gmt.ToUpper().IndexOf("GMT") != -1) + { + pattern = "ddd, dd MMM yyyy HH':'mm':'ss 'GMT'"; + } + if (pattern != "") + { + dt = DateTime.ParseExact(gmt, pattern, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.AdjustToUniversal); + dt = dt.ToLocalTime(); + } + else + { + dt = Convert.ToDateTime(gmt); + } + } + catch (Exception ex) + { + Class_Log log = new Class_Log(); + log.WriteLogFile(ex.ToString(), "Temp113"); + } + return dt; + } + + + /// + /// 请求云端方法,带加解密 + /// + /// + /// + /// + public static string CryptPost(string method, object data, string httpurl = "") + { + string _result = string.Empty; + if (!app.IsCanConnect) + { + return _result; + } + try + { + var timeStamp = CommonLib.CurrentTime(); + if (string.IsNullOrEmpty(httpurl)) + { + httpurl = app.HttpUrl; + } + var token = SecurityHelper.AesEncrypt(method + timeStamp); + string postUrl = string.Concat(httpurl, method, "?token=", HttpUtility.UrlEncode(token), "&time=", timeStamp); + string contentType = "application/json; charset=utf-8"; + string body = SecurityHelper.AesEncrypt(JsonConvert.SerializeObject(data)); + _result = Post(postUrl, body, contentType); + _result = SecurityHelper.AesDecrypt(_result); + //var Jo = JObject.Parse(res); + //string code = Jo.Value("code"); + //if (code == ResultCode.Success) + //{ + // _result.Code = code; + // _result.Msg = Jo.Value("msg"); + // _result.Data = Jo.Value("data").ToObject(); + //} + //else + //{ + // _result.Code = code; + // _result.Msg = Jo.Value("msg"); + //} + } + catch (Exception ex) + { + Mylog.WriteLogFile("请求错误" + ex.ToString(), "MyHttpClientError"); + } + return _result; + } + } +} diff --git a/Container/Common/Recorder.cs b/Container/Common/Recorder.cs new file mode 100644 index 0000000..75e78b4 --- /dev/null +++ b/Container/Common/Recorder.cs @@ -0,0 +1,326 @@ +using NAudio.Wave; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.InteropServices; +using System.Text; +using System.Threading; +using System.Threading.Tasks; + +namespace Container.Common +{ + public class Recorder + { + Class_Log _log = new Class_Log(); + private int deviceNumber = 0; // 选择的录音设备下标。多个设备时可设置为用户选择 + private WaveIn waveIn; // waveIn操作类 + private WaveFormat recordingFormat; // 录音格式 + private WaveFileWriter writer; // 录音文件操作类 + public event EventHandler StoppedEvent = delegate { }; // 录音结束事件 + public event EventHandler DataAvailableEvent = delegate { }; // 录音过程中接收到数据事件 + //private RichTextBox textbox; // waveIn操作类 + private byte[] wavdata; + private int aud_stat = AudioStatus.MSP_AUDIO_SAMPLE_FIRST;//音频状态 + + StringBuilder result = new StringBuilder();//存储最终识别的结果 + int totalLength = 0;//用来记录总的识别后的结果的长度,判断是否超过缓存最大值 + private int ep_stat = EpStatus.MSP_EP_LOOKING_FOR_SPEECH;//端点状态 + private int rec_stat = RecogStatus.MSP_REC_STATUS_SUCCESS;//识别状态 + int errcode = (int)Errors.MSP_SUCCESS; + public double RecordedTime // 获取到录音的时长 + { + get + { + if (writer == null) + return 0; + return (double)writer.Length / writer.WaveFormat.AverageBytesPerSecond; + } + } + //public Recorder(RichTextBox box) + //{ + // textbox = box; + + //} + /// + /// 开始录音 + /// + /// 保存的文件名 + internal bool StartRecorder(string filename = "r.wav") + { + // 设置录音格式WaveFormat(16000, 16, 1); + //recordingFormat = new WaveFormat(16000, 8, WaveIn.GetCapabilities(deviceNumber).Channels); + recordingFormat = new WaveFormat(16000, 16, 1); + // 设置麦克风操作对象 + waveIn = new WaveIn(); + waveIn.DeviceNumber = deviceNumber; // 设置使用的录音设备 + waveIn.DataAvailable += OnDataAviailable; // 接收到音频数据时,写入文件 + waveIn.RecordingStopped += OnRecordingStopped; // 录音结束时执行 + waveIn.WaveFormat = recordingFormat; + // 设置文件操作类 + writer = new WaveFileWriter(filename, recordingFormat); + // 开始录音 + waveIn.StartRecording(); + int errcode = (int)Errors.MSP_SUCCESS; + string session_begin_params = "sub=iat,domain=iat,language=zh_cn,accent=mandarin,sample_rate=16000,result_type=plain,result_encoding=gb2312"; + IatNativeMethods.session_id = IatNativeMethods.QISRSessionBegin(null, session_begin_params, ref errcode); + if (errcode != (int)Errors.MSP_SUCCESS) + _log.WriteLogFile("开始一次语音识别失败!"); + //Thread t = new Thread(run_iat); + //t.Start(); + return true; + } + + private void run_iat(byte[] _wavdata) + { + wavdata = _wavdata; + if (wavdata == null || wavdata.Length == 0) + { + try + { + wavdata = System.IO.File.ReadAllBytes("wav/test.wav"); + } + catch (Exception e) + { + //System.Diagnostics.Debug.WriteLine(e.Message); + //wavdata = null; + } + } + //wavdata = System.IO.File.ReadAllBytes("wav/r.wav"); + + int res = IatNativeMethods.QISRAudioWrite(IatNativeMethods.session_id, wavdata, (uint)wavdata.Length, aud_stat, ref ep_stat, ref rec_stat); + if (res != (int)Errors.MSP_SUCCESS) + { + _log.WriteLogFile("写入识别的音频失败!" + res); + //this.textbox.Dispatcher.Invoke(new Action(delegate + //{ + // textbox.AppendText("写入识别的音频失败!" + res + "\r\n"); + //})); + return; + } + if (RecogStatus.MSP_REC_STATUS_SUCCESS != rec_stat) + { + IntPtr now_result = IatNativeMethods.QISRGetResult(IatNativeMethods.session_id, ref rec_stat, 0, ref errcode); + if (errcode != (int)Errors.MSP_SUCCESS) + { + _log.WriteLogFile("获取结果失败:" + errcode); + //this.textbox.Dispatcher.Invoke(new Action(delegate + //{ + // textbox.AppendText("获取结果失败:" + errcode + "\r\n"); + //})); + return; + } + if (now_result != null) + { + int length = now_result.ToString().Length; + totalLength += length; + if (totalLength > 4096) + { + _log.WriteLogFile("缓存空间不够" + totalLength); + //this.textbox.Dispatcher.Invoke(new Action(delegate + //{ + // textbox.AppendText("缓存空间不够:" + totalLength + "\r\n"); + //})); + } + //result.Append(Marshal.PtrToStringAnsi(now_result)); + } + } + //if (result.Length > 0) + //{ + // //_log.WriteLogFile("中间识别语音:" + result.ToString()); + // this.textbox.Dispatcher.Invoke(new Action( + // delegate + // { + // textbox.AppendText("中间识别语音:" + result.ToString() + "\r\n"); + // } + // ) + // ); + //} + if (EpStatus.MSP_EP_AFTER_SPEECH == ep_stat) + { + //run_iatlast(); + StopRecorder(); + + return; + } + //Thread.Sleep(150);//防止频繁占用cpu + } + + private void run_iatlast() + { + + var res = IatNativeMethods.QISRAudioWrite(IatNativeMethods.session_id, null, 0, AudioStatus.MSP_AUDIO_SAMPLE_LAST, ref ep_stat, ref rec_stat); + if (res != (int)Errors.MSP_SUCCESS) + _log.WriteLogFile("写入音频失败!" + res); + while (RecogStatus.MSP_REC_STATUS_COMPLETE != rec_stat) + { + IntPtr now_result = IatNativeMethods.QISRGetResult(IatNativeMethods.session_id, ref rec_stat, 0, ref errcode); + if (errcode != (int)Errors.MSP_SUCCESS) + { + _log.WriteLogFile("获取结果失败:" + errcode); + return; + } + if (now_result != null) + { + int length = now_result.ToString().Length; + totalLength += length; + if (totalLength > 4096) + _log.WriteLogFile("缓存空间不够" + totalLength); + result.Append(Marshal.PtrToStringAnsi(now_result)); + } + Thread.Sleep(150);//防止频繁占用cpu + } + int ret = IatNativeMethods.QISRSessionEnd(IatNativeMethods.session_id, "normal end"); + if (errcode != (int)Errors.MSP_SUCCESS) + { + _log.WriteLogFile("QISRSessionEnd failed, error code is: %d" + ret); + } + if (result.Length > 0) + { + _log.WriteLogFile("识别语音:" + result.ToString()); + //this.textbox.Dispatcher.Invoke(new Action( + // delegate + // { + // textbox.AppendText("识别语音:" + result.ToString() + "\r\n"); + // textbox.ScrollToEnd(); + // } + // ) + //); + } + } + /// + /// 结束录音 + /// + /// + internal bool StopRecorder() + { + waveIn.StopRecording(); + return true; + } + + /// + /// 录音结束回调函数 + /// + /// + /// + private void OnRecordingStopped(object sender, StoppedEventArgs e) + { + // this.textbox.Dispatcher.Invoke(new Action( + // delegate + // { + // textbox.AppendText("结束录音\r\n"); + // } + // ) + //); + writer.Dispose(); + run_iatlast(); + // 通知结束事件 + StoppedEvent(this, EventArgs.Empty); + } + + /// + /// 录音回调函数,写入数据 + /// + /// + /// + private void OnDataAviailable(object sender, WaveInEventArgs e) + { + + byte[] buffer = e.Buffer; + int bytesRecorded = e.BytesRecorded; + //wavdata = e.Buffer; + long maxFileLength = this.recordingFormat.AverageBytesPerSecond * 60; + var toWrite = (int)Math.Min(maxFileLength - writer.Length, bytesRecorded); + //textbox.AppendText("e.BytesRecorded" + e.BytesRecorded); + //textbox.ScrollToEnd(); + if (toWrite > 0) + { + //textbox.AppendText(totalLength + "run_iat" + e.BytesRecorded + "\r\n"); + //textbox.ScrollToEnd(); + writer.Write(buffer, 0, bytesRecorded); + run_iat(buffer); + aud_stat = AudioStatus.MSP_AUDIO_SAMPLE_CONTINUE; + } + //string audio_path = "wav/test.wav"; + //string session_begin = "sub=iat,domain=iat,language=zh_cn,accent=mandarin,sample_rate=16000,result_type=plain,result_encoding=gb2312"; + //string ret = IatNativeMethods.localaudio_iat(audio_path); + //this.textbox.Dispatcher.Invoke(new Action( + // delegate + // { + // textbox.AppendText("ret" + ret); + // } + // ) + // ); + //WriteToFile(buffer, bytesRecorded); // 音频数据写入文件 + DataAvailableEvent(this, EventArgs.Empty); + } + + /// + /// 写入文件 + /// + /// + /// + private void WriteToFile(byte[] buffer, int bytesRecorded) + { + long maxFileLength = this.recordingFormat.AverageBytesPerSecond * 60; + + var toWrite = (int)Math.Min(maxFileLength - writer.Length, bytesRecorded); + if (toWrite > 0) + { + writer.Write(buffer, 0, bytesRecorded); + } + else + { + StopRecorder(); + } + } + + private void wis_DataAvailable(object sender, WaveInEventArgs e) + { + System.Console.WriteLine(System.DateTime.Now + ":" + System.DateTime.Now.Millisecond); + + int ret = 0; + IntPtr bp = Marshal.AllocHGlobal(e.BytesRecorded); + int status = AudioStatus.MSP_AUDIO_SAMPLE_CONTINUE; + int ep_status = EpStatus.MSP_EP_LOOKING_FOR_SPEECH; + int rec_status = RecogStatus.MSP_REC_STATUS_SUCCESS; + int rslt_status = RecogStatus.MSP_REC_STATUS_SUCCESS; + int errcode = (int)Errors.MSP_SUCCESS; + int totalLength = 0;//用来记录总的识别后的结果的长度,判断是否超过缓存最大值 + StringBuilder result = new StringBuilder();//存储最终识别的结果 + + ///ep_status 端点检测(End-point detected)器所处的状态 + ///rec_status 识别器所处的状态 + ///rslt_status 识别器所处的状态 + Marshal.Copy(e.Buffer, 0, bp, e.BytesRecorded); + ///开始向服务器发送音频数据 + ret = IatNativeMethods.QISRAudioWrite(IatNativeMethods.session_id, bp, (uint)e.BytesRecorded, status, ref ep_status, ref rec_status); + if (ret != 0) throw new Exception("QISRAudioWrite err,errCode=" + ((Errors)ret).ToString("G")); + + ///服务器返回部分结果 + if (rec_status == RecogStatus.MSP_REC_STATUS_SUCCESS) + { + IntPtr now_result = IatNativeMethods.QISRGetResult(IatNativeMethods.session_id, ref rec_status, 0, ref errcode); + if (errcode != (int)Errors.MSP_SUCCESS) + { + _log.WriteLogFile("获取结果失败:" + errcode); + return; + } + if (now_result != null) + { + int length = now_result.ToString().Length; + totalLength += length; + if (totalLength > 4096) + { + _log.WriteLogFile("缓存空间不够" + totalLength); + return; + } + result.Append(Marshal.PtrToStringAnsi(now_result)); + } + Thread.Sleep(150);//防止频繁占用cpu + } + System.Threading.Thread.Sleep(500); + Marshal.FreeHGlobal(bp); + //System.Console.WriteLine(System.DateTime.Now + ":" + System.DateTime.Now.Millisecond); + } + } +} diff --git a/Container/Common/SecurityHelper.cs b/Container/Common/SecurityHelper.cs new file mode 100644 index 0000000..94b5553 --- /dev/null +++ b/Container/Common/SecurityHelper.cs @@ -0,0 +1,95 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Security.Cryptography; +using System.Text; +using System.Threading.Tasks; + +namespace Container.Common +{ + /// + /// 加密解密类 + /// + public class SecurityHelper + { + #region AES加密解密 + private static App app = ((App)System.Windows.Application.Current); + /// + /// 128位处理key + /// + /// 原字节 + /// 处理key + /// + private static byte[] GetAesKey(byte[] keyArray, string key) + { + byte[] newArray = new byte[16]; + if (keyArray.Length < 16) + { + for (int i = 0; i < newArray.Length; i++) + { + if (i >= keyArray.Length) + { + newArray[i] = 0; + } + else + { + newArray[i] = keyArray[i]; + } + } + } + else + newArray = keyArray; + + return newArray; + } + /// + /// 使用AES加密字符串,按128位处理key + /// + /// 加密内容 + /// 秘钥,需要128位、256位..... + /// Base64字符串结果 + public static string AesEncrypt(string content, bool autoHandle = true) + { + byte[] keyArray = Encoding.UTF8.GetBytes(app.SecurityKey); + if (autoHandle) + { + keyArray = GetAesKey(keyArray, app.SecurityKey); + } + byte[] toEncryptArray = Encoding.UTF8.GetBytes(content); + + SymmetricAlgorithm des = Aes.Create(); + des.Key = keyArray; + des.Mode = CipherMode.ECB; + des.Padding = PaddingMode.PKCS7; + ICryptoTransform cTransform = des.CreateEncryptor(); + byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length); + return Convert.ToBase64String(resultArray); + } + /// + /// 使用AES解密字符串,按128位处理key + /// + /// 内容 + /// 秘钥,需要128位、256位..... + /// UTF8解密结果 + public static string AesDecrypt(string content, bool autoHandle = true) + { + byte[] keyArray = Encoding.UTF8.GetBytes(app.SecurityKey); + if (autoHandle) + { + keyArray = GetAesKey(keyArray, app.SecurityKey); + } + byte[] toEncryptArray = Convert.FromBase64String(content); + + SymmetricAlgorithm des = Aes.Create(); + des.Key = keyArray; + des.Mode = CipherMode.ECB; + des.Padding = PaddingMode.PKCS7; + + ICryptoTransform cTransform = des.CreateDecryptor(); + byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length); + + return Encoding.UTF8.GetString(resultArray); + } + #endregion + } +} diff --git a/Container/Common/TypeImg.cs b/Container/Common/TypeImg.cs new file mode 100644 index 0000000..02ee68e --- /dev/null +++ b/Container/Common/TypeImg.cs @@ -0,0 +1,27 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Container.Common +{ + /// + /// 判断文件类型是不是图片 + /// + internal sealed class TypeImg : IJudgeFileType + { + public static readonly List ImgTypes = new List { + //"bmp", "png", "gif", "jpg", "jpeg", "tfs", "psd", "tif" + "bmp", "png", "jpg", "jpeg" + }; + public bool JudgeFileType(string ext) + { + if (ImgTypes.Contains(ext.ToLower())) + { + return true; + } + return false; + } + } +} diff --git a/Container/Common/TypeVideo.cs b/Container/Common/TypeVideo.cs new file mode 100644 index 0000000..1e1a6f6 --- /dev/null +++ b/Container/Common/TypeVideo.cs @@ -0,0 +1,34 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Container.Common +{ + /// + /// 判断文件类型是不是视频 + /// + internal sealed class TypeVideo : IJudgeFileType + { + public static readonly List VideoTypes = new List { + "mp4", + "wmv", "asf", "asx",//微软视频 :wmv、asf、asx + "rm", "rmvb",//Real Player :rm、 rmvb + "mpg","mpeg","mpe",//MPEG视频 :mpg、mpeg、mpe + "3gp",//手机视频 :3gp + "mov",//Apple视频 :mov + "mp4", "m4v",//Sony视频 :mp4、m4v + "avi", "dat", "mkv", "flv", "vob" , "wvx", "mpa", //其他常见视频:avi、dat、mkv、flv、vob、wvx、mpa + "m4k","webm","ogv","f4v","swf" + }; + public bool JudgeFileType(string ext) + { + if (VideoTypes.Contains(ext.ToLower())) + { + return true; + } + return false; + } + } +} diff --git a/Container/Common/VlcPlayer.cs b/Container/Common/VlcPlayer.cs new file mode 100644 index 0000000..8c00979 --- /dev/null +++ b/Container/Common/VlcPlayer.cs @@ -0,0 +1,335 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.InteropServices; +using System.Security; +using System.Text; +using System.Threading; +using System.Threading.Tasks; + +namespace Container.Common +{ + class VlcPlayer + { + private IntPtr libvlc_instance_; + private IntPtr libvlc_media_player_; + + private double duration_; + public VlcPlayer(string pluginPath, bool isTransform) + { + /* + * --avcodec-hurry-up, --no-avcodec-hurry-up + 紧急 (默认启用) + 解码器在时间不充足的情况下可能部分解码器或跳过帧。在 CPU 不是很强大时这非常有用,但是可能会破坏图像。 (默认启用) + * --sout-avcodec-rc-buffer-size=<整数 [-2147483648 .. 2147483647]> + 速率控制缓存大小 + 速率控制缓存大小 (以千字节为单位)。一个较大的缓存将会有较佳的帧率控制,但是可能会导致流的延迟。 + * --avcodec-fast, --no-avcodec-fast + 允许非正常速度优化 (默认关闭) + 允许不符合标准的速度优化。更快但可能会出错。 (默认关闭) + --avcodec-skiploopfilter={0 (无), 1 (非参考), 2 (双向), 3 (非关键), 4 (全部)} + 用于 H.264 解码的跳过循环滤镜 + 跳过循环滤镜 (又作去块) 通常对图像质量会造成不良的效果。但是它能为高分辨率的流提供一个很大的提速。 + * --avcodec-codec=<字串> 编解码器名称 + libavcodec 内部编解码器名称 + --avcodec-hw=<字串> 硬件解码 + 这将允许硬件解码(当硬件解码可用时)。 + * --drop-late-frames, --no-drop-late-frames + 丢弃延迟的帧 (默认启用) + 这将丢弃延迟的帧 (在它们实际应该显示的时间后到达视频输出)。 (默认启用) + --skip-frames, --no-skip-frames + 跳帧 (默认启用) + 在 MPEG2 串流上启用帧丢弃。帧丢弃在您的计算机性能不够强大时发生 (默认启用) + */ + string plugin_arg = "--plugin-path=" + pluginPath; + string[] arguments = { plugin_arg, "--network-caching=<300", ":sout=#transcode{vcodec=h264,acodec=mpga,ab=128,channels=2,samplerate=44100" }; + //string[] arguments = { plugin_arg, "--network-caching=<300", ":sout=#transcode{vcodec=h264,acodec=mpga,ab=128,channels=2,samplerate=44100" }; + string[] argumentTransform = { "-I", "dummy", "--ignore-config", "--video-title", plugin_arg, "--avcodec-skiploopfilter=4", "--avcodec-fast", "--network-caching<=1800", "pe=270", ":sout=#transcode{vcodec=h264,acodec=mpga,ab=128,channels=2,samplerate=44100" }; + //sring[] arguments = { "-I", "--avcodec-hw=any", plugin_arg,"--avcodec-codec=q//", "--avcodec-skiploopfilter=4", "--avcodec-fast", "--network-caching=<1800" }; + + //if (isTransform) + // libvlc_instance_ = LibVlcAPI.libvlc_new(argumentTransform); + //else + libvlc_instance_ = LibVlcAPI.libvlc_new(arguments); + + libvlc_media_player_ = LibVlcAPI.libvlc_media_player_new(libvlc_instance_); + } + + public void SetRenderWindow(int wndHandle) + { + if (libvlc_instance_ != IntPtr.Zero && wndHandle != 0) + { + LibVlcAPI.libvlc_media_player_set_hwnd(libvlc_media_player_, wndHandle); + } + } + + public void PlayFile(string filePath) + { + IntPtr libvlc_media = LibVlcAPI.libvlc_media_new_path(libvlc_instance_, filePath); + if (libvlc_media != IntPtr.Zero) + { + LibVlcAPI.libvlc_media_parse(libvlc_media); + + duration_ = LibVlcAPI.libvlc_media_get_duration(libvlc_media) / 1000.0; + + LibVlcAPI.libvlc_media_player_set_media(libvlc_media_player_, libvlc_media); + LibVlcAPI.libvlc_media_release(libvlc_media); + + LibVlcAPI.libvlc_media_player_play(libvlc_media_player_); + } + } + + public void PlayStream(string url) + { + IntPtr libvlc_media = LibVlcAPI.libvlc_media_new_location(libvlc_instance_, url); + if (libvlc_media != IntPtr.Zero) + { + LibVlcAPI.libvlc_media_player_set_media(libvlc_media_player_, libvlc_media); + LibVlcAPI.libvlc_media_release(libvlc_media); + + LibVlcAPI.libvlc_media_player_play(libvlc_media_player_); + + LibVlcAPI.libvlc_media_parse(libvlc_media); + + Thread.Sleep(300); + + duration_ = LibVlcAPI.libvlc_media_get_duration(libvlc_media) / 1000.0; + } + } + + public void Pause() + { + if (libvlc_media_player_ != IntPtr.Zero) + { + LibVlcAPI.libvlc_media_player_pause(libvlc_media_player_); + } + } + + public void Stop() + { + if (libvlc_media_player_ != IntPtr.Zero) + { + LibVlcAPI.libvlc_media_player_stop(libvlc_media_player_); + } + } + + public double GetPlayTime() + { + return LibVlcAPI.libvlc_media_player_get_time(libvlc_media_player_) / 1000.0; + } + + public void SetPlayTime(double seekTime) + { + LibVlcAPI.libvlc_media_player_set_time(libvlc_media_player_, (Int64)(seekTime * 1000)); + } + + public int GetVolume() + { + return LibVlcAPI.libvlc_audio_get_volume(libvlc_media_player_); + } + + public void SetVolume(int volume) + { + LibVlcAPI.libvlc_audio_set_volume(libvlc_media_player_, volume); + } + + public void SetFullScreen(bool istrue) + { + LibVlcAPI.libvlc_set_fullscreen(libvlc_media_player_, istrue ? 1 : 0); + } + + public double Duration() + { + return duration_; + } + + public string Version() + { + return LibVlcAPI.libvlc_get_version(); + } + } + + internal static class LibVlcAPI + { + internal struct PointerToArrayOfPointerHelper + { + [MarshalAs(UnmanagedType.ByValArray, SizeConst = 11)] + public IntPtr[] pointers; + } + + public static IntPtr libvlc_new(string[] arguments) + { + PointerToArrayOfPointerHelper argv = new PointerToArrayOfPointerHelper(); + argv.pointers = new IntPtr[11]; + + for (int i = 0; i < arguments.Length; i++) + { + argv.pointers[i] = Marshal.StringToHGlobalAnsi(arguments[i]); + } + + IntPtr argvPtr = IntPtr.Zero; + try + { + int size = Marshal.SizeOf(typeof(PointerToArrayOfPointerHelper)); + argvPtr = Marshal.AllocHGlobal(size); + Marshal.StructureToPtr(argv, argvPtr, false); + + return libvlc_new(arguments.Length, argvPtr); + } + finally + { + for (int i = 0; i < arguments.Length + 1; i++) + { + if (argv.pointers[i] != IntPtr.Zero) + { + Marshal.FreeHGlobal(argv.pointers[i]); + } + } + if (argvPtr != IntPtr.Zero) + { + Marshal.FreeHGlobal(argvPtr); + } + } + } + + public static IntPtr libvlc_media_new_path(IntPtr libvlc_instance, string path) + { + IntPtr pMrl = IntPtr.Zero; + try + { + byte[] bytes = Encoding.UTF8.GetBytes(path); + pMrl = Marshal.AllocHGlobal(bytes.Length + 1); + Marshal.Copy(bytes, 0, pMrl, bytes.Length); + Marshal.WriteByte(pMrl, bytes.Length, 0); + return libvlc_media_new_path(libvlc_instance, pMrl); + } + finally + { + if (pMrl != IntPtr.Zero) + { + Marshal.FreeHGlobal(pMrl); + } + } + } + + public static IntPtr libvlc_media_new_location(IntPtr libvlc_instance, string path) + { + IntPtr pMrl = IntPtr.Zero; + try + { + byte[] bytes = Encoding.UTF8.GetBytes(path); + pMrl = Marshal.AllocHGlobal(bytes.Length + 1); + Marshal.Copy(bytes, 0, pMrl, bytes.Length); + Marshal.WriteByte(pMrl, bytes.Length, 0); + return libvlc_media_new_location(libvlc_instance, pMrl); + } + finally + { + if (pMrl != IntPtr.Zero) + { + Marshal.FreeHGlobal(pMrl); + } + } + } + + // ---------------------------------------------------------------------------------------- + // 以下是libvlc.dll导出函数 + + // 创建一个libvlc实例,它是引用计数的 + [DllImport("libvlc", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + [SuppressUnmanagedCodeSecurity] + private static extern IntPtr libvlc_new(int argc, IntPtr argv); + + // 释放libvlc实例 + [DllImport("libvlc", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + [SuppressUnmanagedCodeSecurity] + public static extern void libvlc_release(IntPtr libvlc_instance); + + [DllImport("libvlc", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + [SuppressUnmanagedCodeSecurity] + public static extern String libvlc_get_version(); + + // 从视频来源(例如Url)构建一个libvlc_meida + [DllImport("libvlc", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + [SuppressUnmanagedCodeSecurity] + private static extern IntPtr libvlc_media_new_location(IntPtr libvlc_instance, IntPtr path); + + // 从本地文件路径构建一个libvlc_media + [DllImport("libvlc", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + [SuppressUnmanagedCodeSecurity] + private static extern IntPtr libvlc_media_new_path(IntPtr libvlc_instance, IntPtr path); + + [DllImport("libvlc", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + [SuppressUnmanagedCodeSecurity] + public static extern void libvlc_media_release(IntPtr libvlc_media_inst); + + // 创建libvlc_media_player(播放核心) + [DllImport("libvlc", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + [SuppressUnmanagedCodeSecurity] + public static extern IntPtr libvlc_media_player_new(IntPtr libvlc_instance); + + // 将视频(libvlc_media)绑定到播放器上 + [DllImport("libvlc", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + [SuppressUnmanagedCodeSecurity] + public static extern void libvlc_media_player_set_media(IntPtr libvlc_media_player, IntPtr libvlc_media); + + // 设置图像输出的窗口 + [DllImport("libvlc", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + [SuppressUnmanagedCodeSecurity] + public static extern void libvlc_media_player_set_hwnd(IntPtr libvlc_mediaplayer, Int32 drawable); + + [DllImport("libvlc", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + [SuppressUnmanagedCodeSecurity] + public static extern void libvlc_media_player_play(IntPtr libvlc_mediaplayer); + + [DllImport("libvlc", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + [SuppressUnmanagedCodeSecurity] + public static extern void libvlc_media_player_pause(IntPtr libvlc_mediaplayer); + + [DllImport("libvlc", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + [SuppressUnmanagedCodeSecurity] + public static extern void libvlc_media_player_stop(IntPtr libvlc_mediaplayer); + + // 解析视频资源的媒体信息(如时长等) + [DllImport("libvlc", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + [SuppressUnmanagedCodeSecurity] + public static extern void libvlc_media_parse(IntPtr libvlc_media); + + [DllImport("libvlc", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + [SuppressUnmanagedCodeSecurity] + public static extern bool libvlc_media_is_parsed(IntPtr libvlc_media); + + // 返回视频的时长(必须先调用libvlc_media_parse之后,该函数才会生效) + [DllImport("libvlc", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + [SuppressUnmanagedCodeSecurity] + public static extern Int64 libvlc_media_get_duration(IntPtr libvlc_media); + + // 当前播放的时间 + [DllImport("libvlc", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + [SuppressUnmanagedCodeSecurity] + public static extern Int64 libvlc_media_player_get_time(IntPtr libvlc_mediaplayer); + + // 设置播放位置(拖动) + [DllImport("libvlc", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + [SuppressUnmanagedCodeSecurity] + public static extern void libvlc_media_player_set_time(IntPtr libvlc_mediaplayer, Int64 time); + + [DllImport("libvlc", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + [SuppressUnmanagedCodeSecurity] + public static extern void libvlc_media_player_release(IntPtr libvlc_mediaplayer); + + // 获取和设置音量 + [DllImport("libvlc", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + [SuppressUnmanagedCodeSecurity] + public static extern int libvlc_audio_get_volume(IntPtr libvlc_media_player); + + [DllImport("libvlc", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + [SuppressUnmanagedCodeSecurity] + public static extern void libvlc_audio_set_volume(IntPtr libvlc_media_player, int volume); + + // 设置全屏 + [DllImport("libvlc", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + [SuppressUnmanagedCodeSecurity] + public static extern void libvlc_set_fullscreen(IntPtr libvlc_media_player, int isFullScreen); + } +} diff --git a/Container/Common/WebSocketForFaceManage.cs b/Container/Common/WebSocketForFaceManage.cs new file mode 100644 index 0000000..76fea11 --- /dev/null +++ b/Container/Common/WebSocketForFaceManage.cs @@ -0,0 +1,137 @@ +using System; +using System.Configuration; +using System.Threading; +using WebSocket4Net; + +namespace Container.Common +{ + public class WebSocketForFaceManage + { + private WebSocket websocket = null; + App app = ((App)System.Windows.Application.Current); + public delegate void WebSocketReceiveDelegate(string type, string message); + public static event WebSocketReceiveDelegate WebSocketReceiveEvent; + private Class_Log log = new Class_Log(); + bool reconnect = false; + #region WebSocketClient + + public void OpenWebSocket() + { + try + { + var ws = ConfigurationManager.AppSettings["websocketForFace"]; + log.WriteLogFile(ws, "rich"); + websocket = new WebSocket(ws); + websocket.Error += new EventHandler(websocket_Error); + websocket.MessageReceived += new EventHandler(websocket_MessageReceived); + websocket.Open(); + //websocket.Opened += new EventHandler(websocket_Opened); + websocket.Closed += new EventHandler(websocket_Closed); + } + catch (Exception ex) + { + log.WriteLogFile(ex.ToString()); + } + } + + void websocket_Closed(object sender, EventArgs e) + { + if (!reconnect) + { + reconnect = true; + ReConnect(); + } + } + + public void CloseWebSocket() + { + if (websocket != null) + { + reconnect = true; + websocket.Close(); + } + + } + + void websocket_MessageReceived(object sender, MessageReceivedEventArgs e) + { + log.WriteLogFile("进来了", "rich"); + try + { + WebSocketReceiveEvent("richad", ""); + } + catch (Exception ex) + { + log.WriteLogFile(ex.ToString(), "WebSocketLog"); + + } + } + + void websocket_Error(object sender, SuperSocket.ClientEngine.ErrorEventArgs e) + { + + log.WriteLogFile(e.Exception.Message + e.Exception.StackTrace, "WebSocketErrorLog"); + //try + //{ + // if (websocket != null) + // websocket.Close(); + //} + //catch + //{ + //} + //ReConnect(); + } + + /// + /// websocket重连 + /// + private void ReConnect() + { + try + { + Action ac = new Action(() => + { + while (true) + { + try + { + if (websocket.State == WebSocketState.Closed) + { + Thread.Sleep(30000); + + if (websocket.State == WebSocketState.Closed) + websocket.Open(); + } + + if (websocket.State == WebSocketState.Open) + { + //reconnect = false; + break; + } + } + catch (Exception ex) + { + log.WriteLogFile(ex.ToString(), "WebSocketErrorLog"); + } + finally + { + Thread.Sleep(3000); + } + + + } + }); + ac.BeginInvoke((o) => + { + reconnect = false; + }, null); + } + catch (Exception ex) + { + log.WriteLogFile(ex.ToString(), "WebSocketErrorLog"); + } + } + + #endregion + } +} diff --git a/Container/Common/WebSocketForProgram.cs b/Container/Common/WebSocketForProgram.cs new file mode 100644 index 0000000..5dfdf67 --- /dev/null +++ b/Container/Common/WebSocketForProgram.cs @@ -0,0 +1,182 @@ +using System; +using System.Configuration; +using System.Threading; +using WebSocket4Net; + + +namespace Container.Common +{ + public class WebSocketForProgram + { + private WebSocket websocket = null; + App app = ((App)System.Windows.Application.Current); + public delegate void WebSocketReceiveDelegate(string type, string message); + public static event WebSocketReceiveDelegate WebSocketReceiveEvent; + private Class_Log log = new Class_Log(); + bool reconnect = false; + #region WebSocketClient + + public void OpenWebSocket() + { + try + { + //var ws = ConfigurationManager.AppSettings["websocketProgram"]; + var ws = "ws://" + app.websocketProgramIP + ":" + ConfigurationManager.AppSettings["websocketProgramPort"]; + log.WriteLogFile("ws--" + ws, "GetSyncDev"); + if (websocket != null) { + if (websocket.State == WebSocketState.Open) + { + websocket.Close(); + } + websocket.Dispose(); + websocket = null; + } + websocket = new WebSocket(ws); + websocket.Error += new EventHandler(websocket_Error); + websocket.MessageReceived += new EventHandler(websocket_MessageReceived); + websocket.Opened += new EventHandler(websocket_Opened); + websocket.Closed += new EventHandler(websocket_Closed); + websocket.Open(); + } + catch (Exception ex) + { + log.WriteLogFile(ex.ToString()); + } + } + + public void ReloadWebSocket() + { + try + { + if (websocket != null) + { + reconnect = false; + websocket.Close(); + websocket.Dispose(); + websocket = null; + } + log.WriteLogFile("打开--", "GetSyncDev"); + OpenWebSocket(); + } + catch (Exception e) + { + + log.WriteLogFile(e.ToString(), "WebSocketForProgramError"); + } + } + void websocket_Closed(object sender, EventArgs e) + { + app.isProgramSync = false; + //if (!reconnect) + //{ + // reconnect = true; + // ReConnect(); + //} + } + void websocket_Opened(object sender, EventArgs e) { + reconnect = false; + log.WriteLogFile("打开","客户端"); + app.isProgramSync = true; + } + + public void CloseWebSocket() + { + + if (websocket != null) + { + reconnect = true; + websocket.Close(); + } + + } + + void websocket_MessageReceived(object sender, MessageReceivedEventArgs e) + { + try + { + WebSocketReceiveEvent("play", e.Message); + } + catch (Exception ex) + { + log.WriteLogFile(ex.ToString(), "WebSocketLog"); + + } + } + + void websocket_Error(object sender, SuperSocket.ClientEngine.ErrorEventArgs e) + { + log.WriteLogFile("失败"+e.ToString(), "客户端"); + app.isProgramSync = false; + //try + //{ + // if (websocket != null) + // websocket.Close(); + //} + //catch + //{ + //} + //reconnect = true; + //ReConnect(); + } + + /// + /// websocket重连 + /// + private void ReConnect() + { + try + { + Action ac = new Action(() => + { + while (reconnect) + { + log.WriteLogFile("重试"+ (websocket==null), "WebSocketForProgramErrorLog"); + try + { + if (websocket != null) + { + log.WriteLogFile("重试State" + websocket.State, "WebSocketForProgramErrorLog"); + if (websocket.State == WebSocketState.Closed) + { + reconnect = false; + websocket.Open(); + } + + if (websocket.State == WebSocketState.Open) + { + reconnect = false; + break; + } + } + else { + log.WriteLogFile("重试OpenWebSocket", "WebSocketForProgramErrorLog"); + //Thread.Sleep(10000); + OpenWebSocket(); + } + } + catch (Exception ex) + { + log.WriteLogFile(ex.ToString(), "WebSocketForProgramErrorLog"); + } + finally + { + Thread.Sleep(10000); + } + + + } + }); + ac.BeginInvoke((o) => + { + //reconnect = false; + }, null); + } + catch (Exception ex) + { + log.WriteLogFile(ex.ToString(), "WebSocketForProgramErrorLog"); + } + } + + #endregion + } +} diff --git a/Container/Common/WebsocketForProgramServer.cs b/Container/Common/WebsocketForProgramServer.cs new file mode 100644 index 0000000..bd8baea --- /dev/null +++ b/Container/Common/WebsocketForProgramServer.cs @@ -0,0 +1,94 @@ +using Fleck; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Configuration; +using System.Linq; +using System.Text; +using System.Threading; +using System.Threading.Tasks; + +namespace Container.Common +{ + public class WebsocketForProgramServer + { + //public static ConcurrentDictionary _sockets = new ConcurrentDictionary(); + public static List allSockets = new List(); + + private static Class_Log log = new Class_Log(); //日志记录文件 + private static App app = ((App)System.Windows.Application.Current); + WebSocketServer server = null; + public void openSocket() + { + + try + { + allSockets.Clear(); + FleckLog.Level = LogLevel.Debug; + var ws = "ws://"+app.websocketProgramIP + ":"+ ConfigurationManager.AppSettings["websocketProgramPort"]; + server = new WebSocketServer(ws); + //RecognizerCLR.setBeamDir(serialPortname, microAngle); + server.Start(socket => + { + socket.OnOpen = () => //当建立Socket链接时执行此方法 + { + //var data = socket.ConnectionInfo; //通过data可以获得这个链接传递过来的Cookie信息,用来区分各个链接和用户之间的关系(如果需要后台主动推送信息到某个客户的时候,可以使用Cookie) + //Console.WriteLine("Open!"); + log.WriteLogFile(JsonConvert.SerializeObject(socket.ConnectionInfo.ClientIpAddress), "socket"); + IWebSocketConnection clearSocket = null; + foreach (var item in allSockets) + { + if (item.ConnectionInfo.ClientIpAddress == socket.ConnectionInfo.ClientIpAddress) { + clearSocket = item; + break; + } + } + if (clearSocket != null) { + allSockets.Remove(clearSocket); + } + allSockets.Add(socket); + //log.WriteLogFile(JsonConvert.SerializeObject(allSockets), "socket"); + log.WriteLogFile(allSockets.Count.ToString(), "GetSyncDevServer"); + }; + + socket.OnClose = () =>// 当关闭Socket链接十执行此方法 + { + + //Console.WriteLine("Close!"); + allSockets.Remove(socket); + }; + + socket.OnMessage = message =>// 接收客户端发送过来的信息 + { + + }; + }); + } + catch (Exception e) + { + + log.WriteLogFile(e.ToString(), "recorderror"); + } + + } + + public void CloasSocket() { + try + { + + if (server != null) + { + server.Dispose(); + server = null; + } + allSockets.RemoveRange(0, allSockets.Count); + allSockets.Clear(); + } + catch (Exception e) + { + log.WriteLogFile(e.Message, "ProgramServerError"); + } + } + + } +} diff --git a/Container/Common/WebsocketForVoice.cs b/Container/Common/WebsocketForVoice.cs new file mode 100644 index 0000000..d452b8a --- /dev/null +++ b/Container/Common/WebsocketForVoice.cs @@ -0,0 +1,630 @@ +using Container.Viewmodel; +using Fleck; +using NAudio.Wave; +using Newtonsoft.Json.Linq; +using System; +using System.Collections.Generic; +using System.Configuration; +using System.IO; +using System.Linq; +using System.Net; +using System.Runtime.InteropServices; +using System.Text; +using System.Threading; +using System.Threading.Tasks; + +namespace Container.Common +{ + public class WebsocketForVoice + { + //public static ConcurrentDictionary _sockets = new ConcurrentDictionary(); + public static List allSockets = new List(); + static bool flag = true; + private static Class_Log log = new Class_Log(); //日志记录文件 + private static App app = ((App)System.Windows.Application.Current); + + + private int deviceNumber = 0; // 选择的录音设备下标。多个设备时可设置为用户选择 + private WaveIn waveIn; // waveIn操作类 + private WaveFormat recordingFormat; // 录音格式 + private WaveFileWriter writer; // 录音文件操作类 + public event EventHandler StoppedEvent = delegate { }; // 录音结束事件 + public event EventHandler DataAvailableEvent = delegate { }; // 录音过程中接收到数据事件 + private byte[] wavdata; + private int aud_stat = AudioStatus.MSP_AUDIO_SAMPLE_FIRST;//音频状态 + + StringBuilder result = new StringBuilder();//存储最终识别的结果 + int totalLength = 0;//用来记录总的识别后的结果的长度,判断是否超过缓存最大值 + private int ep_stat = EpStatus.MSP_EP_LOOKING_FOR_SPEECH;//端点状态 + private int rec_stat = RecogStatus.MSP_REC_STATUS_SUCCESS;//识别状态 + int errcode = (int)Errors.MSP_SUCCESS; + bool isClose = false; + + + public void openSocket() + { + try + { + IatNativeMethods.initVoice(); + // 设置录音格式WaveFormat(16000, 16, 1); + //recordingFormat = new WaveFormat(16000, 8, WaveIn.GetCapabilities(deviceNumber).Channels); + recordingFormat = new WaveFormat(16000, 16, 1); + // 设置麦克风操作对象 + waveIn = new WaveIn(); + waveIn.DeviceNumber = deviceNumber; // 设置使用的录音设备 + waveIn.DataAvailable += OnDataAviailable; // 接收到音频数据时,写入文件 + waveIn.RecordingStopped += OnRecordingStopped; // 录音结束时执行 + waveIn.WaveFormat = recordingFormat; + + FleckLog.Level = LogLevel.Debug; + var ws = ConfigurationManager.AppSettings["websocketUrlForVoice"]; + var server = new WebSocketServer(ws); + server.Start(socket => + { + socket.OnOpen = () => //当建立Socket链接时执行此方法 + { + allSockets.Add(socket); + }; + + socket.OnClose = () =>// 当关闭Socket链接十执行此方法 + { + allSockets.Remove(socket); + }; + + socket.OnMessage = message =>// 接收客户端发送过来的信息 + { + if (message == "record" && flag) + { + startRecord(); + isClose = false; + } + else if (message == "close" && !flag) + { + isClose = true; + StopRecorder(); + flag = true; + } + }; + }); + } + catch (Exception e) + { + + log.WriteLogFile(e.ToString(), "recorderror"); + } + + } + + + private void startRecord() + { + flag = false; + log.WriteLogFile("录音进入时间" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff"), "录音"); + try + { + + StartRecorder(); + + } + catch (Exception e) + { + + log.WriteLogFile("---------22222222222-------" + "record" + e.Message, "recorderror"); + } + + } + + private static string PostUrl(string url, string postData) + { + string result = string.Empty; + try + { + HttpWebRequest wbRequest = (HttpWebRequest)WebRequest.Create(url); + wbRequest.Method = "POST"; + wbRequest.ContentType = "application/x-www-form-urlencoded"; + wbRequest.ContentLength = Encoding.UTF8.GetByteCount(postData); + + using (Stream requestStream = wbRequest.GetRequestStream()) + { + using (StreamWriter swrite = new StreamWriter(requestStream)) + { + swrite.Write(postData); + } + } + HttpWebResponse wbResponse = (HttpWebResponse)wbRequest.GetResponse(); + using (Stream responseStream = wbResponse.GetResponseStream()) + { + using (StreamReader sread = new StreamReader(responseStream)) + { + result = sread.ReadToEnd(); + } + } + + } + catch (Exception ex) + { + log.WriteLogFile("PostUrl异常" + url + "---------------" + postData, "recorderror"); + log.WriteLogFile("PostUrl异常" + ex.ToString(), "recorderror"); + } + return result; + } + + /// + /// 开始录音 + /// + /// 保存的文件名 + internal bool StartRecorder(string filename = "r.wav") + { + try + { + totalLength = 0; + // 设置文件操作类 + writer = new WaveFileWriter(filename, recordingFormat); + result.Clear(); + // 开始录音 + waveIn.StartRecording(); + int errcode = (int)Errors.MSP_SUCCESS; + string session_begin_params = "sub=iat,domain=iat,language=zh_cn,accent=mandarin,sample_rate=16000,result_type=plain,result_encoding=gb2312"; + IatNativeMethods.session_id = IatNativeMethods.QISRSessionBegin(null, session_begin_params, ref errcode); + if (errcode != (int)Errors.MSP_SUCCESS) + { + flag = true; + string result = "{\"code\": \"401\",\"msg\": \"未识别到语音输入\",\"data\": { \"ModelType\" : \"\", \"ActionType\" : \"\", \"query\":\"???\" , \"ttsMsg\":\"未识别到语音输入\"}}"; + SendMsg(result); + StopRecorder(); + } + } + catch (Exception e) + { + + log.WriteLogFile(e.ToString(), "record"); + } + return true; + } + + private void run_iat(byte[] _wavdata) + { + try + { + + + wavdata = _wavdata; + if (wavdata == null || wavdata.Length == 0) + { + try + { + wavdata = System.IO.File.ReadAllBytes("wav/test.wav"); + } + catch (Exception e) + { + //System.Diagnostics.Debug.WriteLine(e.Message); + //wavdata = null; + } + } + //wavdata = System.IO.File.ReadAllBytes("wav/r.wav"); + + int res = IatNativeMethods.QISRAudioWrite(IatNativeMethods.session_id, wavdata, (uint)wavdata.Length, aud_stat, ref ep_stat, ref rec_stat); + if (res != (int)Errors.MSP_SUCCESS) + { + flag = true; + string result = "{\"code\": \"401\",\"msg\": \"未识别到语音输入\",\"data\": { \"ModelType\" : \"\", \"ActionType\" : \"\", \"query\":\"???\" , \"ttsMsg\":\"未识别到语音输入\"}}"; + SendMsg(result); + log.WriteLogFile("写入识别的音频失败!" + res); + + StopRecorder(); + return; + } + if (RecogStatus.MSP_REC_STATUS_SUCCESS != rec_stat) + { + IntPtr now_result = IatNativeMethods.QISRGetResult(IatNativeMethods.session_id, ref rec_stat, 0, ref errcode); + if (errcode != (int)Errors.MSP_SUCCESS) + { + flag = true; + log.WriteLogFile("获取结果失败:" + errcode); + string result = "{\"code\": \"401\",\"msg\": \"未识别到语音输入\",\"data\": { \"ModelType\" : \"\", \"ActionType\" : \"\", \"query\":\"???\" , \"ttsMsg\":\"未识别到语音输入\"}}"; + SendMsg(result); + + StopRecorder(); + return; + } + if (now_result != null) + { + int length = now_result.ToString().Length; + totalLength += length; + if (totalLength > 4096) + { + flag = true; + log.WriteLogFile("缓存空间不够" + totalLength); + string result = "{\"code\": \"401\",\"msg\": \"未识别到语音输入\",\"data\": { \"ModelType\" : \"\", \"ActionType\" : \"\", \"query\":\"???\" , \"ttsMsg\":\"未识别到语音输入\"}}"; + SendMsg(result); + StopRecorder(); + return; + } + result.Append(Marshal.PtrToStringAnsi(now_result)); + } + } + if (EpStatus.MSP_EP_AFTER_SPEECH == ep_stat) + { + //run_iatlast(); + StopRecorder(); + + return; + } + } + catch (Exception ex) + { + + log.WriteLogFile(ex.ToString(), "recorderror"); + } + //Thread.Sleep(150);//防止频繁占用cpu + } + + private void run_iatlast() + { + + var res = IatNativeMethods.QISRAudioWrite(IatNativeMethods.session_id, null, 0, AudioStatus.MSP_AUDIO_SAMPLE_LAST, ref ep_stat, ref rec_stat); + if (res != (int)Errors.MSP_SUCCESS) + { + flag = true; + string result = "{\"code\": \"401\",\"msg\": \"未识别到语音输入\",\"data\": { \"ModelType\" : \"\", \"ActionType\" : \"\", \"query\":\"???\" , \"ttsMsg\":\"未识别到语音输入\"}}"; + SendMsg(result); + log.WriteLogFile("写入音频失败!" + res); + StopRecorder(); + return; + } + + while (RecogStatus.MSP_REC_STATUS_COMPLETE != rec_stat) + { + IntPtr now_result = IatNativeMethods.QISRGetResult(IatNativeMethods.session_id, ref rec_stat, 0, ref errcode); + if (errcode != (int)Errors.MSP_SUCCESS) + { + flag = true; + log.WriteLogFile("获取结果失败:" + errcode); + string result = "{\"code\": \"401\",\"msg\": \"未识别到语音输入\",\"data\": { \"ModelType\" : \"\", \"ActionType\" : \"\", \"query\":\"???\" , \"ttsMsg\":\"未识别到语音输入\"}}"; + SendMsg(result); + StopRecorder(); + return; + } + if (now_result != null) + { + int length = now_result.ToString().Length; + totalLength += length; + if (totalLength > 4096) + { + flag = true; + log.WriteLogFile("缓存空间不够" + totalLength); + string result = "{\"code\": \"401\",\"msg\": \"未识别到语音输入\",\"data\": { \"ModelType\" : \"\", \"ActionType\" : \"\", \"query\":\"???\" , \"ttsMsg\":\"未识别到语音输入\"}}"; + SendMsg(result); + + StopRecorder(); + } + + result.Append(Marshal.PtrToStringAnsi(now_result)); + } + Thread.Sleep(150);//防止频繁占用cpu + } + QISRSessionEnd(); + //int ret = IatNativeMethods.QISRSessionEnd(IatNativeMethods.session_id, "normal end"); + //if (errcode != (int)Errors.MSP_SUCCESS) + //{ + // flag = true; + // log.WriteLogFile("QISRSessionEnd failed, error code is: %d" + ret); + // string result = "{\"code\": \"401\",\"msg\": \"未识别到语音输入\",\"data\": { \"ModelType\" : \"\", \"ActionType\" : \"\", \"query\":\"???\" , \"ttsMsg\":\"未识别到语音输入\"}}"; + // WebsocketForVoice.allSockets.ToList().ForEach(s => s.Send(result)); + //} + //if (result.Length > 0) + //{ + // string resultReturn = "{\"code\": \"100\",\"msg\": \""+ result.ToString() + "\",\"data\": { \"ModelType\" : \"\", \"ActionType\" : \"\", \"query\":\"???\" , \"ttsMsg\":\"录音结束\"}}"; + // //最终方法 + + // WebsocketForVoice.allSockets.ToList().ForEach(s => s.Send(resultReturn)); + // var url = app.kioskUrl + "/Video/VoiceSearch"; + // StringBuilder sb = new StringBuilder(); + // sb.Append("Query=" + WebUtility.UrlEncode(result.ToString()) + "&IP=" + app.LocalIP); + // resultReturn = PostUrl(url, sb.ToString()); + // WebsocketForVoice.allSockets.ToList().ForEach(s => s.Send(resultReturn)); + // flag = true; + //} + } + + private void SendMsg(string result) + { + if (!isClose) + { + WebsocketForVoice.allSockets.ToList().ForEach(s => s.Send(result)); + } + + } + private void QISRSessionEnd() + { + int ret = IatNativeMethods.QISRSessionEnd(IatNativeMethods.session_id, "normal end"); + if (!isClose) + { + if (errcode != (int)Errors.MSP_SUCCESS) + { + flag = true; + + log.WriteLogFile("QISRSessionEnd failed, error code is: %d" + ret); + string result = "{\"code\": \"401\",\"msg\": \"未识别到语音输入\",\"data\": { \"ModelType\" : \"\", \"ActionType\" : \"\", \"query\":\"???\" , \"ttsMsg\":\"未识别到语音输入\"}}"; + SendMsg(result); + + } + else + { + if (result.Length > 0) + { + string resultReturn = "{\"code\": \"201\",\"msg\": \"" + result.ToString() + "\",\"data\": { \"ModelType\" : \"\", \"ActionType\" : \"\", \"query\":\"???\" , \"ttsMsg\":\"录音结束\"}}"; + //最终方法 + WebsocketForVoice.allSockets.ToList().ForEach(s => s.Send(resultReturn)); + var url = app.kioskUrl + "/Api/Video/VoiceSearch"; + StringBuilder sb = new StringBuilder(); + sb.Append("Query=" + WebUtility.UrlEncode(result.ToString()) + "&IP=" + app.LocalIP); + resultReturn = PostUrl(url, sb.ToString()); + if (!isClose) + { + SendMsg(resultReturn); + } + if (ConfigurationManager.AppSettings["isvoiceup"] == "1") + { + Action action = new Action(() => + { + var Jo = JObject.Parse(resultReturn); + string code = Jo.Value("code"); + if (code == "500") + { + var voiceData = Jo.Value("data"); + var voiceCode = voiceData.Value("voiceCode"); + var mallCode = voiceData.Value("mallCode"); + if (!string.IsNullOrEmpty(voiceCode)) + { + var voiceFile = Directory.GetCurrentDirectory() + "\\r.wav"; + var formDatas = new List(); + //添加文件 + formDatas.Add(new FormItemModel() + { + Key = "wav", + Value = "", + FileName = DateTime.Now.Ticks.ToString("x") + ".wav", + FileContent = File.OpenRead(voiceFile), + voiceCode = voiceCode, + mallCode = mallCode + }); + //添加文件 + formDatas.Add(new FormItemModel() + { + Key = "voiceCode", + Value = voiceCode, + + }); + //添加文件 + formDatas.Add(new FormItemModel() + { + Key = "mallCode", + Value = mallCode, + + }); + var result = PostForm(app.kioskUrl + "/SaasApi/Statistics/UpLoadVoiceFiles", formDatas); + } + + } + + }); + action.BeginInvoke(null, null); + } + flag = true; + } + else + { + flag = true; + string resultReturn = "{\"code\": \"401\",\"msg\": \"未识别到语音输入\",\"data\": { \"ModelType\" : \"\", \"ActionType\" : \"\", \"query\":\"???\" , \"ttsMsg\":\"录音结束\"}}"; + SendMsg(resultReturn); + } + } + } + } + + + /// + /// 结束录音 + /// + /// + internal bool StopRecorder() + { + waveIn.StopRecording(); + return true; + } + + /// + /// 录音结束回调函数 + /// + /// + /// + private void OnRecordingStopped(object sender, StoppedEventArgs e) + { + writer.Dispose(); + run_iatlast(); + // 通知结束事件 + StoppedEvent(this, EventArgs.Empty); + } + + /// + /// 录音回调函数,写入数据 + /// + /// + /// + private void OnDataAviailable(object sender, WaveInEventArgs e) + { + try + { + byte[] buffer = e.Buffer; + int bytesRecorded = e.BytesRecorded; + long maxFileLength = this.recordingFormat.AverageBytesPerSecond * 60; + var toWrite = (int)Math.Min(maxFileLength - writer.Length, bytesRecorded); + if (toWrite > 0) + { + writer.Write(buffer, 0, bytesRecorded); + run_iat(buffer); + aud_stat = AudioStatus.MSP_AUDIO_SAMPLE_CONTINUE; + } + DataAvailableEvent(this, EventArgs.Empty); + } + catch (Exception ex) + { + + log.WriteLogFile(ex.ToString(), "recorderror"); + } + } + + + + /// + /// 使用Post方法获取字符串结果 + /// + /// + /// Post表单内容 + /// + /// 默认20秒 + /// 响应内容的编码类型(默认utf-8) + /// + public static string PostForm(string url, List formItems, CookieContainer cookieContainer = null, string refererUrl = null, Encoding encoding = null, int timeOut = 10000) + { + try + { + + + HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); + #region 初始化请求对象 + request.Method = "POST"; + request.Timeout = timeOut; + request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"; + request.KeepAlive = true; + request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36"; + if (!string.IsNullOrEmpty(refererUrl)) + request.Referer = refererUrl; + if (cookieContainer != null) + request.CookieContainer = cookieContainer; + #endregion + + string boundary = "----" + DateTime.Now.Ticks.ToString("x");//分隔符 + request.ContentType = string.Format("multipart/form-data; boundary={0}", boundary); + //请求流 + var postStream = new MemoryStream(); + #region 处理Form表单请求内容 + //是否用Form上传文件 + var formUploadFile = formItems != null && formItems.Count > 0; + if (formUploadFile) + { + //文件数据模板 + string fileFormdataTemplate = + "\r\n--" + boundary + + "\r\nContent-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"" + + "\r\nContent-Type: application/octet-stream" + + "\r\n\r\n"; + //文本数据模板 + string dataFormdataTemplate = + "\r\n--" + boundary + + "\r\nContent-Disposition: form-data; name=\"{0}\"" + + "\r\n\r\n{1}"; + foreach (var item in formItems) + { + string formdata = null; + if (item.IsFile) + { + //上传文件 + formdata = string.Format( + fileFormdataTemplate, + item.Key, //表单键 + item.FileName); + } + else + { + //上传文本 + formdata = string.Format( + dataFormdataTemplate, + item.Key, + item.Value); + } + + //统一处理 + byte[] formdataBytes = null; + //第一行不需要换行 + if (postStream.Length == 0) + formdataBytes = Encoding.UTF8.GetBytes(formdata.Substring(2, formdata.Length - 2)); + else + formdataBytes = Encoding.UTF8.GetBytes(formdata); + postStream.Write(formdataBytes, 0, formdataBytes.Length); + + //写入文件内容 + if (item.FileContent != null && item.FileContent.Length > 0) + { + using (var stream = item.FileContent) + { + byte[] buffer = new byte[1024]; + int bytesRead = 0; + while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) != 0) + { + postStream.Write(buffer, 0, bytesRead); + } + } + } + } + //结尾 + var footer = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n"); + postStream.Write(footer, 0, footer.Length); + + } + else + { + request.ContentType = "application/x-www-form-urlencoded"; + } + #endregion + + request.ContentLength = postStream.Length; + + #region 输入二进制流 + if (postStream != null) + { + postStream.Position = 0; + //直接写入流 + Stream requestStream = request.GetRequestStream(); + + byte[] buffer = new byte[1024]; + int bytesRead = 0; + while ((bytesRead = postStream.Read(buffer, 0, buffer.Length)) != 0) + { + requestStream.Write(buffer, 0, bytesRead); + } + + ////debug + //postStream.Seek(0, SeekOrigin.Begin); + //StreamReader sr = new StreamReader(postStream); + //var postStr = sr.ReadToEnd(); + postStream.Close();//关闭文件访问 + } + #endregion + + HttpWebResponse response = (HttpWebResponse)request.GetResponse(); + if (cookieContainer != null) + { + response.Cookies = cookieContainer.GetCookies(response.ResponseUri); + } + + using (Stream responseStream = response.GetResponseStream()) + { + using (StreamReader myStreamReader = new StreamReader(responseStream, encoding ?? Encoding.UTF8)) + { + string retString = myStreamReader.ReadToEnd(); + return retString; + } + } + } + catch (Exception e) + { + + log.WriteLogFile(e.ToString(), "voiceerror"); + return ""; + } + } + } +} + diff --git a/Container/Common/Win32Api.cs b/Container/Common/Win32Api.cs new file mode 100644 index 0000000..4c20564 --- /dev/null +++ b/Container/Common/Win32Api.cs @@ -0,0 +1,37 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.InteropServices; +using System.Text; +using System.Threading.Tasks; + +namespace Container.Common +{ + public class Win32Api + { + [StructLayout(LayoutKind.Sequential)] + public class POINT + { + public int x; + public int y; + } + [StructLayout(LayoutKind.Sequential)] + public class MouseHookStruct + { + public POINT pt; + public int hwnd; + public int wHitTestCode; + public int dwExtraInfo; + } + public delegate int HookProc(int nCode, IntPtr wParam, IntPtr lParam); + //安装钩子 + [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)] + public static extern int SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hInstance, int threadId); + //卸载钩子 + [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)] + public static extern bool UnhookWindowsHookEx(int idHook); + //调用下一个钩子 + [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)] + public static extern int CallNextHookEx(int idHook, int nCode, IntPtr wParam, IntPtr lParam); + } +} diff --git a/Container/Container.csproj b/Container/Container.csproj new file mode 100644 index 0000000..29856cf --- /dev/null +++ b/Container/Container.csproj @@ -0,0 +1,1143 @@ + + + + + + + + Debug + AnyCPU + {DAE19E2F-B2BB-4778-B0F2-5FC48DC5975A} + WinExe + Properties + Container + Container + v4.8 + 512 + {60dc8134-eba5-43b8-bcc9-bb4bc16c2548};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + 4 + + publish\ + true + Disk + false + Foreground + 7 + Days + false + false + true + 0 + 1.0.0.%2a + false + false + true + + + + + x64 + true + full + false + bin\x64\Debug\ + DEBUG;TRACE + prompt + 4 + false + + + x86 + pdbonly + true + bin\x64\Release\ + TRACE + prompt + 4 + false + + + qm.ico + + + LocalIntranet + + + false + + + + x86 + bin\x64\Debug\ + false + + + x86 + bin\x86\Release\ + false + + + true + bin\x64\Debug\ + DEBUG;TRACE + full + x64 + prompt + MinimumRecommendedRules.ruleset + + + bin\x64\Release\ + TRACE + true + pdbonly + x64 + prompt + MinimumRecommendedRules.ruleset + + + + ..\packages\AForge.2.2.5\lib\AForge.dll + + + ..\packages\AForge.Video.2.2.5\lib\AForge.Video.dll + + + ..\packages\AForge.Video.DirectShow.2.2.5\lib\AForge.Video.DirectShow.dll + + + ..\packages\CefSharp.Common.89.0.170\lib\net452\CefSharp.dll + + + ..\packages\CefSharp.Common.89.0.170\lib\net452\CefSharp.Core.dll + + + ..\packages\CefSharp.Wpf.89.0.170\lib\net452\CefSharp.Wpf.dll + + + ..\packages\Fleck.1.1.0\lib\net45\Fleck.dll + + + False + bin\Release\GifImageLib.dll + False + + + False + bin\Release\icsharpcode.sharpzipLib_dll\X86\0648.0009.0101.0002\ICSharpCode.SharpZipLib.dll + + + ..\packages\Microsoft.Diagnostics.Tracing.EventSource.Redist.1.1.28\lib\net46\Microsoft.Diagnostics.Tracing.EventSource.dll + + + False + bin\Release\Microsoft.Practices.Prism.dll + + + ..\packages\Microsoft.Bcl.Async.1.0.168\lib\net40\Microsoft.Threading.Tasks.dll + + + ..\packages\Microsoft.Bcl.Async.1.0.168\lib\net40\Microsoft.Threading.Tasks.Extensions.dll + + + ..\packages\Microsoft.Bcl.Async.1.0.168\lib\net40\Microsoft.Threading.Tasks.Extensions.Desktop.dll + + + ..\packages\Microsoft.Win32.1.0.0\lib\net40\Microsoft.Win32.dll + + + ..\packages\NAudio.1.8.0\lib\net35\NAudio.dll + True + + + False + bin\Release\Newtonsoft.Json.dll + + + ..\packages\QRCoder.1.3.9\lib\net40\QRCoder.dll + + + ..\packages\RabbitMQ.Client.5.1.2\lib\net451\RabbitMQ.Client.dll + + + ..\packages\SharpDX.4.2.0\lib\net45\SharpDX.dll + + + ..\packages\SharpDX.DirectSound.4.2.0\lib\net45\SharpDX.DirectSound.dll + + + + + + + + + + + + ..\packages\System.Net.Sockets.4.3.0\lib\net46\System.Net.Sockets.dll + + + ..\packages\System.ValueTuple.4.5.0\lib\netstandard1.0\System.ValueTuple.dll + + + + + + + + + + + 4.0 + + + False + bin\Release\Transitionals.dll + + + ..\packages\Vlc.DotNet.Core.3.1.0\lib\net45\Vlc.DotNet.Core.dll + + + ..\packages\Vlc.DotNet.Core.Interops.3.1.0\lib\net45\Vlc.DotNet.Core.Interops.dll + + + ..\packages\Vlc.DotNet.Wpf.3.1.0\lib\net45\Vlc.DotNet.Wpf.dll + + + False + bin\Release\WebSocket4Net.dll + + + + + + + ..\packages\XamlAnimatedGif.2.0.0-alpha.1\lib\net45\XamlAnimatedGif.dll + + + + + MSBuild:Compile + Designer + + + + + + + + + BGPage.xaml + + + GetUrl.xaml + + + GetUrlForLocal.xaml + + + + ServiceInfo.xaml + + + UCAppButton.xaml + + + WindowAppChoose.xaml + + + WindowButton.xaml + + + WinShow.xaml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + BrandProg.xaml + + + ClockControl.xaml + + + CountDown.xaml + + + LiveShow.xaml + + + MarqueeControl.xaml + + + MarqueeControlNew.xaml + + + NavGuide.xaml + + + ProgControl.xaml + + + RichAD.xaml + + + UCImageText.xaml + + + WeatherControl.xaml + + + WindowView.xaml + + + WindowViewNew.xaml + + + Designer + MSBuild:Compile + + + Designer + MSBuild:Compile + + + MSBuild:Compile + Designer + + + Designer + MSBuild:Compile + + + Designer + MSBuild:Compile + + + Designer + MSBuild:Compile + + + Designer + MSBuild:Compile + + + Designer + MSBuild:Compile + + + MSBuild:Compile + Designer + + + App.xaml + Code + + + MainWindow.xaml + Code + + + Designer + MSBuild:Compile + + + Designer + MSBuild:Compile + + + Designer + MSBuild:Compile + + + Designer + MSBuild:Compile + + + Designer + MSBuild:Compile + + + Designer + MSBuild:Compile + + + Designer + MSBuild:Compile + + + Designer + MSBuild:Compile + + + Designer + MSBuild:Compile + + + Designer + MSBuild:Compile + + + Designer + MSBuild:Compile + + + Designer + MSBuild:Compile + + + Designer + MSBuild:Compile + + + + + Code + + + True + True + Resources.resx + + + True + Settings.settings + True + + + ResXFileCodeGenerator + Resources.Designer.cs + + + + Designer + + + SettingsSingleFileGenerator + Settings.Designer.cs + + + + + + + + + + Designer + + + + + + + + + + + + + + + + + + + + + Always + + + + + + + + + + + + + + + + + + + + + + + + + + + + + False + Microsoft .NET Framework 4.5.2 %28x86 和 x64%29 + true + + + False + .NET Framework 3.5 SP1 + false + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 这台计算机上缺少此项目引用的 NuGet 程序包。使用“NuGet 程序包还原”可下载这些程序包。有关更多信息,请参见 http://go.microsoft.com/fwlink/?LinkID=322105。缺少的文件是 {0}。 + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Container/Container.csproj.user b/Container/Container.csproj.user new file mode 100644 index 0000000..5f01d08 --- /dev/null +++ b/Container/Container.csproj.user @@ -0,0 +1,14 @@ + + + + ShowAllFiles + publish\ + + + + + + zh-CN + false + + \ No newline at end of file diff --git a/Container/Control/NotificationAreaIcon.cs b/Container/Control/NotificationAreaIcon.cs new file mode 100644 index 0000000..c6d2b7f --- /dev/null +++ b/Container/Control/NotificationAreaIcon.cs @@ -0,0 +1,166 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Windows; +using System.Windows.Input; +using System.Windows.Markup; +using System.Windows.Media; +using System.Windows.Threading; +using Drawing = System.Drawing; +using Forms = System.Windows.Forms; + +namespace Container.Control +{ + /// + /// Represents a thin wrapper for + /// + [ContentProperty("Text")] + [DefaultEvent("MouseDoubleClick")] + public class NotificationAreaIcon : FrameworkElement + { + Forms.NotifyIcon notifyIcon; + + public static readonly RoutedEvent MouseClickEvent = EventManager.RegisterRoutedEvent( + "MouseClick", RoutingStrategy.Bubble, typeof(MouseButtonEventHandler), typeof(NotificationAreaIcon)); + + public static readonly RoutedEvent MouseDoubleClickEvent = EventManager.RegisterRoutedEvent( + "MouseDoubleClick", RoutingStrategy.Bubble, typeof(MouseButtonEventHandler), typeof(NotificationAreaIcon)); + + public static readonly DependencyProperty IconProperty = + DependencyProperty.Register("Icon", typeof(ImageSource), typeof(NotificationAreaIcon)); + + public static readonly DependencyProperty TextProperty = + DependencyProperty.Register("Text", typeof(string), typeof(NotificationAreaIcon)); + + public static readonly DependencyProperty FormsContextMenuProperty = + DependencyProperty.Register("MenuItems", typeof(List), typeof(NotificationAreaIcon), new PropertyMetadata(new List())); + + protected override void OnInitialized(EventArgs e) + { + base.OnInitialized(e); + + // Create and initialize the window forms notify icon based + notifyIcon = new Forms.NotifyIcon(); + notifyIcon.Text = Text; + if (!DesignerProperties.GetIsInDesignMode(this)) + { + notifyIcon.Icon = FromImageSource(Icon); + } + notifyIcon.Visible = FromVisibility(Visibility); + + if (this.MenuItems != null && this.MenuItems.Count > 0) + { + notifyIcon.ContextMenu = new System.Windows.Forms.ContextMenu(this.MenuItems.ToArray()); + } + + notifyIcon.MouseDown += OnMouseDown; + notifyIcon.MouseUp += OnMouseUp; + notifyIcon.MouseClick += OnMouseClick; + notifyIcon.MouseDoubleClick += OnMouseDoubleClick; + + Dispatcher.ShutdownStarted += OnDispatcherShutdownStarted; + } + + private void OnDispatcherShutdownStarted(object sender, EventArgs e) + { + notifyIcon.Dispose(); + } + + private void OnMouseDown(object sender, Forms.MouseEventArgs e) + { + OnRaiseEvent(MouseDownEvent, new MouseButtonEventArgs( + InputManager.Current.PrimaryMouseDevice, 0, ToMouseButton(e.Button))); + } + + private void OnMouseUp(object sender, Forms.MouseEventArgs e) + { + OnRaiseEvent(MouseUpEvent, new MouseButtonEventArgs( + InputManager.Current.PrimaryMouseDevice, 0, ToMouseButton(e.Button))); + } + + private void OnMouseDoubleClick(object sender, Forms.MouseEventArgs e) + { + OnRaiseEvent(MouseDoubleClickEvent, new MouseButtonEventArgs( + InputManager.Current.PrimaryMouseDevice, 0, ToMouseButton(e.Button))); + } + + private void OnMouseClick(object sender, Forms.MouseEventArgs e) + { + OnRaiseEvent(MouseClickEvent, new MouseButtonEventArgs( + InputManager.Current.PrimaryMouseDevice, 0, ToMouseButton(e.Button))); + } + + private void OnRaiseEvent(RoutedEvent handler, MouseButtonEventArgs e) + { + e.RoutedEvent = handler; + RaiseEvent(e); + } + + public List MenuItems + { + get { return (List)GetValue(FormsContextMenuProperty); } + set { SetValue(FormsContextMenuProperty, value); } + } + + public ImageSource Icon + { + get { return (ImageSource)GetValue(IconProperty); } + set { SetValue(IconProperty, value); } + } + + public string Text + { + get { return (string)GetValue(TextProperty); } + set { SetValue(TextProperty, value); } + } + + public event MouseButtonEventHandler MouseClick + { + add { AddHandler(MouseClickEvent, value); } + remove { RemoveHandler(MouseClickEvent, value); } + } + + public event MouseButtonEventHandler MouseDoubleClick + { + add { AddHandler(MouseDoubleClickEvent, value); } + remove { RemoveHandler(MouseDoubleClickEvent, value); } + } + + #region Conversion members + + private static Drawing.Icon FromImageSource(ImageSource icon) + { + if (icon == null) + { + return null; + } + Uri iconUri = new Uri(icon.ToString()); + return new Drawing.Icon(Application.GetResourceStream(iconUri).Stream); + } + + private static bool FromVisibility(Visibility visibility) + { + return visibility == Visibility.Visible; + } + + private MouseButton ToMouseButton(Forms.MouseButtons button) + { + switch (button) + { + case Forms.MouseButtons.Left: + return MouseButton.Left; + case Forms.MouseButtons.Right: + return MouseButton.Right; + case Forms.MouseButtons.Middle: + return MouseButton.Middle; + case Forms.MouseButtons.XButton1: + return MouseButton.XButton1; + case Forms.MouseButtons.XButton2: + return MouseButton.XButton2; + } + throw new InvalidOperationException(); + } + + #endregion Conversion members + } +} \ No newline at end of file diff --git a/Container/Control/OpenExeClass.cs b/Container/Control/OpenExeClass.cs new file mode 100644 index 0000000..a761a32 --- /dev/null +++ b/Container/Control/OpenExeClass.cs @@ -0,0 +1,190 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +using System.Diagnostics; +using System.Runtime.InteropServices; +using System.Windows.Forms; + +namespace Container.Control +{ +/// + /// 以嵌入到窗体的方式打开外部exe--kongfl888 2013 + /// + class OpenExeClass + { + static Process process = null; + static IntPtr appWin; + private static string exeName = ""; + + + [DllImport("user32.dll", SetLastError = true)] + private static extern IntPtr FindWindow(string lpClassName, string lpWindowName); + + [DllImport("user32.dll", SetLastError = true)] + private static extern long SetParent(IntPtr hWndChild, IntPtr hWndNewParent); + + [DllImport("user32.dll", SetLastError = true)] + private static extern bool MoveWindow(IntPtr hwnd, int x, int y, int cx, int cy, bool repaint); + + //[DllImport("user32.dll", EntryPoint = "GetWindowThreadProcessId", SetLastError = true, + // CharSet = CharSet.Unicode, ExactSpelling = true, + // CallingConvention = CallingConvention.StdCall)] + //private static extern long GetWindowThreadProcessId(long hWnd, long lpdwProcessId); + + //[DllImport("user32.dll", EntryPoint = "GetWindowLongA", SetLastError = true)] + //private static extern long GetWindowLong(IntPtr hwnd, int nIndex); + + //[DllImport("user32.dll", EntryPoint = "SetWindowLongA", SetLastError = true)] + //private static extern long SetWindowLong(IntPtr hwnd, int nIndex, long dwNewLong); + + + //[DllImport("user32.dll", SetLastError = true)] + //private static extern long SetWindowPos(IntPtr hwnd, long hWndInsertAfter, long x, long y, long cx, long cy, long wFlags); + + + //[DllImport("user32.dll", EntryPoint = "PostMessageA", SetLastError = true)] + //private static extern bool PostMessage(IntPtr hwnd, uint Msg, long wParam, long lParam); + + //[DllImport("user32.dll", EntryPoint = "ShowWindow", SetLastError = true)] + //private static extern bool ShowWindow(IntPtr hWnd, uint nCmdShow); + + //[DllImport("user32.dll")] + //[return: MarshalAs(UnmanagedType.Bool)] + //static extern bool GetWindowRect(IntPtr hWnd, ref RECT lpRect); + + //[StructLayout(LayoutKind.Sequential)] + //public struct RECT + //{ + // public int Left; //最左坐标 + // public int Top; //最上坐标 + // public int Right; //最右坐标 + // public int Bottom; //最下坐标 + //} + + //private const int SWP_NOOWNERZORDER = 0x200; + //private const int SWP_NOREDRAW = 0x8; + //private const int SWP_NOZORDER = 0x4; + //private const int SWP_SHOWWINDOW = 0x0040; + //private const int WS_EX_MDICHILD = 0x40; + //private const int SWP_FRAMECHANGED = 0x20; + //private const int SWP_NOACTIVATE = 0x10; + //private const int SWP_ASYNCWINDOWPOS = 0x4000; + //private const int SWP_NOMOVE = 0x2; + //private const int SWP_NOSIZE = 0x1; + //private const int GWL_STYLE = (-16); + //private const int WS_VISIBLE = 0x10000000; + //private const int WM_CLOSE = 0x10; + //private const int WS_CHILD = 0x40000000; + //private const int SW_HIDE = 0; + + + public string ExeName + { + get + { + return exeName; + } + set + { + exeName = value; + } + } + + public static void OpenExe(GroupBox fm, string filefullname) + { + exeName = filefullname; + if (exeName == null || exeName == string.Empty) return; + + try + { + // Start the process + process = System.Diagnostics.Process.Start(exeName); + + // Wait for process to be created and enter idle condition + process.WaitForInputIdle(); + + // Get the main handle + //appWin = process.MainWindowHandle; + + appWin = FindWindow(null, "War3 fixer"); + } + catch (Exception ex) + { + MessageBox.Show(fm, ex.Message, "Error"); + } + + // Put it into this form + SetParent(appWin, fm.Handle); + + // Remove border and whatnot + // SetWindowLong(appWin, GWL_STYLE, WS_VISIBLE); + + // Move the window to overlay it on this window + MoveWindow(appWin, 0, 0, fm.Width+2, fm.Height, true); + //RECT rc = new RECT(); + //GetWindowRect(appWin, ref rc); + //int width = rc.Right - rc.Left; //窗口的宽度 + //int height = rc.Bottom - rc.Top; //窗口的高度 + //int x = rc.Left; + //int y = rc.Top; + //MoveWindow(appWin, 0, 0, width, height, true); + + fm.Text = ""; + + } + + + public static bool CloseExe() + { + bool sc = false; + try + { + System.Diagnostics.Process[] processList = System.Diagnostics.Process.GetProcesses(); + foreach (System.Diagnostics.Process process2 in processList) + { + if (process2.Id == process.Id) + { + process.Kill(); //结束进程 + sc=process.WaitForExit(100000); + + } + } + } + catch { sc = true; } + return sc; + } + + public static Process IsProcessRun() + { + Process processRun = new Process(); + try + { + System.Diagnostics.Process[] processList = System.Diagnostics.Process.GetProcesses(); + foreach (System.Diagnostics.Process process2 in processList) + { + if (process2.Id == process.Id) + { + processRun = process; + + } + } + } + catch { } + + return processRun; + } + + //主窗体退出时写FormClosed事件函数,调用CloseExe()函数 在控件改变大小的时候,重新MoveWindow()即可,如: + //private void splitContainer1_Panel2_Resize(object sender, EventArgs e) + //{ + // if (this.appWin != IntPtr.Zero) + // { + // MoveWindow(appWin, 0, 0, this.splitContainer1.Panel2.Width, this.splitContainer1.Panel2.Height, true); + // } + // base.OnResize(e); + //} + } +} diff --git a/Container/Control/ZipFloClass.cs b/Container/Control/ZipFloClass.cs new file mode 100644 index 0000000..dd3d7db --- /dev/null +++ b/Container/Control/ZipFloClass.cs @@ -0,0 +1,158 @@ +using Microsoft.Win32; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using ICSharpCode.SharpZipLib.Checksums; +using ICSharpCode.SharpZipLib.Zip; +using ICSharpCode.SharpZipLib.GZip; +using System.Windows; +using System.IO.Compression; +using Container.Common; + +namespace Container.Control +{ + class ZipFloClass + { + + /// 利用 WinRAR 进行压缩 + /// + /// 将要被压缩的文件夹(绝对路径) + /// 压缩后的 .rar 的存放目录(绝对路径) + /// 压缩文件的名称(包括后缀) + /// true 或 false。压缩成功返回 true,反之,false。 + public bool RAR(string path, string rarPath, string rarName) + { + bool flag = false; + string rarexe; //WinRAR.exe 的完整路径 + RegistryKey regkey; //注册表键 + Object regvalue; //键值 + string cmd; //WinRAR 命令参数 + ProcessStartInfo startinfo; + Process process; + + try + { + regkey = Registry.ClassesRoot.OpenSubKey(@"Applications\WinRAR.exe\shell\open\command"); + regvalue = regkey.GetValue(""); // 键值为 "d:\Program Files\WinRAR\WinRAR.exe" "%1" + rarexe = regvalue.ToString(); + regkey.Close(); + rarexe = rarexe.Substring(1, rarexe.Length - 7); // d:\Program Files\WinRAR\WinRAR.exe + Directory.CreateDirectory(path); + //压缩命令,相当于在要压缩的文件夹(path)上点右键 ->WinRAR->添加到压缩文件->输入压缩文件名(rarName) + cmd = string.Format("a {0} {1} -r", rarName, path); + startinfo = new ProcessStartInfo(); + startinfo.FileName = rarexe; + startinfo.Arguments = cmd; //设置命令参数 + startinfo.WindowStyle = ProcessWindowStyle.Hidden; //隐藏 WinRAR 窗口 + startinfo.WorkingDirectory = rarPath; + process = new Process(); + process.StartInfo = startinfo; + process.Start(); + process.WaitForExit(); //无限期等待进程 winrar.exe 退出 + if (process.HasExited) + { + flag = true; + } + process.Close(); + } + catch (Exception e) + { + throw e; + } + return flag; + } + /// + /// 利用 WinRAR 进行解压缩 + /// + /// 文件解压路径(绝对) + /// 将要解压缩的 .rar 文件的存放目录(绝对路径) + /// 将要解压缩的 .rar 文件名(包括后缀) + /// true 或 false。解压缩成功返回 true,反之,false。 + public bool UnRAR(string path, string rarPath, string rarName) + { + bool flag = false; + string rarexe; + RegistryKey regkey; + Object regvalue; + string cmd; + ProcessStartInfo startinfo; + Process process; + try + { + regkey = Registry.ClassesRoot.OpenSubKey(@"Applications\WinRAR.exe\shell\open\command"); + regvalue = regkey.GetValue(""); + rarexe = regvalue.ToString(); + regkey.Close(); + rarexe = rarexe.Substring(1, rarexe.Length - 7); + Directory.CreateDirectory(path); + //解压缩命令,相当于在要压缩文件(rarName)上点右键 ->WinRAR->解压到当前文件夹 + cmd = string.Format("x {0} {1} -y", rarName, path); + startinfo = new ProcessStartInfo(); + startinfo.FileName = rarexe; + startinfo.Arguments = cmd; + startinfo.WindowStyle = ProcessWindowStyle.Hidden; + startinfo.WorkingDirectory = rarPath; + process = new Process(); + process.StartInfo = startinfo; + process.Start(); + process.WaitForExit(); + if (process.HasExited) + { + flag = true; + } + process.Close(); + } + catch (Exception e) + { + Class_Log log = new Class_Log(); + log.WriteLogFile(e.ToString(), "UnZipError"); + } + return flag; + } + public static void UnZip(string SrcFile, string DstFile) + { + try + { + System.IO.Compression.ZipFile.ExtractToDirectory(SrcFile, DstFile); + // 列出压缩压缩文件 + //using (FileStream zipFileToOpen = new FileStream(SrcFile, FileMode.Open)) + //using (ZipArchive archive = new ZipArchive(zipFileToOpen, ZipArchiveMode.Read)) + //{ + + // foreach (var zipArchiveEntry in archive.Entries) + // MessageBox.Show( + // "FullName of the Zip Archive Entry: {0}", zipArchiveEntry. + // ); + //} + } + catch (Exception ex) + { + Class_Log log = new Class_Log(); + log.WriteLogFile(ex.ToString(), "UnZipError"); + } + // 读取其中一个文件的内容 + //using (FileStream zipFileToOpen = new FileStream(zipFilePath, FileMode.Open)) + //using (ZipArchive archive = new ZipArchive(zipFileToOpen, ZipArchiveMode.Read)) + //{ + // // 解压某个文件 + // ZipArchiveEntry entry = archive.GetEntry("ZipArchiveSample.exe"); + // Console.WriteLine(entry.Name); + // using (System.IO.Stream stream = entry.Open()) + // { + // System.IO.Stream output = new FileStream("http://www.cnblogs.com/ZipArchiveSample.exe", FileMode.Create); + // int b = -1; + // while ((b = stream.ReadByte()) != -1) + // { + // output.WriteByte((byte)b); + // } + // output.Close(); + // } + + //} + } + } +} diff --git a/Container/Icon/qm.ico b/Container/Icon/qm.ico new file mode 100644 index 0000000..34a51b5 Binary files /dev/null and b/Container/Icon/qm.ico differ diff --git a/Container/MainWindow.xaml b/Container/MainWindow.xaml new file mode 100644 index 0000000..19e0a3a --- /dev/null +++ b/Container/MainWindow.xaml @@ -0,0 +1,69 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Container/MainWindow.xaml.cs b/Container/MainWindow.xaml.cs new file mode 100644 index 0000000..b0f85cd --- /dev/null +++ b/Container/MainWindow.xaml.cs @@ -0,0 +1,2836 @@ +using Container.Business; +using Container.ChildWindows; +using Container.Common; +using Container.Control; +using Container.Model; +using Container.Services; +using Container.Win; +using Microsoft.Win32; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Configuration; +using System.Diagnostics; +using System.IO; +using System.IO.Ports; +using System.Linq; +using System.Net; +using System.Net.Sockets; +using System.Runtime.InteropServices; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Data; +using System.Windows.Documents; +using System.Windows.Forms; +using System.Windows.Input; +using System.Windows.Interop; +using System.Windows.Media; +using System.Windows.Media.Imaging; +using System.Windows.Navigation; +using System.Windows.Shapes; +//using System.Runtime.InteropServices; +using System.Windows.Threading; +using Transitionals; + +namespace Container +{ + /// + /// MainWindow.xaml 的交互逻辑 + /// + public partial class MainWindow : Window + { + [DllImport("user32.dll", SetLastError = true)] + static extern IntPtr FindWindow(string IpClassName, string IpWindowName); + [DllImport("user32.dll", SetLastError = true)] + static extern IntPtr SetParent(IntPtr ChildWin, IntPtr FatherWin); + [DllImport("user32.dll", SetLastError = true)] + static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int x, int y, int cx, int cy, uint uflags); + [DllImport("user32.dll", SetLastError = true)] + static extern bool MoveWindow(IntPtr hWnd, int x, int y, int nWindth, int nheight, bool brepaint); + DispatcherTimer timer = new DispatcherTimer(); + DispatcherTimer timerRecord = new DispatcherTimer(); + //DispatcherTimer timerDownFiles = new DispatcherTimer(); + BackgroundWorker background = new BackgroundWorker();//主线程 + private Class_Log log = new Class_Log(); //日志记录文件 + private bool isStop = false;//是否关闭线程 + private string shutDownTime = string.Empty;//记录上一次获取的关机时间 + private Thread HeatBeatThread;//获取关机指令的心跳线程 + HttpMessage httpmessage = new HttpMessage(); //通讯类 + App app = ((App)System.Windows.Application.Current); + Class_Config config = new Class_Config(); //加载配置文件 + List MyProcessName = new List(); //当前打开的应用程序进程名 + WebSocketManage web = new WebSocketManage(); + BackgroundWorker backgroundWorker; + bool startexe = false; + const int WM_CLOSE = 0x0010;//关闭窗体 + PlayBackManage pbm = new PlayBackManage(); + private const uint WM_SYSCOMMAND = 0x112; //系统消息 + private const int SC_MONITORPOWER = 0xF020; //关闭显示器的系统命令 + private const int SC_SCREENSAVE = 0xf140; + private const int MonitorPowerOff = 2; //2为PowerOff, 1为省电状态,-1为开机 + private const int MonitorPowerOn = -1; //2为PowerOff, 1为省电状态,-1为开机 + private static readonly IntPtr HWND_BROADCAST = new IntPtr(0xffff);//广播消息,所有顶级窗体都会接收 + private Socket socket; + + [DllImport("user32.dll")] + static extern void mouse_event(MouseEventFlag flags, int dx, int dy, int data, UIntPtr extraInfo); + [Flags] + enum MouseEventFlag : uint + { + Move = 0x0001, + LeftDown = 0x0002, + LeftUp = 0x0004, + RightDown = 0x0008, + RightUp = 0x0010, + MiddleDown = 0x0020, + MiddleUp = 0x0040, + XDown = 0x0080, + XUp = 0x0100, + Wheel = 0x0800, + VirtualDesk = 0x4000, + Absolute = 0x8000 + } + + + public WindowViewNew WinView + { + set + { + if (value != null) + { + log.WriteLogFile("main关了", "seeyou"); + value.Close(); + + Thread.Sleep(2500); + //Process[] pro = Process.GetProcesses(); + //for (int i = 0; i < pro.Length; i++) + //{ + // if (pro[i].ProcessName.ToLower() == "pcscreensavers.exe") + // { + // pro[i].Kill();//结束进程 + // return; + // } + //} + timer_Tick("", new EventArgs()); + + log.WriteLogFile("结束", "seeyou"); + } + } + } + + + public MainWindow() + { + InitializeComponent(); + //判断是否已经打开了改程序,防止重复打开 + string Productname = System.Windows.Forms.Application.ProductName; + Process[] p = Process.GetProcessesByName(Productname); + if (p.Length > 1) + { + Environment.Exit(0); + } + app.ScreenWidth = SystemParameters.PrimaryScreenWidth; + app.ScreenWidth = 1920; + app.ScreenHeight = SystemParameters.PrimaryScreenHeight; + app.ScreenHeight = 1080; + config.LoadConfig(); + this.WindowStartupLocation = System.Windows.WindowStartupLocation.CenterScreen; + backgroundWorker = new BackgroundWorker(); + backgroundWorker.WorkerReportsProgress = true; + backgroundWorker.WorkerSupportsCancellation = true; + backgroundWorker.ProgressChanged += BackgroundWorker_ProgressChanged; + backgroundWorker.RunWorkerCompleted += BackgroundWorker_RunWorkerCompleted; + backgroundWorker.DoWork += BackgroundWorker_DoWork; + + timer.Tick += new EventHandler(timer_Tick); + timer.Interval = TimeSpan.FromSeconds(60); + + //timerDownFiles.Tick += new EventHandler(timerDownFiles_Tick); + //timerDownFiles.Interval = TimeSpan.FromHours(1); + app.kioskUrl = ConfigurationManager.AppSettings["kioskUrl"]; + app.OBSPath = ConfigurationManager.AppSettings["OBSPath"]; + mLastInputInfo = new LASTINPUTINFO(); + mLastInputInfo.cbSize = Marshal.SizeOf(mLastInputInfo); + //if (ConfigurationManager.AppSettings["isOnlyScreensaver"].Equals("1")) + //{ + //mIdleTimer = new System.Windows.Threading.DispatcherTimer(); + //mIdleTimer.Tick += new EventHandler(IdleTime);//起个Timer一直获取当前时间 + //mIdleTimer.Interval = new TimeSpan(0, 0, 0, 1, 0); + WebSocketManageForLive.WebSocketReceiveEvent += new WebSocketManageForLive.WebSocketReceiveDelegate(WebSocketManageForLive_WebSocketReceiveEvent); + WebsocketForVoice websocketForVoice = new WebsocketForVoice(); + websocketForVoice.openSocket(); + StartSocketServer(); + KillExplorer(); + WebSocketForKiosk webSocketForKiosk = new WebSocketForKiosk(); + webSocketForKiosk.openSocket(); + + //} + //ChatWebSocketMiddleware chatWebSocketMiddleware = new ChatWebSocketMiddleware(); + //chatWebSocketMiddleware.openSocket(); + //SocketService socketService = new SocketService(); + //socketService.openSocket(); + } + + private void StartSocketServer() + { + try + { + IPAddress ip = IPAddress.Parse("127.0.0.1"); + //当开始监听时候,在服务器创建一个负责IP地址跟端口号的Socket + Socket socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); + IPEndPoint point = new IPEndPoint(ip, 8000); + //监听 + socketWatch.Bind(point); + socketWatch.Listen(10); + Thread th = new Thread(ListenClickConnect); + th.IsBackground = true; + th.Start(socketWatch); + } + catch { } + } + public void ListenClickConnect(object o) + { + Socket socketWatch = o as Socket; + //等待用户连接创建一个负责通信的Socket + while (true) + { + try + { + socket = socketWatch.Accept();//等到客户端新的连接 + } + catch + { + + } + } + } + + void BackgroundWorker_DoWork(object sender, DoWorkEventArgs e) + { + //BackgroundWorker worker = sender as BackgroundWorker; + //try + //{ + // bool done = false; + // int port = int.Parse(app.configport); + // System.Net.IPAddress localIP = System.Net.IPAddress.Parse("127.0.0.1"); + // TcpListener listener = new TcpListener(localIP, port); + // listener.Start();//开始监听。。 + // while (!done) + // { + // TcpClient tc = listener.AcceptTcpClient(); + // log.WriteLogFile("Connection Accepted:" + tc.Client.RemoteEndPoint.ToString(), "TCPLog"); + // NetworkStream ns = tc.GetStream(); + // try + // { + // int BufferSize = 1024; + // byte[] buffer = new byte[BufferSize]; + + // lock (ns) + // { + // try + // { + // int bytesRead = ns.Read(buffer, 0, BufferSize);//获取客户端的数据 + // System.Text.UTF8Encoding ASCII = new System.Text.UTF8Encoding(); + // string Messages = ASCII.GetString(buffer).Substring(0, bytesRead);//字节数组转成字符串 + // log.WriteLogFile(ASCII.GetString(buffer).Substring(0, bytesRead), "TCPLog"); + + // if (Messages.Trim().Equals("0")) + // { + // worker.ReportProgress(1, null); + // } + // else + // { + // string[] str = Messages.Split('|'); + // if (str.Count() > 1) + // { + // if (str.Count() == 2) + // { + // app.Appversion = str[0].Trim().Replace("\u0000", ""); + // app.AppPlayNameCH = str[1].Trim().Replace("\u0000", ""); + // } + // else if (str.Count() == 3) + // { + // app.Appversion = "v" + str[2].Trim().Replace("\u0000", "");//.Replace("\u0000", "") + // app.AppPlayNameCH = str[1].Trim().Replace("\u0000", ""); + // } + // } + // else + // { + // if (Messages.Trim().Replace("\u0000", "").Length < 8) + // app.Appversion = Messages.Trim(); + // if (app.AppPlayName.ToLower().Contains("pc")) + // app.AppPlayNameCH = "信息发布"; + // else + // app.AppPlayNameCH = "导视"; + // } + + // worker.ReportProgress(0, null); + // } + // } + // catch (Exception ex) + // { + // log.WriteLogFile(ex.ToString(), "TCPLog"); + // //worker.ReportProgress(2, null); + // } + // Thread.Sleep(5000); + // } + // ns.Close(); + // tc.Close(); + // } + // catch (Exception ex) + // { + // log.WriteLogFile(ex.ToString(), "TCPLog"); + // } + + // } + //} + //catch (Exception ex) + //{ + // log.WriteLogFile(ex.ToString(), "TCPLog"); + // worker.ReportProgress(2, null); + //} + //e.Cancel = true; + return; + } + void BackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) + { + + } + void BackgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e) + { + int progressPercentage = e.ProgressPercentage; + string userState = (string)e.UserState; + try + { + switch (progressPercentage) + { + case 0: + //收到数据事件 + timer.Start(); + break; + case 1: + app.AppPlayName = ""; + app.CurAppPlayName = app.AppPlayName; + app.NowAppType = ""; + //MessageBox.Show("TCP服务启动失败"); + timer.Stop(); + break; + case 2: + //MessageBox.Show("TCP服务启动失败"); + //this.Close(); + background.CancelAsync(); + break; + default: break; + } + } + catch (System.Exception) + { + + } + } + [DllImport("kernel32.dll", EntryPoint = "SetProcessWorkingSetSize")] + public static extern int SetProcessWorkingSetSize(IntPtr process, int minSize, int maxSize); + private void timer_Tick(object sender, EventArgs e) + { + try + { + Process[] pro = Process.GetProcesses(); + //if (app.AppList.Count > 0) + //{ + // var needApp = app.AppTimeList.Where(i => i.BeginTimeSlot.Substring(0, 2) == DateTime.Now.ToString("HH")).Join(app.AppList, at => at.AppCode, al => al.Code, (at, al) => al).FirstOrDefault(); + // if (needApp == null) + // { + // var defaultApp = app.AppList.Where(i => i.Default == bool.TrueString).FirstOrDefault(); + // if (app.NowNeedPlayApp == null || app.NowNeedPlayApp.Name != defaultApp.Name) + // { + // app.NowNeedPlayApp = defaultApp; + // } + // } + // else + // { + // if (app.NowNeedPlayApp == null || app.NowNeedPlayApp.Name != needApp.Name) + // { + // app.NowNeedPlayApp = needApp; + // } + // } + // bool pcstart = false; + // //for (int i = 0; i < pro.Length; i++) + // //{ + // // if (pro[i].ProcessName.ToLower().Trim() == "pcscreensavers") + // // { + // // pcstart = true; + // // } + // //} + // IntPtr Win = FindWindow(null, "WindowViewNew");//设置置顶 + // if (Win != null && Win != IntPtr.Zero) + // { + // pcstart = true; + // //SetWindowPos(Win, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE); + // } + // if (pcstart) + // { + // if (app.AppPlayinfo == null || app.AppPlayinfo.Name != app.NowNeedPlayApp.Name) + // { + // app.AppPlayinfo = app.NowNeedPlayApp; + // ChangeExE(app.NowNeedPlayApp.Startup, (app.HttpUrl.Replace("//", "|")).Split('/')[0].Replace("|", "//") + "|" + app.deviceid + "|" + app.configwebsocket + "|"); + // return; + // } + // } + //} + + #region 注释用于测试 + if (app.AppList.Count > 0) + { + var needApp = app.AppTimeList.Where(i => i.BeginTimeSlot.Substring(0, 2) == DateTime.Now.ToString("HH")).Join(app.AppList, at => at.AppCode, al => al.Code, (at, al) => al).FirstOrDefault(); + if (needApp == null) + { + var defaultApp = app.AppList.Where(i => i.Default == bool.TrueString).FirstOrDefault(); + app.NowNeedPlayApp = defaultApp; + } + else + { + app.NowNeedPlayApp = needApp; + } + } + string palyExe = string.Empty; + if (app.NowNeedPlayApp == null) + { + app.AppPlayinfo = null; + palyExe = app.configstartexe; + } + else + { + app.AppPlayinfo = app.NowNeedPlayApp; + palyExe = app.NowNeedPlayApp.Startup; + } + if (!string.IsNullOrEmpty(palyExe)) + { + bool pcstart = false; + IntPtr Win = FindWindow(null, "WindowViewNew");//设置置顶 + if (Win != null && Win != IntPtr.Zero) + { + pcstart = true; + SetWindowPos(Win, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE); + } + + bool kioskStart = false; + bool chromeStart = false; + for (int i = 0; i < pro.Length; i++) + { + if (pro[i].ProcessName.ToLower() == app.AppPlayName.ToLower()) + { + kioskStart = true; + break; + } + if (pro[i].ProcessName.ToLower() == "chrome") + { + chromeStart = true; + break; + } + } + if (!(kioskStart || (pcstart && chromeStart))) + { + MyProcessName.Clear(); + StartExE(palyExe, (app.HttpUrl.Replace("//", "|")).Split('/')[0].Replace("|", "//") + "|" + app.deviceid + "|" + app.configwebsocket + "|"); + } + + } + else + { + bool pcstart = false; + IntPtr Win = FindWindow(null, "WindowViewNew");//设置置顶 + if (Win != null && Win != IntPtr.Zero) + { + pcstart = true; + SetWindowPos(Win, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE); + //CloseHandle(Win); + } + if (!pcstart) + { + MyProcessName.Clear(); + app.AppPlayNameCH = "信息发布"; + app.Appversion = app.Containerversion; + MyProcessName.Add("WindowView"); + app.AppPlayName = "pcscreensavers"; + app.CurAppPlayName = app.AppPlayName; + WindowViewNew windowView = new WindowViewNew(0); + windowView.Show(); + } + } + #endregion + //if (app.AppList.Count > 0) + //{ + // var needApp = app.AppTimeList.Where(i => i.BeginTimeSlot.Substring(0, 2) == DateTime.Now.ToString("HH")).Join(app.AppList, at => at.AppCode, al => al.Code, (at, al) => al).FirstOrDefault(); + // if (needApp == null) + // { + // var defaultApp = app.AppList.Where(i => i.Default == bool.TrueString).FirstOrDefault(); + // app.NowNeedPlayApp = defaultApp; + // } + // else + // { + // app.NowNeedPlayApp = needApp; + // } + //} + //string palyExe = string.Empty; + //if (app.NowNeedPlayApp == null) + //{ + // app.AppPlayinfo = null; + // palyExe = app.configstartexe; + //} + //else + //{ + // app.AppPlayinfo = app.NowNeedPlayApp; + // palyExe = app.NowNeedPlayApp.Startup; + //} + //if (!string.IsNullOrEmpty(palyExe)) + //{ + // bool pcstart = false; + // for (int i = 0; i < pro.Length; i++) + // { + // if (pro[i].ProcessName.ToLower() == app.AppPlayName.ToLower()) + // { + // pcstart = true; + // break; + // } + // } + // if (!pcstart) { + // MyProcessName.Clear(); + // StartExE(palyExe, (app.HttpUrl.Replace("//", "|")).Split('/')[0].Replace("|", "//") + "|" + app.deviceid + "|" + app.configwebsocket + "|"); + // } + + //} + //else { + // bool pcstart = false; + // IntPtr Win = FindWindow(null, "WindowViewNew");//设置置顶 + // if (Win != null && Win != IntPtr.Zero) + // { + // pcstart = true; + // //SetWindowPos(Win, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE); + // } + // if (!pcstart) + // { + // MyProcessName.Clear(); + // app.AppPlayNameCH = "信息发布"; + // app.Appversion = app.Containerversion; + // MyProcessName.Add("WindowView"); + // app.AppPlayName = "pcscreensavers"; + // app.CurAppPlayName = app.AppPlayName; + // WindowViewNew windowView = new WindowViewNew(0); + // windowView.Show(); + // } + //} + + //if (app.AppPlayName == "pcscreensavers") + //{ + + //} + //if (app.AppPlayName == "") + //{ + // timer.Stop(); + // return; + //} + //MyProcessName.Clear(); + //string playExe = string.Empty; + //if (app.NowNeedPlayApp == null) + //{ + // app.AppPlayinfo = null; + // playExe = app.configstartexe; + //} + //else + //{ + // app.AppPlayinfo = app.NowNeedPlayApp; + // playExe = app.NowNeedPlayApp.Startup; + //} + //if (!string.IsNullOrEmpty(playExe)) + //{ + // StartExE(playExe, (app.HttpUrl.Replace("//", "|")).Split('/')[0].Replace("|", "//") + "|" + app.deviceid + "|" + app.configwebsocket + "|"); + //} + //else + //{ + // app.AppPlayNameCH = "信息发布"; + // app.Appversion = app.Containerversion; + // MyProcessName.Add("WindowView"); + // app.AppPlayName = "pcscreensavers"; + // app.CurAppPlayName = app.AppPlayName; + // WindowViewNew windowView = new WindowViewNew(); + // windowView.Show(); + + //} + + } + catch (Exception ex) + { + log.WriteLogFile(ex.ToString()); + } + } + + private void timerDownFiles_Tick(object sender, EventArgs e) + { + //try + //{ + // if (DateTime.Now.Hour == 0) { + // PlayBackManage pbm = new PlayBackManage(); + // Action ac3 = new Action(() => + // { + // pbm.InitOutLineFiles();//下载定制节目组图片 + // }); + // ac3.BeginInvoke(null, null); + // } + + //} + //catch (Exception ex) + //{ + // log.WriteLogFile(ex.ToString()); + + //} + } + + + //bool isExecutionOpenApp = false; + /// + /// 心跳线程:获取关机重启指令 + /// + private void HeatBeatGetShutDown() + { + string content = string.Empty; + string synetimeurl = AppDomain.CurrentDomain.BaseDirectory + "/exefile/synetime.bat"; + if (HeatBeatThread == null) + { + //MqttClient mqttClient = new MqttClient(); + if (!string.IsNullOrEmpty(app.configHttpUrl)) + { + RabbitHostedService rabbitHostedService = new RabbitHostedService(); + rabbitHostedService.Register(); + //mqttClient.InitAsync(); + RabbitHostedService.WebSocketReceiveEvent += new RabbitHostedService.WebSocketReceiveDelegate(WebSocketManage_WebSocketReceiveEvent); + MqServer.Create(); + } + HeatBeatThread = new Thread(new ThreadStart(() => + { + while (!isStop) + { + Thread.Sleep(30000); + //if (isExecutionOpenApp) + //{ + // isExecutionOpenApp = false; + //} + try + { + + //StartExE(synetimeurl, ""); + app.IsCanConnect = MyHttpClient.IsCanConnect(app.HttpUrl); + if (string.IsNullOrEmpty(app.configHttpUrl)) + { + content = httpmessage.HeatBeat(); + } + else + { + + content = httpmessage.HeatBeatForMqtt(); + } + + if (!string.IsNullOrEmpty(content)) + { + Process MyProcess = new Process(); + //设定程序名 + MyProcess.StartInfo.FileName = "cmd.exe"; + + //关闭Shell的使用 + MyProcess.StartInfo.UseShellExecute = false; + //重定向标准输入 + MyProcess.StartInfo.RedirectStandardInput = true; + //重定向标准输出 + MyProcess.StartInfo.RedirectStandardOutput = true; + //重定向错误输出 + MyProcess.StartInfo.RedirectStandardError = true; + //设置不显示窗口 + MyProcess.StartInfo.CreateNoWindow = true; + + string cmdtext = string.Empty; + if (content.Equals("ShutDownTime")) + { + if (!string.IsNullOrEmpty(app.shutdowntime)) + { + if (shutDownTime != app.shutdowntime) + { + shutDownTime = app.shutdowntime; + cmdtext = "schtasks /create /tn shutdownWindows /sc DAILY /st " + app.shutdowntime + " /tr \"shutdown -s -f -t 0\" -f"; //关机 + + log.WriteLogFile(cmdtext, "cmdexelog"); + //执行VER命令 + MyProcess.Start(); + MyProcess.StandardInput.WriteLine(cmdtext); + } + } + else if (!string.IsNullOrEmpty(shutDownTime)) + { + shutDownTime = string.Empty; + deleteSchtasks(); + } + } + } + + //if (app.NowAppName != "") + //{ + // if (!app.appClick) + // { + // if (app.NowAppName != app.AppPlayinfo.Name) + // { + // //isExecutionOpenApp = true; + // //Thread.Sleep(10000); + // //打开应用 + + // IEnumerable exeinfo = app.AppList.Where(i => i.Name == app.NowAppName); + // if (exeinfo.Count() > 0) + // { + // // + // //log.WriteLogFile(exeinfo.Count().ToString()); + // if (app.NowAppType != "bat" && app.NowAppType != "") + // { + // killExE(); + // } + // //else if (app.NowAppType == "html") + // //{ + // // app.winh5.WinClose(); + // // //app.winh5 = null; + // //} + // string fileName = exeinfo.ElementAt(0).Startup; + // //if (string.IsNullOrEmpty(exeinfo.ElementAt(0).exestartname)) + // //{ + // // fileName = exeinfo.ElementAt(0).exepath; + // //} + // //else { + // // fileName = exeinfo.ElementAt(0).exepath + "/" + exeinfo.ElementAt(0).exestartname; + // //} + // if (ChangeExE(fileName, exeinfo.ElementAt(0))) + // { + // app.AppPlayinfo = exeinfo.ElementAt(0); + // app.AppPlayNameCH = ""; + // app.Appversion = ""; + + // } + // else + // { + // app.AppPlayName = ""; + // app.AppPlayNameCH = ""; + // app.Appversion = ""; + + // //打开失败 + // } + // //Thread.Sleep(20000); + // } + // } + // } + //} + } + catch (Exception ex) + { + log.WriteLogFile(ex.ToString()); + + } + finally + { + Thread.Sleep(10000); + SetProcessWorkingSetSize(Process.GetCurrentProcess().Handle, -1, -1); + } + } + })); + } + HeatBeatThread.IsBackground = true; + HeatBeatThread.Start(); + } + + /// + /// 打开外部exe应用程序 + /// 应用程序地址 + /// + /// + private bool ChangeExE(string path, string param = "") + { + try + { + if (!File.Exists(path) && !path.StartsWith("http:")) + { + //System.Windows.MessageBox.Show("应用程序打开失败:。。。" + path + " 文件不存在"); + log.WriteLogFile("应用程序打开失败:" + path + " 文件不存在", "UCAppButtonlog"); + return false; + } + + if (path.Substring(path.Length - 4, 4).ToLower().Equals(".bat")) + { + param = ""; + Process myprocess = new Process(); + ProcessStartInfo startInfo = new ProcessStartInfo(path, param); + path = path.Replace("\\", "/"); + startInfo.Verb = "runas"; + startInfo.CreateNoWindow = true; + startInfo.WorkingDirectory = path.Substring(0, path.LastIndexOf("/"));//设置应用程序在其所在目录 + myprocess.StartInfo = startInfo; + myprocess.StartInfo.UseShellExecute = false; + myprocess.StartInfo.CreateNoWindow = true; + myprocess.Start(); + //MyProcessName.Add("chrome"); + app.AppPlayName = "chrome"; + app.CurAppPlayName = app.AppPlayName; + app.NowAppType = "bat"; + //startexe = true; + //timer.Start(); + log.WriteLogFile("打开成功", "startlog"); + } + else + { + Process myprocess = new Process(); + ProcessStartInfo startInfo = new ProcessStartInfo(path, param); + path = path.Replace("\\", "/"); + startInfo.WorkingDirectory = path.Substring(0, path.LastIndexOf("/"));//设置应用程序在其所在目录 + startInfo.Verb = "runas"; + startInfo.CreateNoWindow = true; + myprocess.StartInfo = startInfo; + myprocess.StartInfo.UseShellExecute = false; + myprocess.Start(); + //MyProcessName.Add(myprocess.ProcessName); + app.NowAppType = "exe"; + app.AppPlayName = myprocess.ProcessName; + app.CurAppPlayName = app.AppPlayName; + //startexe = true; + } + //Process myprocess = new Process(); + //ProcessStartInfo startInfo = new ProcessStartInfo(path, param); + //path = path.Replace("\\", "/"); + //startInfo.WorkingDirectory = path.Substring(0, path.LastIndexOf("/"));//设置应用程序在其所在目录工作 + //myprocess.StartInfo = startInfo; + //myprocess.StartInfo.UseShellExecute = false; + //myprocess.Start(); + //ProcessName = myprocess.ProcessName; + return true; + } + catch (Exception ex) + { + log.WriteLogFile(ex.ToString(), "UCAppButtonlog"); + return false; + + } + + } + /// + /// 窗体加载事件 + /// + private void MainWindow_Loaded(object sender, RoutedEventArgs e) + { + try + { + deleteSchtasks("ContainerService"); + string exePath = AppDomain.CurrentDomain.BaseDirectory + "/ContainerService.exe"; + string cmdtext = "schtasks /create /tn ContainerService /sc minute /mo 2 /tr \"" + exePath + "\" -f"; //关机 + createSchtasks(cmdtext); + //loads(); + //this.ShowInTaskbar = false;//使程序不在任务栏显示 + //app.HttpUrl = ""; + Class_Config config = new Class_Config(); + //config.ReadAppInfo(ref app.NowAppList); + config.LoadInitialConfig(); + config.LoadConfig();//加载注册文件(楼栋楼层等设备信息) + app.Containerversion = config.GetVersion(); + log.WriteLogFile(app.HttpUrl, "config"); + log.WriteLogFile(app.configurl, "config"); + + if (app.BuildingID.Equals("") || app.Floor.Equals("")) + { + //app.HttpUrl = ConfigurationManager.AppSettings["RemoteAddress"]; //服务器地址 + // app.HttpUrl = app.configurl; + //配置文件不存在则重新注册 + this.WindowState = WindowState.Minimized; + if (string.IsNullOrEmpty(app.configHttpUrl)) + { + app.HttpUrl = app.configurl; + GetUrlForLocal MyService = new GetUrlForLocal(); + MyService.ShowDialog(); + if (MyService.DialogResult == false) + { + OnMenuItemExitClick(null, null); + return; + } + } + else + { + GetUrl MyService = new GetUrl(); + MyService.ShowDialog(); + if (MyService.DialogResult == false) + { + OnMenuItemExitClick(null, null); + return; + } + } + } + else if (!app.HttpUrl.Replace("\\", "/").Equals(app.configurl.Replace("\\", "/"))) + { + app.HttpUrl = app.configurl; + GetUrlForLocal MyService = new GetUrlForLocal(); + MyService.ShowDialog(); + if (MyService.DialogResult == false) + { + OnMenuItemExitClick(null, null); + return; + } + } + else + { + app.IsCanConnect = MyHttpClient.IsCanConnect(app.HttpUrl); + string msg = ""; + log.WriteLogFile(app.IsCanConnect.ToString(), "connect"); + bool flag = httpmessage.UploadDeviceInfo(app.BuildingID, app.Floor, app.DeviceType, ref msg, false); + //Action ac = new Action(() => + //{ + log.WriteLogFile(flag + "---", "config"); + deleteSchtasks(); + if (app.IsCanConnect && !flag) + { + app.deviceid = ""; + if (string.IsNullOrEmpty(app.configHttpUrl)) + { + GetUrlForLocal MyService = new GetUrlForLocal(); + MyService.ShowDialog(); + if (MyService.DialogResult == false) + { + OnMenuItemExitClick(null, null); + return; + } + } + else + { + GetUrl MyService = new GetUrl(); + MyService.ShowDialog(); + if (MyService.DialogResult == false) + { + OnMenuItemExitClick(null, null); + return; + } + } + return; + } + else + { + if (!string.IsNullOrEmpty(app.shutdowntime)) + { + createSchtasks(); + } + } + //}); + //ac.BeginInvoke(null, null); + } + //btn_OK.Visibility = System.Windows.Visibility.Hidden; + if (!app.deviceid.Equals("")) + { + Terminalid.Text = "当前终端编号:" + app.deviceid; + txtVersion.Text = app.Containerversion; + if (!string.IsNullOrEmpty(app.devicemark)) + Terminalmark.Text = "当前终端标识:" + app.devicemark; + // this.WindowState = WindowState.Normal; + + httpmessage.LoadBG(); + IntPtr Win = FindWindow(null, "BGPage"); //Win_h5Page是我的程序中需要置顶的窗体的名字 + if (Win != null) + { + SetWindowPos(Win, HWND_BOTTOM, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE); + + } + + + string errorMsg = ""; + config.ReadAppInfo(ref app.AppList); + config.ReadAppTimeInfo(ref app.AppTimeList); + httpmessage.LoadAppConfig(ref errorMsg); + httpmessage.LoadScreenTime(); + //if (ConfigurationManager.AppSettings["isOnlyScreensaver"].Equals("1")) + //{ + // httpmessage.LoadAppConfig(ref errorMsg); + //} + IntPtr WinMain = FindWindow(null, "MainWindow"); //Win_h5Page是我的程序中需要置顶的窗体的名字 + if (WinMain != null) + { + SetWindowPos(WinMain, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE); + + } + IntPtr WinBG = FindWindow(null, "BGPage"); //Win_h5Page是我的程序中需要置顶的窗体的名字 + if (WinBG != null) + { + SetWindowPos(WinBG, HWND_BOTTOM, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE); + + } + + + Action UploadApp = new Action(() => + { + HeatBeatGetShutDown(); + if (string.IsNullOrEmpty(app.configHttpUrl)) + { + WebSocketManage.WebSocketReceiveEvent += new WebSocketManage.WebSocketReceiveDelegate(WebSocketManage_WebSocketReceiveEvent); + web.OpenWebSocket(); + + } + WebSocketManageForLive webForLive = new WebSocketManageForLive(); + webForLive.OpenWebSocket(); + //string msg = ""; + //httpmessage.UploadAppInfo(ref msg); + }); + UploadApp.BeginInvoke(null, null); + //app.winh6 = new H5Page(""); + //app.winh6.Show(); + if (app.AppList.Count > 0) + { + var needApp = app.AppTimeList.Where(i => i.BeginTimeSlot.Substring(0, 2) == DateTime.Now.ToString("HH")).Join(app.AppList, at => at.AppCode, al => al.Code, (at, al) => al).FirstOrDefault(); + if (needApp == null) + { + var defaultApp = app.AppList.Where(i => i.Default == bool.TrueString).FirstOrDefault(); + app.NowNeedPlayApp = defaultApp; + } + else + { + app.NowNeedPlayApp = needApp; + } + } + string palyExe = string.Empty; + if (app.NowNeedPlayApp == null) + { + app.AppPlayinfo = null; + palyExe = app.configstartexe; + } + else + { + app.AppPlayinfo = app.NowNeedPlayApp; + palyExe = app.NowNeedPlayApp.Startup; + } + string synetimeurl = AppDomain.CurrentDomain.BaseDirectory + "/exefile/synetime.bat"; + StartExE(synetimeurl, ""); + string windowsset = AppDomain.CurrentDomain.BaseDirectory + "/exefile/windows.bat"; + StartExE(windowsset, ""); + if (!string.IsNullOrEmpty(palyExe)) + { + mouse_event(MouseEventFlag.LeftDown | MouseEventFlag.LeftUp, 0, 0, 0, UIntPtr.Zero); + Action ac1 = new Action(() => + { + StartExE(palyExe, (app.HttpUrl.Replace("//", "|")).Split('/')[0].Replace("|", "//") + "|" + app.deviceid + "|" + app.configwebsocket + "|1"); + }); + ac1.BeginInvoke((o) => + { + this.Dispatcher.Invoke(new Action(() => + { + pbm.DownResource(); + //if (mIdleTimer != null) + //{ + // mIdleTimer.Start(); + //} + this.WindowState = WindowState.Minimized; + //if (startexe) + //{ + // app.AppPlayinfo.AppID = "1"; + + // this.WindowState = System.Windows.WindowState.Minimized; + //} + //else + //{ + // this.WindowState = WindowState.Minimized; + //} + + + })); + + }, null); + } + else + { + app.AppPlayNameCH = "信息发布"; + app.AppPlayName = "pcscreensavers"; + app.Appversion = app.Containerversion; + app.CurAppPlayName = app.AppPlayName; + MyProcessName.Add("WindowView"); + //if (mIdleTimer != null) + //{ + // mIdleTimer.Start(); + //} + WindowViewNew windowView = new WindowViewNew(0); + windowView.Show(); + + } + + if (app.AppList.Count > 1) + { + this.WindowState = WindowState.Minimized; + + if (app.AppList != null && app.AppList.Count > 1) + { + WindowButton win = new WindowButton(); + win.Show(); + } + } + backgroundWorker.RunWorkerAsync(); + log.DeleteFiles(); + + //PlayBackManage pbm = new PlayBackManage(); + // Action ac3 = new Action(() => + // { + // pbm.InitOutLineFiles();//下载定制节目组图片 + // }); + // ac3.BeginInvoke(null, null); + // timerDownFiles.Start(); + this.WindowState = WindowState.Minimized; + } + else + { + Terminalid.Text = "未获得终端号请重新注册。"; + return; + } + } + catch (Exception ex) + { + log.WriteLogFile(ex.ToString()); + } + } + + /// + /// websocket委托事件 + /// + private void WebSocketManage_WebSocketReceiveEvent(string type, string message) + { + if (type == "apppublish")//开始下载 + { + + //ChatWebSocketMiddleware.allSockets.ToList().ForEach(s => s.Send(JsonConvert.SerializeObject(app.AppList))); + //downLineExE(); + //if (ConfigurationManager.AppSettings["MenuShow"].Equals("0")) //判断是否有悬浮框 + //{ + if (app.AppList.Count > 1) + { + + + IntPtr Win = FindWindow(null, "WindowButton"); //置顶窗体 + //if (Win != null) + //{ + // SendMessage(Win, WM_CLOSE, 0, 0); + //} + if (Win == null || Win == IntPtr.Zero) + { + this.Dispatcher.Invoke(new Action(() => + { + WindowButton WinButton = new WindowButton(); + //adView.SetADImage(fileName, app.insertAD.Duration); + WinButton.Show(); + log.WriteLogFile("打开悬浮框"); + IntPtr Win1 = FindWindow(null, "WindowButton");//设置置顶 + SetWindowPos(Win1, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE); + + IntPtr Win2 = FindWindow(null, "WindowViewNew");//设置置顶 + if (Win2 != null && Win2 != IntPtr.Zero) + { + SetWindowPos(Win2, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE); + } + })); + } + + //} + } + } + else + if (type == "appupdate")//开始下载 + { + //downLineExE(); + } + else if (type == "appdown") + { + if (app.AppList.Count <= 1) + { + IntPtr Win = FindWindow(null, "WindowButton"); //置顶窗体 + if (Win != null && Win != IntPtr.Zero) + { + SendMessage(Win, WM_CLOSE, 0, 0); + } + } + //ChatWebSocketMiddleware.allSockets.ToList().ForEach(s => s.Send(JsonConvert.SerializeObject(app.AppList))); + //appDown(); + } + else if (type == "apptimeset") + { + //var curApp = app.NowAppList.Where(i => i.AppID == app.DefaultAppCode).FirstOrDefault(); + //if (curApp != null) + //{ + // app.configstartexe = string.IsNullOrEmpty(curApp.exestartname) ? curApp.exepath : (curApp.exepath + "/" + curApp.exestartname); + //} + //else + //{ + // app.configstartexe = ""; + //} + } + else if (type == "appclock")//打开 + { + //if (string.IsNullOrEmpty(app.AppStartinfo.exestartname)) + //{ + // killExE(); + // startexe = false; + // if (!string.IsNullOrEmpty(app.configstartexe)) + // StartExE(app.configstartexe, (app.HttpUrl.Replace("//", "|")).Split('/')[0].Replace("|", "//") + "|" + app.deviceid + "|" + app.configwebsocket + "|1"); + // if (startexe) + // app.AppPlayinfo.AppID = "1"; + + //} + //else if (!app.AppStartinfo.AppID.Equals(app.AppStartinfo.AppID)) + //{ + // string path = AppDomain.CurrentDomain.BaseDirectory + "/exefile/" + app.AppPlayDir; + // DirectoryInfo dir = new DirectoryInfo(path); + // if (dir == null) + // { + // //System.Windows.MessageBox.Show(app.AppStartinfo.exestartname + "应用程序文件不存在"); + // return; + // } + // string exepath = ""; + // ListFiles(dir, app.AppStartinfo.exestartname, ref exepath); + // if (exepath != "") + // { + // killExE(); + // startexe = false; + // StartExE(exepath); + // if (startexe) + // app.AppPlayinfo = app.AppStartinfo; + + // } + // else + // { + // //System.Windows.MessageBox.Show(app.AppStartinfo.exestartname + "文件不存在"); + // } + //} + } + else if (type.Equals("screenshot") || type.Equals("cloud-screenshot")) + { + string Mess = ""; + if (!string.IsNullOrEmpty(app.deviceid)) + { + string[] IP = app.LocalIP.Split('.'); + string imgname = app.deviceid.Replace("-", "") + System.DateTime.Now.ToString("yyMMddhhmmssffff") + ".jpg"; + string imgPath = Class_Config.PrintScreen(imgname); + httpmessage.UpLoadImg(ref Mess, imgPath, imgname, app.screenshotUserName, type.Equals("screenshot") ? "local" : "cloud"); + } + + + } + else if (type.Equals("restart")) + { + Process MyProcess = new Process(); + //设定程序名 + MyProcess.StartInfo.FileName = "cmd.exe"; + + //关闭Shell的使用 + MyProcess.StartInfo.UseShellExecute = false; + //重定向标准输入 + MyProcess.StartInfo.RedirectStandardInput = true; + //重定向标准输出 + MyProcess.StartInfo.RedirectStandardOutput = true; + //重定向错误输出 + MyProcess.StartInfo.RedirectStandardError = true; + //设置不显示窗口 + MyProcess.StartInfo.CreateNoWindow = true; + + string cmdtext = string.Empty; + cmdtext = @"Shutdown -f -r -t 0"; //重启 + + log.WriteLogFile(cmdtext, "cmdexelog"); + //执行VER命令 + MyProcess.Start(); + MyProcess.StandardInput.WriteLine(cmdtext); + log.WriteLogFile("重启", "cmdexelog"); + string output = ""; + char[] outl = new char[2048]; + string error = ""; + using (System.IO.StreamReader myOutput = MyProcess.StandardOutput) + { + myOutput.Read(outl, 0, 2048); + output = new string(outl); + log.WriteLogFile(output, "cmdexelog"); + + } + using (System.IO.StreamReader myError = MyProcess.StandardError) + { + + myError.Read(outl, 0, 1024); + error = new string(outl); + log.WriteLogFile(error, "cmdexelog"); + } + + } + else if (type.Equals("shutdown")) + { + Process MyProcess = new Process(); + //设定程序名 + MyProcess.StartInfo.FileName = "cmd.exe"; + + //关闭Shell的使用 + MyProcess.StartInfo.UseShellExecute = false; + //重定向标准输入 + MyProcess.StartInfo.RedirectStandardInput = true; + //重定向标准输出 + MyProcess.StartInfo.RedirectStandardOutput = true; + //重定向错误输出 + MyProcess.StartInfo.RedirectStandardError = true; + //设置不显示窗口 + MyProcess.StartInfo.CreateNoWindow = true; + + string cmdtext = string.Empty; + cmdtext = @"Shutdown -f -s -t 0"; //关机 + + log.WriteLogFile(cmdtext, "cmdexelog"); + //执行VER命令 + MyProcess.Start(); + MyProcess.StandardInput.WriteLine(cmdtext); + log.WriteLogFile("关机", "cmdexelog"); + string output = ""; + char[] outl = new char[2048]; + string error = ""; + using (System.IO.StreamReader myOutput = MyProcess.StandardOutput) + { + myOutput.Read(outl, 0, 2048); + output = new string(outl); + log.WriteLogFile(output, "cmdexelog"); + + } + using (System.IO.StreamReader myError = MyProcess.StandardError) + { + + myError.Read(outl, 0, 1024); + error = new string(outl); + log.WriteLogFile(error, "cmdexelog"); + + } + } + else if (type.Equals("turnoff") || type.Equals("turnofftouch")) + { + + bool is64Bit; + is64Bit = Environment.Is64BitOperatingSystem; + + int i = 0; + IntPtr p = new IntPtr(i); + string tpath = System.Environment.CurrentDirectory; + + string OKorNO = "disable"; + string systemWordLength; + //检测系统是64位还是32位 + if (is64Bit == true) + { + systemWordLength = "x64"; + } + else + { + systemWordLength = "x86"; + } + ShellExecute(p, "runas", tpath + "\\devcon\\" + systemWordLength + "\\devcon.exe", OKorNO + " *HID* /c net user administrator /active:yes", "", (int)ShowWindowCommands.SW_HIDE); + ShellExecute(p, "runas", tpath + "\\devcon\\" + systemWordLength + "\\devcon.exe", "enable HID_DEVICE_SYSTEM_MOUSE user administrator /active:yes", "", (int)ShowWindowCommands.SW_HIDE); + httpmessage.ScreenOperSuccess(0); + } + else if (type.Equals("turnon") || type.Equals("turnontouch")) + { + + bool is64Bit; + is64Bit = Environment.Is64BitOperatingSystem; + + int i = 0; + IntPtr p = new IntPtr(i); + string tpath = System.Environment.CurrentDirectory; + + string OKorNO = "enable"; + string systemWordLength; + //检测系统是64位还是32位 + if (is64Bit == true) + { + systemWordLength = "x64"; + } + else + { + systemWordLength = "x86"; + } + ShellExecute(p, "runas", tpath + "\\devcon\\" + systemWordLength + "\\devcon.exe", OKorNO + " *HID* /c net user administrator /active:yes", "", (int)ShowWindowCommands.SW_HIDE); + httpmessage.ScreenOperSuccess(1); + } + else if (type.Equals("devnumedit")) + { + DevNumEdit(); + } + else if (type.Equals("bgset")) + { + BGSet(); + } + else if (type.Equals("startexplorer")) + { + StartExplorer(); + } + else if (type.Equals("killexplorer")) + { + KillExplorer(); + } + else if (type.Equals("shutdowntime")) + { + deleteSchtasks(); + if (!string.IsNullOrEmpty(app.shutdowntime)) + { + createSchtasks(); + } + } + + + } + + + private void deleteSchtasks(string schtaskName) + { + try + { + Process MyProcess = new Process(); + //设定程序名 + MyProcess.StartInfo.FileName = "cmd.exe"; + + //关闭Shell的使用 + MyProcess.StartInfo.UseShellExecute = false; + //重定向标准输入 + MyProcess.StartInfo.RedirectStandardInput = true; + //重定向标准输出 + MyProcess.StartInfo.RedirectStandardOutput = true; + //重定向错误输出 + MyProcess.StartInfo.RedirectStandardError = true; + //设置不显示窗口 + MyProcess.StartInfo.CreateNoWindow = true; + string cmdtext = "schtasks /delete /tn " + schtaskName + " -f"; //关机 + log.WriteLogFile(cmdtext, "cmdexelog"); + + //执行VER命令 + MyProcess.Start(); + + MyProcess.StandardInput.WriteLine(cmdtext); + } + catch (Exception ex) + { + log.WriteLogFile(ex.ToString()); + } + } + + private void createSchtasks(string cmdtext) + { + try + { + Process MyProcess = new Process(); + //设定程序名 + MyProcess.StartInfo.FileName = "cmd.exe"; + + //关闭Shell的使用 + MyProcess.StartInfo.UseShellExecute = false; + //重定向标准输入 + MyProcess.StartInfo.RedirectStandardInput = true; + //重定向标准输出 + MyProcess.StartInfo.RedirectStandardOutput = true; + //重定向错误输出 + MyProcess.StartInfo.RedirectStandardError = true; + //设置不显示窗口 + MyProcess.StartInfo.CreateNoWindow = true; + + log.WriteLogFile(cmdtext, "cmdexelog"); + //执行VER命令 + MyProcess.Start(); + MyProcess.StandardInput.WriteLine(cmdtext); + } + catch (Exception ex) + { + log.WriteLogFile(ex.ToString()); + } + } + + + + /// + /// 窗体关闭事件 + /// + /// + private void WebSocketManageForLive_WebSocketReceiveEvent(string type, string message) + { + log.WriteLogFile(type, "live"); + if (type == "live")//开始下载 + { + + //app.AppPlayNameCH = "直播"; + //app.CurAppPlayName = "live"; + //MyProcessName.Add("LiveShow"); + try + { + if (app.live.OldLiveCode != app.live.LiveCode) + { + try + { + app.isLoadLive = false; + //结束进程 + IntPtr WinLiveShow = FindWindow(null, "LiveShow"); //置顶窗体 + if (WinLiveShow != null && WinLiveShow != IntPtr.Zero) + { + SendMessage(WinLiveShow, WM_CLOSE, 0, 0); + } + app.live.OldLiveCode = app.live.LiveCode; + Action UploadApp = new Action(() => + { + app.isLoadLive = true; + App.Current.Dispatcher.Invoke((Action)(() => + { + try + { + LiveShow liveShow = new LiveShow(); + liveShow.Show(); + } + catch (Exception ex) + { + log.WriteLogFile(ex.ToString(), "errorrrr"); + } + })); + }); + UploadApp.BeginInvoke(null, null); + IntPtr Win = FindWindow(null, "WindowViewNew"); //置顶窗体 + if ((Win != null && Win != IntPtr.Zero)) + { + SendMessage(Win, WM_CLOSE, 0, 0); + } + } + catch (Exception e) + { + log.WriteLogFile(e.ToString(), "liveerror"); + Thread.Sleep(1000); + app.isLoadLive = false; + //结束进程 + IntPtr WinLiveShow = FindWindow(null, "LiveShow"); //置顶窗体 + if (WinLiveShow != null && WinLiveShow != IntPtr.Zero) + { + SendMessage(WinLiveShow, WM_CLOSE, 0, 0); + } + app.live.OldLiveCode = app.live.LiveCode; + Action UploadApp = new Action(() => + { + app.isLoadLive = true; + App.Current.Dispatcher.Invoke((Action)(() => + { + try + { + LiveShow liveShow = new LiveShow(); + liveShow.Show(); + } + catch (Exception ex) + { + log.WriteLogFile(ex.ToString(), "errorrrr"); + } + })); + + }); + UploadApp.BeginInvoke(null, null); + IntPtr Win = FindWindow(null, "WindowViewNew"); //置顶窗体 + if ((Win != null && Win != IntPtr.Zero)) + { + SendMessage(Win, WM_CLOSE, 0, 0); + } + } + } + else + { + bool isStartVlc = false; + //结束进程 + IntPtr WinLiveShow = FindWindow(null, "LiveShow"); //置顶窗体 + if (WinLiveShow != null && WinLiveShow != IntPtr.Zero) + { + isStartVlc = true; + } + if (!isStartVlc && !app.isLoadLive) + { + + try + { + app.live.OldLiveCode = app.live.LiveCode; + app.isLoadLive = true; + App.Current.Dispatcher.Invoke((Action)(() => + { + try + { + LiveShow liveShow = new LiveShow(); + liveShow.Show(); + } + catch (Exception ex) + { + log.WriteLogFile(ex.ToString(), "errorrrr"); + } + })); + IntPtr Win = FindWindow(null, "WindowViewNew"); //置顶窗体 + if ((Win != null && Win != IntPtr.Zero)) + { + SendMessage(Win, WM_CLOSE, 0, 0); + } + } + catch (Exception e) + { + + log.WriteLogFile(e.ToString(), "liveerror"); + Thread.Sleep(1000); + if (!app.isLoadLive) + { + app.isLoadLive = true; + app.live.OldLiveCode = app.live.LiveCode; + App.Current.Dispatcher.Invoke((Action)(() => + { + try + { + LiveShow liveShow = new LiveShow(); + liveShow.Show(); + } + catch (Exception ex) + { + log.WriteLogFile(ex.ToString(), "errorrrr"); + } + })); + IntPtr Win = FindWindow(null, "WindowViewNew"); //置顶窗体 + if ((Win != null && Win != IntPtr.Zero)) + { + SendMessage(Win, WM_CLOSE, 0, 0); + } + } + } + } + else + { + if (app.live.HFilePath != app.curLive.hFilePath) + { + app.curLive.hFilePath = app.live.HFilePath; + var model = new { Type = "ADImage", Parameter = app.live.HFilePath }; + byte[] data = Encoding.Default.GetBytes(JsonConvert.SerializeObject(model)); + //6、发送消息 + socket.Send(data, 0, data.Length, SocketFlags.None); //指定套接字的发送行为 + } + if (socket.Connected)//判断客户端是否还在连接 + { + app.curLive.vFilePath = app.live.VFilePath; + var model = new { Type = "Image", Parameter = string.Join(";", app.live.VFilePath) }; + byte[] data = Encoding.Default.GetBytes(JsonConvert.SerializeObject(model)); + //6、发送消息 + socket.Send(data, 0, data.Length, SocketFlags.None); //指定套接字的发送行为 + } + //bool isReload = false; + //if (SystemParameters.PrimaryScreenWidth > SystemParameters.PrimaryScreenHeight) + //{ + // if (!string.IsNullOrEmpty(app.live.HFilePath)) + // { + // isReload = true; + // } + // else + // { + // //app.LiveReload = true; + // } + //} + //else + //{ + // if (!string.IsNullOrEmpty(app.live.VFilePath)) + // { + // isReload = true; + // } + // else + // { + // } + //} + + } + + } + } + catch (Exception e) + { + + log.WriteLogFile(e.ToString(), "liveerror"); + + } + } + else if (type == "shutdownlive") + { + + try + { + //IntPtr Win = FindWindow(null, "WindowView"); //置顶窗体 + //if ((Win == null || Win == IntPtr.Zero)) + //{ + + //} + + + app.isLoadLive = false; + //结束进程 + IntPtr WinLive = FindWindow(null, "LiveShow"); //置顶窗体 + if (WinLive != null && WinLive != IntPtr.Zero) + { + Action UploadApp = new Action(() => + { + App.Current.Dispatcher.Invoke((Action)(() => + { + try + { + app.AppPlayNameCH = "信息发布"; + app.CurAppPlayName = "pcscreensavers"; + app.Appversion = app.Containerversion; + MyProcessName.Add("WindowView"); + WindowViewNew windowView = new WindowViewNew(0); + windowView.Show(); + } + catch (Exception ex) + { + log.WriteLogFile(ex.ToString(), "errorrrr"); + } + })); + }); + UploadApp.BeginInvoke(null, null); + + SendMessage(WinLive, WM_CLOSE, 0, 0); + + + } + //结束进程 + //IntPtr WinLivePage = FindWindow(null, "LivePage"); //置顶窗体 + //if (WinLivePage != null && WinLivePage != IntPtr.Zero) + //{ + // SendMessage(WinLivePage, WM_CLOSE, 0, 0); + //} + IntPtr WindowView = FindWindow(null, "WindowViewNew"); //置顶窗体 + if ((WindowView != null && WindowView != IntPtr.Zero)) + { + SetWindowPos(WindowView, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE); + } + + } + catch (Exception ex) + { + + log.WriteLogFile(ex.ToString(), "shutdownliveerror"); + } + } + else if (type == "livecoupon" || type == "getcoupon" || type == "shutdowncoupon") + { + if (socket.Connected)//判断客户端是否还在连接 + { + var model = new { Type = type }; + byte[] data = Encoding.Default.GetBytes(JsonConvert.SerializeObject(model)); + //6、发送消息 + socket.Send(data, 0, data.Length, SocketFlags.None); //指定套接字的发送行为 + } + } + else if (type == "like" || type == "watchnum") + { + if (socket.Connected)//判断客户端是否还在连接 + { + var model = new { Type = type, Parameter = new { likes = app.live.Likes, watchNum = app.live.WatchNum } }; + byte[] data = Encoding.Default.GetBytes(JsonConvert.SerializeObject(model)); + //6、发送消息 + socket.Send(data, 0, data.Length, SocketFlags.None); //指定套接字的发送行为 + } + //if (app.curLive != null) + //{ + // app.curLive.likes = app.live.Likes; + // app.curLive.watchNum = app.live.WatchNum; + //} + //log.WriteLogFile(ChatWebSocketServicesFoH5.allSockets.Count.ToString() + "like个数", "111"); + //ChatWebSocketServicesFoH5.allSockets.ToList().ForEach(s => s.Send("like")); + } + else if (type == "playprog") + { + + //结束进程 + IntPtr WinLive = FindWindow(null, "LiveShow"); //置顶窗体 + if (WinLive != null && WinLive != IntPtr.Zero) + { + app.isLoadLive = false; + SendMessage(WinLive, WM_CLOSE, 0, 0); + } + //结束进程 + //IntPtr WinLivePage = FindWindow(null, "LivePage"); //置顶窗体 + //if (WinLivePage != null && WinLivePage != IntPtr.Zero) + //{ + // SendMessage(WinLivePage, WM_CLOSE, 0, 0); + //} + + IntPtr brandWin = FindWindow(null, "BrandProg"); //置顶窗体 + if ((brandWin == null || brandWin == IntPtr.Zero)) + { + Action UploadApp = new Action(() => + { + App.Current.Dispatcher.Invoke((Action)(() => + { + try + { + BrandProg prog = new BrandProg(); + prog.Show(); + } + catch (Exception ex) + { + log.WriteLogFile(ex.ToString(), "errorrrr"); + } + })); + }); + UploadApp.BeginInvoke(null, null); + } + + + IntPtr Win = FindWindow(null, "WindowViewNew"); //置顶窗体 + if ((Win != null && Win != IntPtr.Zero)) + { + SendMessage(Win, WM_CLOSE, 0, 0); + } + + + + //if (socket.Connected)//判断客户端是否还在连接 + //{ + // var model = new { Type = type }; + // byte[] data = Encoding.Default.GetBytes(JsonConvert.SerializeObject(model)); + // //6、发送消息 + // socket.Send(data, 0, data.Length, SocketFlags.None); //指定套接字的发送行为 + //} + } + else if (type == "shutdownprog") + { + + } + } + + + + + + + + + private void MainWindow_Closed(object sender, EventArgs e) + { + try + { + isStop = true; + StartExplorer(); + deleteSchtasks(); + killExE(); + Process[] process = Process.GetProcesses(); + foreach (Process prc in process) + { + if (prc.ProcessName.Equals(System.Diagnostics.Process.GetCurrentProcess().ProcessName)) + prc.Kill(); + } + } + catch (Exception) + { + Process[] process = Process.GetProcesses(); + foreach (Process prc in process) + { + if (prc.ProcessName == "Container") + prc.CloseMainWindow(); + } + } + } + + /// + /// 打开客户定制节目组应用程序 + /// 应用程序地址 + /// + private void StartCScreen() + { + try + { + string path = Environment.CurrentDirectory + "/CScreen/ScreenSavers.exe"; + if (!File.Exists(path)) + { + return; + } + Process myprocess = new Process(); + ProcessStartInfo startInfo = new ProcessStartInfo(path); + startInfo.Verb = "runas"; + startInfo.CreateNoWindow = true; + path = path.Replace("\\", "/"); + startInfo.WorkingDirectory = path.Substring(0, path.LastIndexOf("/"));//设置应用程序在其所在目录 + myprocess.StartInfo = startInfo; + myprocess.StartInfo.UseShellExecute = false; + myprocess.Start(); + + } + catch (Exception ex) + { + log.WriteLogFile(ex.ToString()); + //this.Openexe.Visible = true; + startexe = false; + //System.Windows.MessageBox.Show("应用程序打开失败:" + ex.ToString()); + + } + + } + /// + /// 打开外部exe应用程序 + /// 应用程序地址 + /// + private void StartExE(string path, string param = "") + { + try + { + timer.Stop(); + if (!File.Exists(path) && !path.StartsWith("http:")) + { + if (!File.Exists(System.Windows.Forms.Application.ExecutablePath.Replace("\\", "/").Substring(0, System.Windows.Forms.Application.ExecutablePath.Replace("\\", "/").LastIndexOf("/")) + path)) + { + OnReLoginClick(null, null); + startexe = false; + return; + } + else + { + path = System.Windows.Forms.Application.ExecutablePath.Replace("\\", "/").Substring(0, System.Windows.Forms.Application.ExecutablePath.Replace("\\", "/").LastIndexOf("/")) + path; + } + } + log.WriteLogFile(path.Substring(path.Length - 4, 4).ToLower(), "startlog"); + if (path.Substring(path.Length - 4, 4).ToLower().Equals(".bat")) + { + param = ""; + Process myprocess = new Process(); + ProcessStartInfo startInfo = new ProcessStartInfo(path, param); + startInfo.Verb = "runas"; + startInfo.CreateNoWindow = true; + path = path.Replace("\\", "/"); + startInfo.WorkingDirectory = path.Substring(0, path.LastIndexOf("/"));//设置应用程序在其所在目录 + myprocess.StartInfo = startInfo; + myprocess.StartInfo.UseShellExecute = false; + myprocess.StartInfo.CreateNoWindow = true; + myprocess.Start(); + MyProcessName.Add("chrome"); + app.AppPlayName = "chrome"; + app.CurAppPlayName = app.AppPlayName; + app.NowAppType = "bat"; + startexe = true; + timer.Start(); + log.WriteLogFile("打开成功", "startlog"); + } + else + { + Process myprocess = new Process(); + ProcessStartInfo startInfo = new ProcessStartInfo(path, param); + path = path.Replace("\\", "/"); + startInfo.WorkingDirectory = path.Substring(0, path.LastIndexOf("/"));//设置应用程序在其所在目录 + startInfo.Verb = "runas"; + startInfo.CreateNoWindow = true; + myprocess.StartInfo = startInfo; + myprocess.StartInfo.UseShellExecute = false; + myprocess.StartInfo.CreateNoWindow = true; + myprocess.Start(); + MyProcessName.Add(myprocess.ProcessName); + app.AppPlayName = myprocess.ProcessName; + app.CurAppPlayName = myprocess.ProcessName; + app.NowAppType = "exe"; + startexe = true; + timer.Start(); + } + + } + catch (Exception ex) + { + log.WriteLogFile(ex.ToString()); + startexe = false; + + } + + } + /// + /// 关闭已打开外部应用程序 + /// + private void killExE() + { + try + { + if (app.NowAppType == "exe") + { + Process[] pro = Process.GetProcesses(); + for (int i = 0; i < pro.Length; i++) + { + //log.WriteLogFile(pro[i].ProcessName.ToLower()); + if (pro[i].ProcessName.ToLower() == app.AppPlayName.ToLower()) + { + pro[i].Kill();//结束进程 + + app.AppPlayName = ""; + app.CurAppPlayName = app.AppPlayName; + app.NowAppType = ""; + if (MyProcessName.Count > 0) + MyProcessName.RemoveAt(0);//移除进程列表中的元素 + return; + } + } + } + } + catch (Exception ex) + { + log.WriteLogFile(ex.ToString()); + + } + } + + /// + /// 删除每日定时关机任务 + /// + private void deleteSchtasks() + { + try + { + Process MyProcess = new Process(); + //设定程序名 + MyProcess.StartInfo.FileName = "cmd.exe"; + + //关闭Shell的使用 + MyProcess.StartInfo.UseShellExecute = false; + //重定向标准输入 + MyProcess.StartInfo.RedirectStandardInput = true; + //重定向标准输出 + MyProcess.StartInfo.RedirectStandardOutput = true; + //重定向错误输出 + MyProcess.StartInfo.RedirectStandardError = true; + //设置不显示窗口 + MyProcess.StartInfo.CreateNoWindow = true; + string cmdtext = "schtasks /delete /tn shutdownWindows -f"; //关机 + log.WriteLogFile(cmdtext, "cmdexelog"); + + //执行VER命令 + MyProcess.Start(); + + MyProcess.StandardInput.WriteLine(cmdtext); + } + catch (Exception ex) + { + log.WriteLogFile(ex.ToString()); + } + } + private void createSchtasks() + { + try + { + Process MyProcess = new Process(); + //设定程序名 + MyProcess.StartInfo.FileName = "cmd.exe"; + + //关闭Shell的使用 + MyProcess.StartInfo.UseShellExecute = false; + //重定向标准输入 + MyProcess.StartInfo.RedirectStandardInput = true; + //重定向标准输出 + MyProcess.StartInfo.RedirectStandardOutput = true; + //重定向错误输出 + MyProcess.StartInfo.RedirectStandardError = true; + //设置不显示窗口 + MyProcess.StartInfo.CreateNoWindow = true; + + string cmdtext = string.Empty; + cmdtext = "schtasks /create /tn shutdownWindows /sc DAILY /st " + app.shutdowntime + " /tr \"shutdown -s -f -t 0\" -f"; //关机 + + log.WriteLogFile(cmdtext, "cmdexelog"); + //执行VER命令 + MyProcess.Start(); + MyProcess.StandardInput.WriteLine(cmdtext); + } + catch (Exception ex) + { + log.WriteLogFile(ex.ToString()); + } + } + + /// + /// 下载应用程序 + /// + private void downLineExE() + { + log.WriteLogFile("开始下载"); + //try + //{ + // string error = ""; + // // + // string filename = ""; + // app.appUrl = app.appUrl.Replace("\\", "/"); + // if (string.IsNullOrEmpty(app.appUrl) && (app.Appdowninfo.exestartname.IndexOf("http://") == 0 || app.Appdowninfo.exestartname.IndexOf("https://") == 0)) + // { + // filename = app.Appdowninfo.exename + ".bat"; + // } + // else if (app.appUrl.Contains("/")) + // filename = app.appUrl.Substring(app.appUrl.LastIndexOf("/")); + // if (string.IsNullOrEmpty(filename)) + // { + // return; + // } + // string exename = app.appName; + // string path = AppDomain.CurrentDomain.BaseDirectory + "/exefile/" + filename; + // if (app.Appdowninfo.Default) + // { + // timer.Start(); + // app.defaultFile = app.Appdowninfo.exename; + // } + // if (!Directory.Exists(path) || app.AppUpdate == true) + // { + // List AppList = new List(); + // Class_Config config = new Class_Config(); + // config.ReadAppInfo(ref AppList); + // exename = httpmessage.DownLoadexe(AppList, ref error);//正式使用下载 + // IntPtr WindowAppChoose = FindWindow(null, "WindowAppChoose"); + // if (WindowAppChoose != null) + // { + // SetWindowPos(WindowAppChoose, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE); + // SendMessage(WindowAppChoose, WM_CLOSE, 0, 0); // 调用了 发送消息 发送关闭窗口的消息 + // } + // if (app.Appdowninfo.Default) + // { + // app.AppPlayName = app.Appdowninfo.exename; + // } + // //if (!string.IsNullOrEmpty(exename)) + // //{ + // // //下载成功 + // // httpmessage.UpLoadDownLoadState(ref error, "1"); + // //} + // //else + // //{ + // // //下载失败 + // // log.WriteLogFile(error); + // // httpmessage.UpLoadDownLoadState(ref error, "2"); + // //} + // } + //} + //catch (Exception ex) + //{ + // log.WriteLogFile(ex.ToString()); + + //} + } + + private void appDown() + { + //try + //{ + // if (config.RemoveExeConfig(app.AppDownCode)) + // { + // Class_Config config = new Class_Config(); + // config.ReadAppInfo(ref app.NowAppList); + // if (app.NowAppList == null || app.NowAppList.Count == 0) + // { + // app.configstartexe = ""; + // IntPtr WindowAppChoose = FindWindow(null, "WindowAppChoose"); + // if (WindowAppChoose != null || WindowAppChoose.ToString() != "0") + // { + // SetWindowPos(WindowAppChoose, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE); + // SendMessage(WindowAppChoose, WM_CLOSE, 0, 0); // 调用了 发送消息 发送关闭窗口的消息 + // } + // IntPtr WinButton = FindWindow(null, "WindowButton"); + // if (WinButton != null || WindowAppChoose.ToString() != "0") + // { + // SetWindowPos(WinButton, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE); + // SendMessage(WinButton, WM_CLOSE, 0, 0); // 调用了 发送消息 发送关闭窗口的消息 + // } + // } + // else + // { + // var curApp = app.NowAppList.Where(i => i.AppID == app.DefaultAppCode).FirstOrDefault(); + + // if (curApp != null) + // { + // app.configstartexe = string.IsNullOrEmpty(curApp.exestartname) ? curApp.exepath : (curApp.exepath + "/" + curApp.exestartname); + // } + // else + // { + // app.configstartexe = ""; + // } + // IntPtr WindowAppChoose = FindWindow(null, "WindowAppChoose"); + // if (WindowAppChoose != null || WindowAppChoose.ToString() != "0") + // { + // SetWindowPos(WindowAppChoose, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE); + // SendMessage(WindowAppChoose, WM_CLOSE, 0, 0); // 调用了 发送消息 发送关闭窗口的消息 + // } + // } + // log.WriteLogFile("卸载应用成功"); + // } + // else + // { + // log.WriteLogFile("卸载应用失败"); + // } + //} + //catch (Exception ex) + //{ + // log.WriteLogFile(ex.ToString()); + + //} + } + + /// + /// 遍历文件夹判断应用程序是否存在,若存在则返回Path为打开的应用程序路径 + /// 文件夹路径 + /// 应用程序名称 + /// 返回:应用程序路径 + /// + public void ListFiles(FileSystemInfo info, string name, ref string Path) + { + try + { + if (!info.Exists) return; + DirectoryInfo dir = info as DirectoryInfo; + //不是目录 + if (dir == null) return; + FileSystemInfo[] files = dir.GetFileSystemInfos(); + for (int i = 0; i < files.Length; i++) + { + FileInfo file = files[i] as FileInfo; + //是文件 + if (file != null) + { + if (file.Name.Trim().ToLower().Equals(name)) + { + Path = file.FullName; + return; + } + } + //对于子目录,进行递归调用 + //else + ListFiles(files[i], name, ref Path); + } + } + catch (Exception ex) + { + log.WriteLogFile(ex.ToString()); + + } + } + + #region Notification Icon 右下角图标事件 + + bool shouldClose; + WindowState lastWindowState; + + protected override void OnStateChanged(EventArgs e) + { + try + { + this.lastWindowState = WindowState; + } + catch + { } + } + + protected override void OnClosing(System.ComponentModel.CancelEventArgs e) + { + try + { + if (!shouldClose) + { + e.Cancel = true; + Hide(); + } + } + catch { } + } + + private void Open() + { + try + { + Show(); + this.WindowState = WindowState.Normal; + } + catch + { } + } + + + //双击还原 + private void OnNotificationAreaIconDoubleClick(object sender, MouseButtonEventArgs e) + { + try + { + if (e.ChangedButton == MouseButton.Left) + { + Open(); + } + } + catch + { + } + } + + //re-login + + private void OnReLoginClick(object sender, EventArgs e) + { + try + { + ////this.Logout(); + //failopen.Visibility = Visibility.Visible; + //sucessopen.Visibility = Visibility.Hidden; + //Open(); + } + catch + { + } + } + + private void OnMenuItemExitClick(object sender, EventArgs e) + { + try + { + this.shouldClose = true; + Close(); + } + catch { } + } + + #endregion + + //private void Text_Focus(object sender, RoutedEventArgs e) + //{ + // OpenFileDialog openExcel = new OpenFileDialog();//实例化打开对话框对象 + // openExcel.Filter = "可执行文件|*.exe";//设置打开文件筛选器 + // openExcel.Multiselect = false;//设置打开对话框中不能多选 + // if (openExcel.ShowDialog() != System.Windows.Forms.DialogResult.OK)//判断是否选择了文件 + // { + // return; + // } + // Textpath.Text = openExcel.FileName; + //} + + //private void Btn_Click(object sender, RoutedEventArgs e) + //{ + // StartExE(Textpath.Text.ToString()); + //} + + private void Btn_OK(object sender, RoutedEventArgs e) + { + this.WindowState = WindowState.Minimized; + } + + #region 检测鼠标动作 设置屏保 + //定义结构体 + [StructLayout(LayoutKind.Sequential)] + struct LASTINPUTINFO + { + // 设置结构体块容量 + [MarshalAs(UnmanagedType.U4)] + public int cbSize; + // 捕获的时间 + [MarshalAs(UnmanagedType.U4)] + public uint dwTime; + } + + // 定义定时器,结构体对象等 + + //private DispatcherTimer mIdleTimer; + private LASTINPUTINFO mLastInputInfo; + + [DllImport("user32.dll")] + private static extern bool GetLastInputInfo(ref LASTINPUTINFO plii); + + public static readonly IntPtr HWND_TOPMOST = new IntPtr(-1); //窗体置顶 + public static readonly IntPtr HWND_NOTOPMOST = new IntPtr(-2); //取消窗体置顶 + public static readonly IntPtr HWND_BOTTOM = new IntPtr(1); //取消窗体置顶 + public const uint SWP_NOMOVE = 0x0002; //不调整窗体位置 + public const uint SWP_NOSIZE = 0x0001; //不调整窗体大小 + + + public enum ShowWindowCommands : int + { + + SW_HIDE = 0, + SW_SHOWNORMAL = 1, + SW_NORMAL = 1, + SW_SHOWMINIMIZED = 2, + SW_SHOWMAXIMIZED = 3, + SW_MAXIMIZE = 3, + SW_SHOWNOACTIVATE = 4, + SW_SHOW = 5, + SW_MINIMIZE = 6, + SW_SHOWMINNOACTIVE = 7, + SW_SHOWNA = 8, + SW_RESTORE = 9, + SW_SHOWDEFAULT = 10, + SW_MAX = 10 + } + + /*初始化 + mLastInputInfo = new LASTINPUTINFO(); + mLastInputInfo.cbSize = Marshal.SizeOf(mLastInputInfo); + + mIdleTimer = new System.Windows.Threading.DispatcherTimer(); + mIdleTimer.Tick += new EventHandler(IdleTime);//起个Timer一直获取当前时间 + mIdleTimer.Interval = new TimeSpan(0, 0, 0, 1, 0); + mIdleTimer.Start(); + */ + bool ScreenSaver = false; + //实现 屏保开启或关闭线程 + private void IdleTime(object sender, EventArgs e) + { + //if (isExecutionOpenApp) + //{ + // log.WriteLogFile("正在执行打开应用操作isExecutionOpenApp", "OpenApp"); + // goto DonotDone; + //} + if (GetLastInputInfo(ref mLastInputInfo)) + { + //if (ConfigurationManager.AppSettings["isScreensaverOpen"].Equals("0")) + //{ + if (ScreenSaver) + { + //Process[] proSc = Process.GetProcesses(); + bool pcstart = false; + //for (int i = 0; i < proSc.Length; i++) + //{ + // if (proSc[i].ProcessName.ToLower().Trim() == "pcscreensavers") + // { + // pcstart = true; + // } + //} + IntPtr Win = FindWindow(null, "WindowViewNew");//设置置顶 + if (Win != null && Win != IntPtr.Zero) + { + pcstart = true; + //SetWindowPos(Win, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE); + } + if (!pcstart && !app.isStartScreen) + { + ScreenSaver = pcstart; + log.WriteLogFile("ScreenSaver =" + ScreenSaver.ToString()); + } + else + { + //鼠标操作,切换应用 + if ((Environment.TickCount - (long)mLastInputInfo.dwTime) / 1000 < 2) + { + log.WriteLogFile("(Environment.TickCount - (long)mLastInputInfo.dwTime) / 1000 =" + ((Environment.TickCount - (long)mLastInputInfo.dwTime) / 1000).ToString()); + try + { + app.isStartScreen = false; + //关闭信息发布 + Process[] pro = Process.GetProcesses(); + //for (int i = 0; i < pro.Length; i++) + //{ + // if (pro[i].ProcessName.ToLower().Trim() == "pcscreensavers") + // { + // pro[i].Kill();//结束进程 + // } + //} + IntPtr Win1 = FindWindow(null, "WindowViewNew");//设置置顶 + if (Win1 != null && Win1 != IntPtr.Zero) + { + SendMessage(Win1, WM_CLOSE, 0, 0); + app.AppPlayNameCH = "导视"; + app.Appversion = app.kioskVersion; + //SetWindowPos(Win, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE); + } + for (int i = 0; i < pro.Length; i++) + { + if (pro[i].ProcessName.ToLower().Trim() == "screensavers") + { + pro[i].Kill();//结束进程 + } + } + + for (int j = 0; j < MyProcessName.Count; j++) + { + if (MyProcessName[j].Trim().ToLower().Equals("windowview")) + { + MyProcessName.RemoveAt(j); + //break; + } + }//移除进程列表中的元素 + ScreenSaver = false; + app.CurAppPlayName = app.AppPlayName; + log.WriteLogFile(app.CurAppPlayName + "-----", "start"); + //if (ConfigurationManager.AppSettings["MenuShow"].Equals("0")) //判断是否有悬浮框 + //{ + if (app.AppList != null && app.AppList.Count > 1) + { + + IntPtr WinButton = FindWindow(null, "WindowButton"); //置顶窗体 + if (WinButton != null && WinButton != IntPtr.Zero) + { + SetWindowPos(WinButton, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE); + IntPtr WinChoose = FindWindow(null, "WindowAppChoose"); //置顶窗体 + if (WinChoose != null) + { + SetWindowPos(WinChoose, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE); + } + } + else + { + WindowButton win = new WindowButton(); + win.Show(); + } + + } + //} + } + catch (Exception ex) + { + log.WriteLogFile(ex.ToString()); + } + } + } + } + else + { + log.WriteLogFile(app.CurAppPlayName, "start"); + if (!app.CurAppPlayName.Trim().ToLower().Equals("pcscreensavers")) + { + + //if ((Environment.TickCount - (long)mLastInputInfo.dwTime) / 1000 > 30) + if ((Environment.TickCount - (long)mLastInputInfo.dwTime) / 1000 > app.screensaver.ScreenTime - 5) //&& (Environment.TickCount - (long)mLastInputInfo.dwTime) / 1000 < 60 + { + log.WriteLogFile("(Environment.TickCount - (long)mLastInputInfo.dwTime) / 1000 =" + ((Environment.TickCount - (long)mLastInputInfo.dwTime) / 1000).ToString()); + + try + { + //if (ConfigurationManager.AppSettings["MenuShow"].Equals("0")) //判断是否有悬浮框 + //{ + log.WriteLogFile("1430行取消置顶" + app.AppList.Count); + //if(app.AppPlayinfo) + if (app.NowNeedPlayApp != null) + { + if (app.AppPlayinfo == null || app.AppPlayinfo.Name != app.NowNeedPlayApp.Name) + { + ChangeExE(app.NowNeedPlayApp.Startup, (app.HttpUrl.Replace("//", "|")).Split('/')[0].Replace("|", "//") + "|" + app.deviceid + "|" + app.configwebsocket + "|"); + app.AppPlayinfo = app.NowNeedPlayApp; + + } + } + else if (string.IsNullOrEmpty(app.AppPlayName)) + { + killExE(); + if (!string.IsNullOrEmpty(app.configstartexe)) + { + ChangeExE(app.configstartexe, (app.HttpUrl.Replace("//", "|")).Split('/')[0].Replace("|", "//") + "|" + app.deviceid + "|" + app.configwebsocket + "|"); + } + app.AppPlayinfo = null; + } + if (app.AppList != null && app.AppList.Count > 1) + { + IntPtr Win1 = FindWindow(null, "WindowButton"); //取消置顶 + if (Win1 != null) + { + SetWindowPos(Win1, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE); + } + + Win1 = FindWindow(null, "WindowAppChoose"); //取消置顶 + if (Win1 != null) + { + SetWindowPos(Win1, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE); + } + //} + } + } + catch (Exception ex) + { + log.WriteLogFile(ex.ToString()); + } + bool ispc = false;//pcscreensavers是否以打开 + bool issc = false;//screensavers是否以打开 + Process[] pro = Process.GetProcesses(); + IntPtr Win = FindWindow(null, "WindowViewNew");//设置置顶 + if (Win != null && Win != IntPtr.Zero) + { + ispc = true; + //SetWindowPos(Win, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE); + } + //for (int i = 0; i < pro.Length; i++) + //{ + // if (pro[i].ProcessName.ToLower().Trim() == "pcscreensavers") + // { + // ispc = true; + // } + //} + + for (int i = 0; i < pro.Length; i++) + { + if (pro[i].ProcessName.ToLower().Trim() == "screensavers") + { + issc = true; + } + } + //打开信息发布 + try + { + if (!issc) + { + StartCScreen(); + } + if (!ispc) + { + //string path = @"exefile\PCScreen\PCScreenSavers.exe"; + //Process myprocess = new Process(); + //ProcessStartInfo startInfo = new ProcessStartInfo(path, (app.HttpUrl.Replace("//", "|")).Split('/')[0].Replace("|", "//") + "|" + app.deviceid + "|" + app.configwebsocket+"|0"); + //path = path.Replace("\\", "/"); + //startInfo.Verb = "runas"; + //startInfo.CreateNoWindow = true; + //startInfo.WorkingDirectory = path.Substring(0, path.LastIndexOf("/"));//设置应用程序在其所在目录 + //myprocess.StartInfo = startInfo; + //myprocess.StartInfo.UseShellExecute = false; + //myprocess.Start(); + // MyProcessName.Add(myprocess.ProcessName); + app.isStartScreen = true; + ScreenSaver = true; + //ScreenSavers result = pbm.GetResourceForLoad(); + //if (result != null && result.ResList.Count > 0) + //{ + // app.AppPlayNameCH = "信息发布"; + // app.CurAppPlayName = "pcscreensavers"; + // app.Appversion = app.Containerversion; + // MyProcessName.Add("WindowView"); + + WindowViewNew windowView = new WindowViewNew(); + windowView.Show(); + + //} + } + // ScreenSaver = true; + + + log.WriteLogFile("打开屏保成功"); + } + catch (Exception ex) + { + log.WriteLogFile("打开屏保失败" + ex.ToString()); + } + } + + } + } + //} + //if (app.appClick) + //{ + // if ((Environment.TickCount - (long)mLastInputInfo.dwTime) / 1000 >= (app.screenTime+30)) + // { + // if (!string.IsNullOrEmpty(app.NowAppName)) + // { + // if (app.NowAppName != app.AppPlayinfo.Name) + // { + // //打开应用 + // IEnumerable exeinfo = app.AppList.Where(i => i.Name.ToString() == app.NowAppName); + // if (exeinfo.Count() > 0) + // { + + // // + // //log.WriteLogFile(exeinfo.Count().ToString()); + // if (app.NowAppType != "bat" && app.NowAppType != "") + // { + // killExE(); + // } + // //else if (app.NowAppType == "html") + // //{ + // // app.winh5.WinClose(); + // // //app.winh5 = null; + // //} + // string fileName = exeinfo.ElementAt(0).Startup; + // //if (string.IsNullOrEmpty(exeinfo.ElementAt(0).exestartname)) { + // // fileName = exeinfo.ElementAt(0).exepath; + // //} else { + // // fileName = exeinfo.ElementAt(0).exepath + "/" + exeinfo.ElementAt(0).exestartname; + // //} + // if (ChangeExE(fileName, exeinfo.ElementAt(0))) + // { + + // app.AppPlayinfo = exeinfo.ElementAt(0); + // app.AppPlayNameCH = ""; + // app.Appversion = ""; + + // } + // else + // { + // app.AppPlayName = ""; + // app.AppPlayNameCH = ""; + // app.Appversion = ""; + // //打开失败 + // } + // app.appClick = false; + // } + // } + // } + // } + //} + } + + //DonotDone: + // return; + + } + #endregion + [DllImport("User32.dll", EntryPoint = "SendMessage")] + public static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam); + + //关屏 + [DllImport("user32.dll")] + private static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, int wParam, int lParam); + + [DllImport("shell32.dll")] + public extern static IntPtr ShellExecute(IntPtr hwnd, + string lpOperation, + string lpFile, + string lpParameters, + string lpDirectory, + int nShowCmd + ); + + //锁屏 + [DllImport("user32.dll")] + public static extern bool LockWorkStation(); + + + private void DevNumEdit() + { + try + { + if (config.UpdateConfig(app.devicemark)) + { + log.WriteLogFile("修改设备名称成功"); + } + else + { + log.WriteLogFile("修改设备名称失败"); + } + } + catch (Exception ex) + { + log.WriteLogFile(ex.ToString()); + + } + } + + private void BGSet() + { + try + { + string filefolder = AppDomain.CurrentDomain.BaseDirectory + "/bgfile"; + try + { + if (!Directory.Exists(filefolder)) + { + DirectoryInfo directoryInfo = new DirectoryInfo(filefolder); + directoryInfo.Create(); + } + } + catch (Exception ex) + { + log.WriteLogFile(ex.ToString()); + + } + HttpClient httpClient = new HttpClient(); + string fileName = ""; + if (httpClient.DownLoadImage(app.bgPath, "bgfile", ref fileName)) + { + if (app.pageBg == null) + { + app.pageBg = new BGPage(); + app.pageBg.LoadImage(fileName); + app.pageBg.Show(); + } + else + { + this.Dispatcher.Invoke(new Action(() => + { + app.pageBg.LoadImage(fileName); + })); + } + //this.Dispatcher.Invoke(new Action(() => + //{ + // ADInsert adView = new ADInsert(); + // adView.SetADImage(fileName, app.insertAD.Duration); + // adView.Show(); + // log.WriteLogFile("插播下载成功"); + //})); + //Process[] proSc = Process.GetProcesses(); + //bool pcstart = false; + //for (int i = 0; i < proSc.Length; i++) + //{ + // if (proSc[i].ProcessName.ToLower().Trim() == "pcscreensavers") + // { + // pcstart = true; + // break; + // } + //} + //IntPtr Win1 = FindWindow(null, "ADInsert");//设置置顶 + //if (pcstart) + //{ + // if (Win1 != null) + // { + // log.WriteLogFile("插播置顶:"); + // SetWindowPos(Win1, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE); + // } + //} + //else + //{ + // if (Win1 != null) + // { + // SetWindowPos(Win1, HWND_BOTTOM, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE); + // } + + //} + } + else + { + log.WriteLogFile("插播下载失败"); + } + } + catch (Exception ex) + { + log.WriteLogFile(ex.ToString()); + + } + } + private void KillExplorer() + { + try + { + Process MyProcess = new Process(); + //设定程序名 + MyProcess.StartInfo.FileName = "cmd.exe"; + + //关闭Shell的使用 + MyProcess.StartInfo.UseShellExecute = false; + //重定向标准输入 + MyProcess.StartInfo.RedirectStandardInput = true; + //重定向标准输出 + MyProcess.StartInfo.RedirectStandardOutput = true; + //重定向错误输出 + MyProcess.StartInfo.RedirectStandardError = true; + MyProcess.StartInfo.CreateNoWindow = true; + MyProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;//隐藏控制台窗口 + //设置不显示窗口 + MyProcess.StartInfo.CreateNoWindow = true; + string cmdtext = "taskkill /im explorer.exe /t /f"; //关闭explorer(桌面进程)进程 + log.WriteLogFile(cmdtext, "cmdexelog"); + + //执行VER命令 + MyProcess.Start(); + + MyProcess.StandardInput.WriteLine(cmdtext); + } + catch (Exception ex) + { + log.WriteLogFile(ex.ToString()); + } + } + + + private void StartExplorer() + { + //log.WriteLogFile(Environment.GetEnvironmentVariable("windir") + "\\explorer.exe", "explorer"); + //System.Diagnostics.Process process = new System.Diagnostics.Process(); + //System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo(); + //startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; + //startInfo.FileName = "cmd.exe"; + //process.StartInfo = startInfo; + //process.StartInfo.RedirectStandardInput = true; + //process.StartInfo.RedirectStandardOutput = true; + //process.StartInfo.UseShellExecute = false; + //process.Start(); + //process.StandardInput.WriteLine(Environment.GetEnvironmentVariable("windir") + "\\explorer.exe"); + //process.StandardInput.Flush(); + //process.StandardInput.Close(); + //process.WaitForExit(); + //ShellExecute(IntPtr.Zero, null, "explorer.exe", null, null, (int)ShowWindowCommands.SW_HIDE); + } + + } +} diff --git a/Container/Model/BuildingModel.cs b/Container/Model/BuildingModel.cs new file mode 100644 index 0000000..20aafd6 --- /dev/null +++ b/Container/Model/BuildingModel.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Container.Model +{ + public class BuildingModel + { + public int ID { set; get; } //楼栋ID + public string BNAME { set; get; } //名称 + } +} diff --git a/Container/Model/ExeModel.cs b/Container/Model/ExeModel.cs new file mode 100644 index 0000000..9cefdad --- /dev/null +++ b/Container/Model/ExeModel.cs @@ -0,0 +1,30 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Runtime.Serialization.Formatters.Binary; +using System.Text; +using System.Threading.Tasks; + +namespace Container.Model +{ + public class ExeModel + { + //应用名称 + public string exename { get; set; } + //启动项名称 + public string exestartname { get; set; } + //应用文件夹路径名称 + public string exepath { get; set; } + //图标路径 + public string icopath { get; set; } + //应用ID + public string AppID { get; set; } + + public string Version { get; set; } + + public bool Default { get; set; } + } + + +} diff --git a/Container/Model/FloorModel.cs b/Container/Model/FloorModel.cs new file mode 100644 index 0000000..8d240db --- /dev/null +++ b/Container/Model/FloorModel.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Container.Model +{ + class FloorModel + { + public int ID { set; get; } //楼层ID + public string FNAME { set; get; } //名称 + } +} diff --git a/Container/Model/InsertADModel.cs b/Container/Model/InsertADModel.cs new file mode 100644 index 0000000..e822359 --- /dev/null +++ b/Container/Model/InsertADModel.cs @@ -0,0 +1,104 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Container.Model +{ + public class InsertADModel + { + + public string FilePath { set; get; } //文件地址 + public int Duration { set; get; } //时长 + } + + public class Live + { + public string LiveUrl { get; set; } + + public string HFilePath { get; set; } + + public List VFilePath { get; set; } + + public string MallCode { get; set; } + + public string MallName { get; set; } + + public string OldLiveCode { get; set; } + public string LiveCode { get; set; } + + public string SenderID { get; set; } + public int Likes { get; set; } + + public int WatchNum { get; set; } + + public CouponInfo CouponInfo { get; set; } + + public string FloorName { get; set; } + + public string HouseNum { get; set; } + + public string LogoPath { get; set; } + + public string QRCode { get; set; } + + public string ShopName { get; set; } + } + + + public class CouponInfo { + + public int ID { get; set; } + public string Code { get; set; } + public string ShopCode { get; set; } + public string Title { get; set; } + public string Intro { get; set; } + public int PublishState { get; set; } + public int TotalNum { get; set; } + public int Received { get; set; } + + public string QrCode { get; set; } + } + + public class CurrentLive + { + public string floorName { get; set; } + + public string hFilePath { get; set; } + + public string houseNum { get; set; } + + public int likes { get; set; } + + public string liveurl { get; set; } + public string logoPath { get; set; } + + public string mallName { get; set; } + public string qrCode { get; set; } + public string shopName { get; set; } + public List vFilePath { get; set; } + public int watchNum { get; set; } + + public CouponInfo CouponInfo { get; set; } + } + + public class PlayProg { + + public string OrderNo { get; set; } + + public string Code { get; set; } + + public string FilePath { get; set; } + + public int OrderType { get; set; } + } + + public class ShutDownProg + { + + public string OrderNo { get; set; } + + public string Code { get; set; } + } +} diff --git a/Container/Model/ProgModel.cs b/Container/Model/ProgModel.cs new file mode 100644 index 0000000..c0fd1c6 --- /dev/null +++ b/Container/Model/ProgModel.cs @@ -0,0 +1,105 @@ +using Newtonsoft.Json.Linq; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Container.Model +{ + public class ScheduleModel { + public string date { get; set; } + public List schedule { get; set; } + } + + public class ProgModel + { + public string beginTime { get; set; } + + public string endTime { get; set; } + public List programs { get; set; } + } + + public class Programme { + public string code { get; set; } + public string name { get; set; } + public string resolution { get; set; } + public string duration { get; set; } + public string backgroundColor { get; set; } + public string backgroundMaterial { get; set; } + public backgroundMaterialInfo backgroundMaterialInfo { get; set; } + public List components { get; set; } + + } + + public class backgroundMaterialInfo { + public string filePath { get; set; } + public string fileHash { get; set; } + } + + public class Component + { + public string code { get; set; } + public string programmeCode { get; set; } + + public string addTime { get; set; } + + public int height { get; set; } + + public int width { get; set; } + + public int offsetX { get; set; } + + public int offsetY { get; set; } + + public int zIndex { get; set; } + + public string typeCode { get; set; } + + public JObject config { get; set; } + + public List materials { get; set; } + } + + public class Material{ + public int order { get; set; } + public string materialCode { get; set; } + public string fileUrl { get; set; } + public string fileHash { get; set; } + public string name { get; set; } + + public int duration { get; set; } + + public MediaInfo mediaInfo { get; set; } + } + + public class PlayMaterial { + public JObject config { get; set; } + public int order { get; set; } + public string materialCode { get; set; } + public string fileUrl { get; set; } + public string fileHash { get; set; } + public string name { get; set; } + + public int duration { get; set; } + public string typeCode { get; set; } + + public MediaInfo mediaInfo { get; set; } + } + + public class MediaInfo { + public string name { get; set; } + public string password { get; set; } + public int port { get; set; } + public string protocol { get; set; } + public string url { get; set; } + + public string userName { get; set; } + + public string ipAddress { get; set; } + + public string channel { get; set; } + + public string bitRateType { get; set; } + } +} diff --git a/Container/Model/ScreenSavers.cs b/Container/Model/ScreenSavers.cs new file mode 100644 index 0000000..6269b56 --- /dev/null +++ b/Container/Model/ScreenSavers.cs @@ -0,0 +1,126 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Xml.Serialization; + +namespace Container.Model +{ + [XmlRoot("root")] + public class ScreenSavers + { + [XmlElement("code")] + public string Code; + + [XmlArray("items"), XmlArrayItem("item")] + public List ResList = new List(); + + public ScreenSavers Clone() + { + ScreenSavers model = new ScreenSavers(); + model.Code = this.Code; + foreach (var item in this.ResList) + { + ResInfo info = new ResInfo(); + info.id = item.id; + info.img = item.img; + info.time = item.time; + info.effect = item.effect; + info.text = item.text; + info.color = item.color; + info.code = item.code; + info.screenmatch = item.screenmatch; + //info.angle = item.angle; + info.expirydate = item.expirydate; + info.launchtime = item.launchtime; + info.floorName = item.floorName; + info.logoPath = item.logoPath; + info.shopName = item.shopName; + info.protype = item.protype; + info.xaxis = item.xaxis; + info.yaxis = item.yaxis; + info.houseNum = item.houseNum; + info.devNum = item.devNum; + info.floorOrder = item.floorOrder; + info.shopFormatIcon = item.shopFormatIcon; + info.shopFormatName = item.shopFormatName; + info.applets = item.applets; + model.ResList.Add(info); + } + + return model; + } + } + + public class ResInfo + { + [XmlAttribute("id")] + public string id; + + [XmlAttribute("img")] + public string img; + + [XmlAttribute("time")] + public string time; + + [XmlAttribute("effect")] + public string effect; + + [XmlAttribute("text")] + public string text; + + [XmlAttribute("color")] + public string color; + + [XmlAttribute("code")] + public string code; + + [XmlAttribute("screenmatch")] + public string screenmatch; + + [XmlAttribute("launchtime")] + public string launchtime; + + [XmlAttribute("expirydate")] + public string expirydate; + + //[XmlAttribute("angle")] + //public string angle; + + [XmlAttribute("floorName")] + public string floorName; + + [XmlAttribute("shopName")] + public string shopName; + + [XmlAttribute("logoPath")] + public string logoPath; + + [XmlAttribute("protype")] + public string protype; + + [XmlAttribute("houseNum")] + public string houseNum; + + [XmlAttribute("xaxis")] + public string xaxis; + + [XmlAttribute("yaxis")] + public string yaxis; + + [XmlAttribute("devNum")] + public string devNum; + + [XmlAttribute("floorOrder")] + public string floorOrder; + + [XmlAttribute("shopFormatIcon")] + public string shopFormatIcon; + [XmlAttribute("shopFormatName")] + public string shopFormatName; + + [XmlAttribute("applets")] + public string applets; + } +} diff --git a/Container/Model/SubTitle.cs b/Container/Model/SubTitle.cs new file mode 100644 index 0000000..40de945 --- /dev/null +++ b/Container/Model/SubTitle.cs @@ -0,0 +1,54 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Container.Model +{ + public class SubTitle + { + + /// + /// 字幕内容 + /// + public string text { get; set; } + + /// + /// 开始时间 + /// + public string beginTime { get; set; } + + /// + /// 结束时间 + /// + public string endTime { get; set; } + + /// + /// 位置 + /// + public string location { get; set; } + + + /// + /// 编码 + /// + public string code { get; set; } + + /// + /// 字体大小 + /// + public int fontSize { get; set; } + + /// + /// 滚动方向 left:从左到右 right:从右到左 + /// + public string direction { get; set; } + + /// + /// 字体颜色 + /// + public string fontColor { get; set; } + + } +} diff --git a/Container/Properties/AssemblyInfo.cs b/Container/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..a8bf037 --- /dev/null +++ b/Container/Properties/AssemblyInfo.cs @@ -0,0 +1,55 @@ +using System.Reflection; +using System.Resources; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Windows; + +// 有关程序集的常规信息通过以下 +// 特性集控制。更改这些特性值可修改 +// 与程序集关联的信息。 +[assembly: AssemblyTitle("Container")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("南京千目信息科技有限公司")] +[assembly: AssemblyProduct("产品容器")] +[assembly: AssemblyCopyright("Wxd@1000mu.2017.7.20")] +[assembly: AssemblyTrademark("1000mu")] +[assembly: AssemblyCulture("")] + +// 将 ComVisible 设置为 false 使此程序集中的类型 +// 对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型, +// 则将该类型上的 ComVisible 特性设置为 true。 +[assembly: ComVisible(false)] + +//若要开始生成可本地化的应用程序,请在 +// 中的 .csproj 文件中 +//设置 CultureYouAreCodingWith。 例如,如果您在源文件中 +//使用的是美国英语,请将 设置为 en-US。 然后取消 +//对以下 NeutralResourceLanguage 特性的注释。 更新 +//以下行中的“en-US”以匹配项目文件中的 UICulture 设置。 + +//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] + + +[assembly: ThemeInfo( + ResourceDictionaryLocation.None, //主题特定资源词典所处位置 + //(在页面或应用程序资源词典中 + // 未找到某个资源的情况下使用) + ResourceDictionaryLocation.SourceAssembly //常规资源词典所处位置 + //(在页面、应用程序或任何主题特定资源词典中 + // 未找到某个资源的情况下使用) +)] + + +// 程序集的版本信息由下面四个值组成: +// +// 主版本 +// 次版本 +// 生成号 +// 修订号 +// +// 可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值, +// 方法是按如下所示使用“*”: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Container/Properties/Resources.Designer.cs b/Container/Properties/Resources.Designer.cs new file mode 100644 index 0000000..bf27bb1 --- /dev/null +++ b/Container/Properties/Resources.Designer.cs @@ -0,0 +1,63 @@ +//------------------------------------------------------------------------------ +// +// 此代码由工具生成。 +// 运行时版本:4.0.30319.42000 +// +// 对此文件的更改可能会导致不正确的行为,并且如果 +// 重新生成代码,这些更改将会丢失。 +// +//------------------------------------------------------------------------------ + +namespace Container.Properties { + using System; + + + /// + /// 一个强类型的资源类,用于查找本地化的字符串等。 + /// + // 此类是由 StronglyTypedResourceBuilder + // 类通过类似于 ResGen 或 Visual Studio 的工具自动生成的。 + // 若要添加或移除成员,请编辑 .ResX 文件,然后重新运行 ResGen + // (以 /str 作为命令选项),或重新生成 VS 项目。 + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + internal class Resources { + + private static global::System.Resources.ResourceManager resourceMan; + + private static global::System.Globalization.CultureInfo resourceCulture; + + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + internal Resources() { + } + + /// + /// 返回此类使用的缓存的 ResourceManager 实例。 + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Resources.ResourceManager ResourceManager { + get { + if (object.ReferenceEquals(resourceMan, null)) { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Container.Properties.Resources", typeof(Resources).Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + /// + /// 重写当前线程的 CurrentUICulture 属性,对 + /// 使用此强类型资源类的所有资源查找执行重写。 + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Globalization.CultureInfo Culture { + get { + return resourceCulture; + } + set { + resourceCulture = value; + } + } + } +} diff --git a/Container/Properties/Resources.resx b/Container/Properties/Resources.resx new file mode 100644 index 0000000..af7dbeb --- /dev/null +++ b/Container/Properties/Resources.resx @@ -0,0 +1,117 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/Container/Properties/Settings.Designer.cs b/Container/Properties/Settings.Designer.cs new file mode 100644 index 0000000..986221b --- /dev/null +++ b/Container/Properties/Settings.Designer.cs @@ -0,0 +1,26 @@ +//------------------------------------------------------------------------------ +// +// 此代码由工具生成。 +// 运行时版本:4.0.30319.42000 +// +// 对此文件的更改可能会导致不正确的行为,并且如果 +// 重新生成代码,这些更改将会丢失。 +// +//------------------------------------------------------------------------------ + +namespace Container.Properties { + + + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "17.2.0.0")] + internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { + + private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); + + public static Settings Default { + get { + return defaultInstance; + } + } + } +} diff --git a/Container/Properties/Settings.settings b/Container/Properties/Settings.settings new file mode 100644 index 0000000..033d7a5 --- /dev/null +++ b/Container/Properties/Settings.settings @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/Container/Properties/app.manifest b/Container/Properties/app.manifest new file mode 100644 index 0000000..ddc23c7 --- /dev/null +++ b/Container/Properties/app.manifest @@ -0,0 +1,54 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Container/Resources/BROWNSTD REGULAR.otf b/Container/Resources/BROWNSTD REGULAR.otf new file mode 100644 index 0000000..c929c4e Binary files /dev/null and b/Container/Resources/BROWNSTD REGULAR.otf differ diff --git a/Container/Resources/DINPro-Regular_0.otf b/Container/Resources/DINPro-Regular_0.otf new file mode 100644 index 0000000..84d57ab Binary files /dev/null and b/Container/Resources/DINPro-Regular_0.otf differ diff --git a/Container/Resources/SourceHanSansCN-Light_0.otf b/Container/Resources/SourceHanSansCN-Light_0.otf new file mode 100644 index 0000000..1cff8e6 Binary files /dev/null and b/Container/Resources/SourceHanSansCN-Light_0.otf differ diff --git a/Container/Resources/SourceHanSansCN-Regular.otf b/Container/Resources/SourceHanSansCN-Regular.otf new file mode 100644 index 0000000..886f82f Binary files /dev/null and b/Container/Resources/SourceHanSansCN-Regular.otf differ diff --git a/Container/SaversViewModel/NavViewModel.cs b/Container/SaversViewModel/NavViewModel.cs new file mode 100644 index 0000000..a20f337 --- /dev/null +++ b/Container/SaversViewModel/NavViewModel.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Container.SaversViewModel +{ + public class NavViewModel + { + public string FloorName { get; set; } + public int Angle { get; set; } + public int Distance { get; set; } + public string ShopName { get; set; } + public string LogoPath { get; set; } + + } +} diff --git a/Container/SaversViewModel/ProgressViewModel.cs b/Container/SaversViewModel/ProgressViewModel.cs new file mode 100644 index 0000000..43adcad --- /dev/null +++ b/Container/SaversViewModel/ProgressViewModel.cs @@ -0,0 +1,76 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Container.SaversViewModel +{ + class ProgressViewModel : ViewModelBase + { + private int currentProgress = 0; + private int maxValue = 0; + private double val = 0.00; + private string message = string.Empty; + private string title = string.Empty; + + + public double Val + { + get { return val; } + set + { + val = value; + OnPropertyChanged("Val"); + } + } + + public string Title + { + get { return title; } + set + { + title = value; + OnPropertyChanged("Title"); + } + } + + public int CurrentProgress + { + get { return currentProgress; } + set + { + currentProgress = value; + OnPropertyChanged("CurrentProgress"); + } + } + + public int MaxValue + { + get { return maxValue; } + set + { + maxValue = value; + OnPropertyChanged("MaxValue"); + } + } + + public string Message + { + get { return message; } + set + { + message = value; + OnPropertyChanged("Message"); + } + } + } + + public enum MarqueeType + { + Up, + Down, + Left, + Right + } +} diff --git a/Container/SaversViewModel/Screensaver.cs b/Container/SaversViewModel/Screensaver.cs new file mode 100644 index 0000000..95bbc5a --- /dev/null +++ b/Container/SaversViewModel/Screensaver.cs @@ -0,0 +1,54 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Container.SaversViewModel +{ + public class Screensaver + { + + + /// + /// 屏保提示图标设置 + /// + public int ScreenType { get; set; } + + /// + /// 屏保提示图标设置 + /// + public string ScreenFile { get; set; } + + /// + /// 效果 0、固定位置 1、自由运动 + /// + public int ScreenEffect { get; set; } + + /// + /// 播放类型 固定位置( 0、右下角 1、居中) 自由运动(0、左右移动 1、随机移动) + /// + public int EffectType { get; set; } + + public int ScreenTime { get; set; } + + } + + public class Input_PlayRecordDetail + { + /// + /// 节目编码 + /// + public string ProgramCode { get; set; } + + /// + /// 时长 + /// + public int Time { get; set; } + + /// + /// 播放日期 + /// + public DateTime PlayTime { get; set; } + } +} diff --git a/Container/SaversViewModel/ViewModelBase.cs b/Container/SaversViewModel/ViewModelBase.cs new file mode 100644 index 0000000..11cab8a --- /dev/null +++ b/Container/SaversViewModel/ViewModelBase.cs @@ -0,0 +1,20 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Container.SaversViewModel +{ + class ViewModelBase : INotifyPropertyChanged + { + public event PropertyChangedEventHandler PropertyChanged; + + protected virtual void OnPropertyChanged(string propertyName) + { + if (PropertyChanged != null) + PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); + } + } +} diff --git a/Container/Services/HttpClient.cs b/Container/Services/HttpClient.cs new file mode 100644 index 0000000..681a21c --- /dev/null +++ b/Container/Services/HttpClient.cs @@ -0,0 +1,850 @@ +using Container.Common; +using System; +using System.Collections.Generic; +using System.Drawing; +using System.IO; +using System.Linq; +using System.Net; +//using System.Net.Http; +using System.Text; +using System.Threading.Tasks; +using System.Windows; +using Container.Control; +using Container.Model; + +namespace Container.Services +{ + + class HttpClient + { + public string message; + public string url; + //public string httpStr; + private Class_Log log = new Class_Log(); + App app = ((App)Application.Current); + public string HttpPost()//string postDataStr, string tradecode, string devicecode, string id, string organcode,string producttype + { + try + { + message = message.Replace("'", "\""); + return GetWebService(message); //"jsonparam=" + message.Length.ToString().PadLeft(8, '0') + + + } + catch (Exception ex) + { + log.WriteLogFile("错误信息:" + ex.ToString(), "HttpClient"); + return ""; + } + } + + /// + /// + /// + /// 地址 + /// 方法 + /// json参数 + /// + public string WebServiceApp(string param) + { + //转换输入参数的编码类型,获取bytep[]数组 + byte[] byteArray = Encoding.UTF8.GetBytes(param); + //初始化新的webRequst + //1. 创建httpWebRequest对象 + if (message != "") + url = url + "?" + message; + //url = Encoding.UTF8.GetString(Encoding.UTF8.GetBytes(url)); + HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(new Uri(url)); + log.WriteLogFile("SendUrl:" + url, "HttpClient"); + log.WriteLogFile("SendMessage:" + param, "HttpClient"); + //2. 初始化HttpWebRequest对象 + webRequest.Method = "POST"; + webRequest.ContentType = "application/x-www-form-urlencoded"; + webRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"; + //webRequest.ProtocolVersion = + webRequest.ContentLength = byteArray.Length; + //3. 附加要POST给服务器的数据到HttpWebRequest对象(附加POST数据的过程比较特殊,它并没有提供一个属性给用户存取,需要写入HttpWebRequest对象提供的一个stream里面。) + Stream newStream = webRequest.GetRequestStream();//创建一个Stream,赋值是写入HttpWebRequest对象提供的一个stream里面 + newStream.Write(byteArray, 0, byteArray.Length); + newStream.Close(); + //4. 读取服务器的返回信息 + HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse(); + StreamReader php = new StreamReader(response.GetResponseStream(), Encoding.UTF8); + string phpend = php.ReadToEnd(); + php.Close(); + response.Close(); + log.WriteLogFile("RecvMessage:" + phpend, "HttpClient"); + + return phpend; + + } + + + /// + /// Http post方法 + /// + /// json参数 + /// 服务器地址 + /// + public string PostMoths(string param, string url) + { + log.WriteLogFile("Sendurl:" + url, "HttpClient"); + + log.WriteLogFile("SendMessage:" + param, "HttpClient"); + string strURL = url; + System.Net.HttpWebRequest request; + request = (System.Net.HttpWebRequest)WebRequest.Create(strURL); + request.Method = "POST"; + request.ContentType = "application/json;charset=UTF-8"; + string paraUrlCoded = param; + byte[] payload; + payload = System.Text.Encoding.UTF8.GetBytes(paraUrlCoded); + request.ContentLength = payload.Length; + Stream writer = request.GetRequestStream(); + writer.Write(payload, 0, payload.Length); + writer.Close(); + System.Net.HttpWebResponse response; + response = (System.Net.HttpWebResponse)request.GetResponse(); + System.IO.Stream s; + s = response.GetResponseStream(); + string StrDate = ""; + string strValue = ""; + StreamReader Reader = new StreamReader(s, Encoding.UTF8); + while ((StrDate = Reader.ReadLine()) != null) + { + strValue += StrDate + "\r\n"; + } + log.WriteLogFile("RecvMessage:" + strValue, "HttpClient"); + + return strValue; + } + /// + /// + /// + /// 地址 + /// 方法 + /// json参数 + /// + public string GetWebService(string param) + { + //message = message.Replace("'", "\""); + string postDataStr = param; + if (!param.Trim().Equals("")) + url += "?" + param; + log.WriteLogFile("SendUrl:" + url, "HttpClient"); + CookieContainer cookie = new CookieContainer(); + HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); + request.Method = "Get"; + request.Timeout = 59000; + //request.ContentType = "application/x-www-form-urlencoded"; + + HttpWebResponse response = (HttpWebResponse)request.GetResponse(); + + response.Cookies = cookie.GetCookies(response.ResponseUri); + Stream myResponseStream = response.GetResponseStream(); + StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8")); + string retString = myStreamReader.ReadToEnd(); + log.WriteLogFile("RecvMessage:" + retString, "HttpClient"); + myStreamReader.Close(); + myResponseStream.Close(); + + return retString; + + } + + public static void DelectDir(string srcPath) + { + try + { + DirectoryInfo dir = new DirectoryInfo(srcPath); + FileSystemInfo[] fileinfo = dir.GetFileSystemInfos(); //返回目录中所有文件和子目录 + foreach (FileSystemInfo i in fileinfo) + { + if (i is DirectoryInfo) //判断是否文件夹 + { + DirectoryInfo subdir = new DirectoryInfo(i.FullName); + subdir.Delete(true); //删除子目录和文件 + } + else + { + File.Delete(i.FullName); //删除指定文件 + } + } + } + catch (Exception e) + { + throw; + } + } + + /// + /// 下载离线数据 + /// + /// 文件下载地址 + /// 应用程序文件名(不带扩展名) + /// 下载成功标志 + public bool DownLoadFiles(string path,ref string filename) + { + + try + { + var httpPath = path.Substring(0, path.IndexOf("://") + 3); + var fileBackPath = path.Substring(path.IndexOf("://") + 3).Replace("//", "/").Replace("\\", "/"); + path = httpPath+ fileBackPath; + string localFile = string.Empty;//本地压缩文件保存的路径 + string Unzippath = string.Empty;//解压文件所在的路径 + path = path.Replace(@"\", "/"); + if (path.Contains("/")) + { + var filename1 = path.Substring(path.LastIndexOf("/") + 1, path.LastIndexOf(".zip") - path.LastIndexOf("/") - 1); + localFile = AppDomain.CurrentDomain.BaseDirectory + "/zipfile" + path.Substring(path.LastIndexOf("/"));//本地地址 + Unzippath = AppDomain.CurrentDomain.BaseDirectory + "/exefile/exefile" + "/" + filename1;//本地地址 + } + else + { + var filename1 = path.Substring(0, path.LastIndexOf(".zip")); + localFile = AppDomain.CurrentDomain.BaseDirectory + "/zipfile" + path; + Unzippath = AppDomain.CurrentDomain.BaseDirectory + "/exefile/exefile" + "/" + filename1; + } + //判断压缩包是否存在、 + if (File.Exists(localFile)) + { + File.Delete(localFile); + } + if (Directory.Exists(Unzippath)) + { + DelectDir(Unzippath); + } + if (File.Exists(localFile + ".temp")) + { + File.Delete(localFile + ".temp"); + } + + //下载应用程序压缩文件 + if (!File.Exists(localFile + ".temp")) + { + try + { + using (Stream fileStream = new FileStream(localFile + ".temp", FileMode.OpenOrCreate)) + { + fileStream.Seek(fileStream.Length, SeekOrigin.Current); + log.WriteLogFile(path, "HttpClient");//服务器地址 + HttpWebRequest request = (HttpWebRequest)WebRequest.Create(path); + request.AddRange(fileStream.Length); + //下载文件 + HttpWebResponse respone = (HttpWebResponse)request.GetResponse(); + using (Stream netStream = respone.GetResponseStream()) + { + long totalDownloadedByte = 0; + byte[] read = new byte[1024]; + int realReadLen = netStream.Read(read, 0, read.Length); + while (realReadLen > 0) + { + totalDownloadedByte = realReadLen + totalDownloadedByte; + + fileStream.Write(read, 0, realReadLen); + realReadLen = netStream.Read(read, 0, read.Length); + System.Windows.Forms.Application.DoEvents(); + } + netStream.Close(); + } + + fileStream.Close(); + } + //删除temp文件 + if (File.Exists(localFile)) + { + File.Delete(localFile); + } + File.Move(localFile + ".temp", localFile); + //解压文件 + ZipFloClass.UnZip(localFile, Unzippath); + filename = Unzippath; + //app.Appdowninfo.exepath = Unzippath+ "/" + filename; + } + catch (Exception ex) + { + //File.Move(localFile + ".temp", localFile); + log.WriteLogFile(ex.ToString(), "HttpClient"); + return false; + } + } + } + catch (Exception ex) + { + log.WriteLogFile(ex.ToString(), "HttpClient"); + return false; + } + + return true; + + } + + + /// + /// 下载图片 + /// + /// 文件下载地址 + /// 应用程序文件名(不带扩展名) + /// 下载成功标志 + public bool DownLoadIcon( ref string filepath) + { + + try + { + var httpPath = filepath.Substring(0, filepath.IndexOf("://") + 3); + var fileBackPath = filepath.Substring(filepath.IndexOf("://") + 3).Replace("//", "/").Replace("\\", "/"); + filepath = httpPath + fileBackPath; + string Iconpath = string.Empty;//文件保存的路径 + var path = filepath; + if (path.Contains("/")) + { + var fileList = path.Split('/'); + var fileType=path.Substring(path.LastIndexOf(".") , path.Length - path.LastIndexOf(".")); + path = fileList[fileList.Length-2]+ fileType; + } + //else + //{ + // path = path; + //} + Iconpath = AppDomain.CurrentDomain.BaseDirectory + @"AppIcon\" + path; + log.WriteLogFile("图标地址" + Iconpath, "Icon"); + + if (File.Exists(Iconpath)) + { + filepath = Iconpath; + return true; + } + if (File.Exists(Iconpath + ".temp")) + { + File.Delete(Iconpath + ".temp"); + } + + //下载应用程序压缩文件 + if (!File.Exists(Iconpath + ".temp")) + { + try + { + using (Stream fileStream = new FileStream(Iconpath + ".temp", FileMode.OpenOrCreate)) + { + fileStream.Seek(fileStream.Length, SeekOrigin.Current); + log.WriteLogFile(filepath, "HttpClient");//服务器地址 + HttpWebRequest request = (HttpWebRequest)WebRequest.Create(filepath); + request.AddRange(fileStream.Length); + //下载文件 + HttpWebResponse respone = (HttpWebResponse)request.GetResponse(); + using (Stream netStream = respone.GetResponseStream()) + { + long totalDownloadedByte = 0; + byte[] read = new byte[1024]; + int realReadLen = netStream.Read(read, 0, read.Length); + while (realReadLen > 0) + { + totalDownloadedByte = realReadLen + totalDownloadedByte; + + fileStream.Write(read, 0, realReadLen); + realReadLen = netStream.Read(read, 0, read.Length); + System.Windows.Forms.Application.DoEvents(); + } + netStream.Close(); + } + + fileStream.Close(); + } + } + catch (Exception ex) + { + log.WriteLogFile(ex.ToString(), "HttpClient"); + //File.delete(Iconpath + ".temp", Iconpath); + return false; + } + //删除temp文件 + if (File.Exists(Iconpath)) + { + File.Delete(Iconpath); + } + File.Move(Iconpath + ".temp", Iconpath); + } + filepath = Iconpath; + log.WriteLogFile(filepath, "Icon"); + } + catch (Exception ex) + { + log.WriteLogFile(ex.ToString(), "HttpClient"); + return false; + } + + return true; + + } + + /// + /// 下载图片 + /// + /// 文件下载地址 + /// 文件夹名称 + /// 应用程序文件名(不带扩展名) + /// 下载成功标志 + public bool DownLoadImage(string path, string folderName, ref string filename) + { + + try + { + var httpPath = path.Substring(0, path.IndexOf("://") + 3); + var fileBackPath = path.Substring(path.IndexOf("://") + 3).Replace("//", "/").Replace("\\", "/"); + path = httpPath + fileBackPath; + string Iconpath = string.Empty;//文件保存的路径 + var names = path.Split('/'); + if (names.Length > 0) + { + filename = names[names.Length - 2] + names[names.Length - 1].Substring(names[names.Length - 1].LastIndexOf('.')); + } + else + { + filename = path.Substring(path.LastIndexOf("/")); + } + //if (path.Contains("/")) + //{ + // filename = path.Substring(path.LastIndexOf("/") + 1, path.Length - path.LastIndexOf("/") - 1); + //} + //else + //{ + // filename = path; + //} + string fpath = AppDomain.CurrentDomain.BaseDirectory + "/" + folderName; + if (!Directory.Exists(fpath)) + { + DirectoryInfo directoryInfo = new DirectoryInfo(fpath); + directoryInfo.Create(); + } + Iconpath = fpath + "/" + filename; + filename = Iconpath; + + if (File.Exists(Iconpath)) + { + return true; + } + if (File.Exists(Iconpath + ".temp")) + { + File.Delete(Iconpath + ".temp"); + } + + //下载应用程序压缩文件 + if (!File.Exists(Iconpath + ".temp")) + { + try + { + using (Stream fileStream = new FileStream(Iconpath + ".temp", FileMode.OpenOrCreate)) + { + fileStream.Seek(fileStream.Length, SeekOrigin.Current); + log.WriteLogFile(path, "HttpClient");//服务器地址 + HttpWebRequest request = (HttpWebRequest)WebRequest.Create(path); + request.AddRange(fileStream.Length); + //下载文件 + HttpWebResponse respone = (HttpWebResponse)request.GetResponse(); + using (Stream netStream = respone.GetResponseStream()) + { + long totalDownloadedByte = 0; + byte[] read = new byte[1024]; + int realReadLen = netStream.Read(read, 0, read.Length); + while (realReadLen > 0) + { + totalDownloadedByte = realReadLen + totalDownloadedByte; + + fileStream.Write(read, 0, realReadLen); + realReadLen = netStream.Read(read, 0, read.Length); + System.Windows.Forms.Application.DoEvents(); + } + netStream.Close(); + } + + fileStream.Close(); + } + } + catch (Exception ex) + { + log.WriteLogFile(ex.ToString(), "HttpClient"); + //File.delete(Iconpath + ".temp", Iconpath); + return false; + } + //删除temp文件 + if (File.Exists(Iconpath)) + { + File.Delete(Iconpath); + } + File.Move(Iconpath + ".temp", Iconpath); + filename = Iconpath; + + } + } + catch (Exception ex) + { + log.WriteLogFile(ex.ToString(), "HttpClient"); + return false; + } + + return true; + + } + + public bool DownLoadBGImage(string path, string folderName) + { + + try + { + string filename = string.Empty; + var httpPath = path.Substring(0, path.IndexOf("://") + 3); + var fileBackPath = path.Substring(path.IndexOf("://") + 3).Replace("//", "/").Replace("\\", "/"); + path = httpPath + fileBackPath; + string Iconpath = string.Empty;//文件保存的路径 + filename = "bg.png"; + //if (path.Contains("/")) + //{ + // filename = path.Substring(path.LastIndexOf("/") + 1, path.Length - path.LastIndexOf("/") - 1); + //} + //else + //{ + // filename = path; + //} + string fpath = AppDomain.CurrentDomain.BaseDirectory + "/" + folderName; + if (!Directory.Exists(fpath)) + { + DirectoryInfo directoryInfo = new DirectoryInfo(fpath); + directoryInfo.Create(); + } + foreach (FileInfo file in (new DirectoryInfo(fpath)).GetFiles()) + { + file.Attributes = FileAttributes.Normal; + file.Delete(); + } + Iconpath = fpath + "/" + filename; + filename = Iconpath; + + if (File.Exists(Iconpath)) + { + return true; + } + if (File.Exists(Iconpath + ".temp")) + { + File.Delete(Iconpath + ".temp"); + } + + //下载应用程序压缩文件 + if (!File.Exists(Iconpath + ".temp")) + { + try + { + using (Stream fileStream = new FileStream(Iconpath + ".temp", FileMode.OpenOrCreate)) + { + fileStream.Seek(fileStream.Length, SeekOrigin.Current); + log.WriteLogFile(path, "HttpClient");//服务器地址 + HttpWebRequest request = (HttpWebRequest)WebRequest.Create(path); + request.AddRange(fileStream.Length); + //下载文件 + HttpWebResponse respone = (HttpWebResponse)request.GetResponse(); + using (Stream netStream = respone.GetResponseStream()) + { + long totalDownloadedByte = 0; + byte[] read = new byte[1024]; + int realReadLen = netStream.Read(read, 0, read.Length); + while (realReadLen > 0) + { + totalDownloadedByte = realReadLen + totalDownloadedByte; + + fileStream.Write(read, 0, realReadLen); + realReadLen = netStream.Read(read, 0, read.Length); + System.Windows.Forms.Application.DoEvents(); + } + netStream.Close(); + } + + fileStream.Close(); + } + } + catch (Exception ex) + { + log.WriteLogFile(ex.ToString(), "HttpClient"); + //File.delete(Iconpath + ".temp", Iconpath); + return false; + } + //删除temp文件 + if (File.Exists(Iconpath)) + { + File.Delete(Iconpath); + } + File.Move(Iconpath + ".temp", Iconpath); + filename = Iconpath; + + } + } + catch (Exception ex) + { + log.WriteLogFile(ex.ToString(), "HttpClient"); + return false; + } + + return true; + + } + + + public string UpLoadNew(string url, string path) + { + try + { + HttpWebRequest Request1 = (HttpWebRequest)System.Net.WebRequest.Create(url); + HttpWebResponse Response1 = (HttpWebResponse)(WebResponse)Request1.GetResponse(); + System.IO.BinaryReader sr1 = new BinaryReader(Response1.GetResponseStream()); + long fileLenth1 = Response1.ContentLength; + byte[] content1 = sr1.ReadBytes((Int32)fileLenth1); + FileStream so1 = new FileStream(path, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite); + BinaryWriter fileWriter1 = new BinaryWriter(so1); + fileWriter1.Write(content1, 0, (Int32)fileLenth1); + content1 = null; + Response1.Close(); + fileWriter1.Flush(); + fileWriter1.Close(); + so1.Close(); + return true.ToString(); + } + catch (Exception ex) + { + return false.ToString() + ex.Message; + } + + } + public string UpLoadTxt(string url, string path, string name) + { + try + { + HttpWebRequest Request1 = (HttpWebRequest)System.Net.WebRequest.Create(url); + HttpWebResponse Response1 = (HttpWebResponse)(WebResponse)Request1.GetResponse(); + System.IO.BinaryReader sr1 = new BinaryReader(Response1.GetResponseStream()); + long fileLenth1 = Response1.ContentLength; + byte[] content1 = sr1.ReadBytes((Int32)fileLenth1); + if (File.Exists(url)) { return ""; } + FileStream so1 = new FileStream(path + "\\" + name, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite); + BinaryWriter fileWriter1 = new BinaryWriter(so1); + fileWriter1.Write(content1, 0, (Int32)fileLenth1); + content1 = null; + Response1.Close(); + fileWriter1.Flush(); + fileWriter1.Close(); + so1.Close(); + return true.ToString(); + } + catch (Exception ex) + { + return false.ToString() + ex.Message; + } + + } + + /// + /// + /// + /// 地址 + /// 方法 + /// json参数 + /// + public string WebServiceApppost(string param) + { + App app = ((App)Application.Current); + //转换输入参数的编码类型,获取bytep[]数组 + byte[] byteArray = Encoding.UTF8.GetBytes(param); + //初始化新的webRequst + //1. 创建httpWebRequest对象 + HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(new Uri(url)); + log.WriteLogFile("SendUrl:" + url, "HttpClient"); + log.WriteLogFile("SendMessage:" + param, "HttpClient"); + //2. 初始化HttpWebRequest对象 + webRequest.Method = "POST"; + webRequest.ContentType = "application/x-www-form-urlencoded"; + webRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"; + //webRequest.ProtocolVersion = + webRequest.ContentLength = byteArray.Length; + //3. 附加要POST给服务器的数据到HttpWebRequest对象(附加POST数据的过程比较特殊,它并没有提供一个属性给用户存取,需要写入HttpWebRequest对象提供的一个stream里面。) + Stream newStream = webRequest.GetRequestStream();//创建一个Stream,赋值是写入HttpWebRequest对象提供的一个stream里面 + newStream.Write(byteArray, 0, byteArray.Length); + newStream.Close(); + //4. 读取服务器的返回信息 + HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse(); + StreamReader php = new StreamReader(response.GetResponseStream(), Encoding.UTF8); + string phpend = php.ReadToEnd(); + php.Close(); + response.Close(); + log.WriteLogFile("RecvMessage:" + phpend, "HttpClient"); + + return phpend; + + } + + /// + /// http协议上传文件 + /// + /// + /// + /// + public string HttpUploadFile(string url, string path, string param) + { + log.WriteLogFile("上传图片-平台地址为:" + url); + log.WriteLogFile("上传图片-本地位置:" + path); + byte[] byteArray = Encoding.UTF8.GetBytes(param.Length.ToString().PadLeft(6, '0') + param); + log.WriteLogFile("参数:" + param.Length.ToString().PadLeft(6, '0') + param); + System.Text.ASCIIEncoding ASCII = new System.Text.ASCIIEncoding(); + + string len = ASCII.GetString(byteArray,0,6); + + string mes = ASCII.GetString(byteArray, 6, int.Parse(len));//@"E:\Test\回单机单机版\MultifuncSelfHelpterminal\bin\Release\CommonPic\ADpic\admin.jpg" + FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read); + byte[] bArr = new byte[fs.Length]; + fs.Read(bArr, 0, bArr.Length); + fs.Close(); + //FileStream fs1 = new FileStream("E:\\1234.jpg", FileMode.Create); + //fs1.Write(bArr, 0, bArr.Length); + + //fs1.Flush(); + //fs1.Dispose(); + //MessageBox.Show(len + " " + mes); + // 设置参数 + HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; + CookieContainer cookieContainer = new CookieContainer(); + request.CookieContainer = cookieContainer; + request.AllowAutoRedirect = true; + request.Method = "POST"; + //string boundary = DateTime.Now.Ticks.ToString("X"); // 随机分隔线 + request.ContentType = "charset=utf-8"; + //request.ContentType = "application/json;charset=utf-8;boundary=" + boundary; + + //byte[] itemBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "\r\n"); + //byte[] endBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n"); + + int pos = path.LastIndexOf("\\"); + string fileName = path.Substring(pos + 1); + + //请求头部信息 + //StringBuilder sbHeader = new StringBuilder(string.Format("Content-Disposition:form-data;name=\"file\";filename=\"{0}\"\r\nContent-Type:application/octet-stream\r\n\r\n", fileName)); + //byte[] postHeaderBytes = Encoding.UTF8.GetBytes(sbHeader.ToString()); + + //StringBuilder sbType = new StringBuilder(string.Format("Content-Disposition:form-data;name=\"type\"\r\nContent-Type:text/plain\r\n\r\n" + "1" + "\r\n")); + //byte[] strType = Encoding.UTF8.GetBytes(sbType.ToString()); + + + Stream postStream = request.GetRequestStream(); + postStream.Write(byteArray, 0, byteArray.Length); + postStream.Write(bArr, 0, bArr.Length); + postStream.Close(); + + //发送请求并获取相应回应数据 + HttpWebResponse response = request.GetResponse() as HttpWebResponse; + //直到request.GetResponse()程序才开始向目标网页发送Post请求 + Stream instream = response.GetResponseStream(); + + StreamReader sr = new StreamReader(instream, Encoding.UTF8); + //返回结果网页(html)代码 + string content = sr.ReadToEnd(); + + + // stream.Read(bytes, 0, bytes.Length); + // stream.Dispose(); + + + + + return content; + } + /// + /// http上传 + /// + //public static string HttpUploadFile(string url, string path) + //{ + // // 设置参数 + // HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; + // CookieContainer cookieContainer = new CookieContainer(); + // request.CookieContainer = cookieContainer; + // request.AllowAutoRedirect = true; + // request.Method = "POST"; + // string boundary = DateTime.Now.Ticks.ToString("X"); // 随机分隔线 + // request.ContentType = "multipart/form-data;charset=utf-8;boundary=" + boundary; + // byte[] itemBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "\r\n"); + // byte[] endBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n"); + + // int pos = path.LastIndexOf("\\"); + // string fileName = path.Substring(pos + 1); + + // //请求头部信息 + // StringBuilder sbHeader = new StringBuilder(string.Format("Content-Disposition:form-data;name=\"file\";filename=\"{0}\"\r\nContent-Type:application/octet-stream\r\n\r\n", fileName)); + // byte[] postHeaderBytes = Encoding.UTF8.GetBytes(sbHeader.ToString()); + + // FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read); + // byte[] bArr = new byte[fs.Length]; + // fs.Read(bArr, 0, bArr.Length); + // fs.Close(); + + // Stream postStream = request.GetRequestStream(); + // postStream.Write(itemBoundaryBytes, 0, itemBoundaryBytes.Length); + // postStream.Write(postHeaderBytes, 0, postHeaderBytes.Length); + // postStream.Write(bArr, 0, bArr.Length); + // postStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length); + // postStream.Close(); + + // //发送请求并获取相应回应数据 + // HttpWebResponse response = request.GetResponse() as HttpWebResponse; + // //直到request.GetResponse()程序才开始向目标网页发送Post请求 + // Stream instream = response.GetResponseStream(); + // StreamReader sr = new StreamReader(instream, Encoding.UTF8); + // //返回结果网页(html)代码 + // string content = sr.ReadToEnd(); + // return content; + //} + + public void SaveImg(string strPath, Bitmap img) + { + //保存图片到目录 + if (Directory.Exists(strPath)) + { + //文件名称 + string guid = Guid.NewGuid().ToString().Replace("-", "") + ".png"; + img.Save(strPath + "/" + guid, System.Drawing.Imaging.ImageFormat.Png); + } + else + { + //当前目录不存在,则创建 + Directory.CreateDirectory(strPath); + } + } + + + public bool CheckImageIsExists(string path, string folderName, ref string filename) + { + path = path.Replace("\\", "/"); + string Iconpath = string.Empty;//文件保存的路径 + var names = path.Split('/'); + if (names.Length > 0) + { + filename = names[names.Length - 2] + names[names.Length - 1].Substring(names[names.Length - 1].LastIndexOf('.')); + } + else + { + filename = path.Substring(path.LastIndexOf("/")); + } + string fpath = AppDomain.CurrentDomain.BaseDirectory + "/" + folderName; + if (!Directory.Exists(fpath)) + { + DirectoryInfo directoryInfo = new DirectoryInfo(fpath); + directoryInfo.Create(); + } + Iconpath = fpath + "/" + filename; + filename = Iconpath; + //判断文件是否存在 + if (File.Exists(Iconpath)) + { + return true; + } + else + { + return false; + } + } + } + +} diff --git a/Container/Services/HttpListen.cs b/Container/Services/HttpListen.cs new file mode 100644 index 0000000..069671c --- /dev/null +++ b/Container/Services/HttpListen.cs @@ -0,0 +1,104 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Net; +using System.Net.Sockets; +using System.IO; + +namespace Container.Services +{ + class HttpListen + { + static void ListenerHttpUrl() + { + try + { + HttpListen listerner = new HttpListen(); + { + for (; true; ) + { + try + { + Console.Write("请输入服务器IP地址:"); + string ip = Console.ReadLine(); + + listerner.AuthenticationSchemes = AuthenticationSchemes.Anonymous;//指定身份验证 Anonymous匿名访问 + listerner.Prefixes.Add("http://" + ip + ":1500/AnsweringMachineService/"); + + // listerner.Prefixes.Add("http://localhost/web/"); + listerner.Start(); + } + catch (Exception e) + { + Console.WriteLine("未能成功连接服务器....."); + listerner = new HttpListen(); + continue; + } + break; + } + Console.WriteLine("服务器启动成功......."); + + int maxThreadNum, portThreadNum; + + //线程池 + int minThreadNum; + ThreadPool.GetMaxThreads(out maxThreadNum, out portThreadNum); + ThreadPool.GetMinThreads(out minThreadNum, out portThreadNum); + Console.WriteLine("最大线程数:{0}", maxThreadNum); + Console.WriteLine("最小空闲线程数:{0}", minThreadNum); + + + //ThreadPool.QueueUserWorkItem(new WaitCallback(TaskProc1), x); + + Console.WriteLine("\n\n等待客户连接中。。。。"); + while (true) + { + //等待请求连接 + //没有请求则GetContext处于阻塞状态 + HttpListenerContext ctx = listerner.GetContext(); + + ThreadPool.QueueUserWorkItem(new WaitCallback(TaskProc), ctx); + } + con.Close(); + listerner.Stop(); + } + } + catch (Exception e) + { + Console.WriteLine(e.Message); + Console.Write("Press any key to continue . . . "); + Console.ReadKey( ); + } + + } + + static void TaskProc(object o) + { + HttpListenerContext ctx = (HttpListenerContext)o; + + ctx.Response.StatusCode = 200;//设置返回给客服端http状态代码 + + string type = ctx.Request.QueryString["type"]; + string userId = ctx.Request.QueryString["userId"]; + string password = ctx.Request.QueryString["password"]; + string filename = Path.GetFileName(ctx.Request.RawUrl); + string userName = HttpUtility.ParseQueryString(filename).Get("userName");//避免中文乱码 + + //进行处理 + + //使用Writer输出http响应代码 + using (StreamWriter writer = new StreamWriter(ctx.Response.OutputStream)) + { + writer.Write("处理结果"); + writer.Close(); + ctx.Response.Close(); + } + } + } +} diff --git a/Container/Services/HttpMessage.cs b/Container/Services/HttpMessage.cs new file mode 100644 index 0000000..db8d1be --- /dev/null +++ b/Container/Services/HttpMessage.cs @@ -0,0 +1,1008 @@ +using Container.Common; +using System.Management; +using System.Net; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Newtonsoft.Json; +using System.Windows; +using Container.Model; +using Container.Control; +using System.Windows.Data; +using System.IO; +using Container.ChildWindows; +using System.Runtime.Serialization.Formatters.Binary; +using System.Runtime.InteropServices; +using Newtonsoft.Json.Linq; +using Container.Viewmodel; +using Container.Business; +using AForge.Video.DirectShow; +using System.Collections; + +namespace Container.Services +{ + class CommandInfo + { + public string type { get; set; } + public string parameter { get; set; } + } + + public class Building + { + public string buildingName; + public string code; + public List floors; + } + + public class DeviceType + { + public string id; + public string code; + public string dictValue; + } + + public class AppModel + { + public string code; + public string filePath; + public string iconFilePath; + public string name; + public string spaceName; + public string screenInfoCode; + public string startup; + public string version; + public bool defaultFile; + } + + public class AppListModel + { + public string AppID; + public string AppType; + public string Code; + public string Default; + public string File; + public string Logo; + public string PackageName; + public string PlatformType; + public string ShelfTime; + public string Startup; + public string Name; + public string Version; + } + + public class AppTimeModel + { + public string AppCode; + public string BeginTimeSlot; + public string EndTimeSlot; + } + + public class Floor + { + public string floorName; + public string code; + } + + //public class Screensaver + //{ + // public string Time; + // public string ScreenType; + // public string ScreenEffect; + // public string ScreenType; + // public string ScreenType; + //} + class HttpMessage + { + private HttpClient httpclient = new HttpClient(); + private Class_Log log = new Class_Log(); + private Class_Config config = new Class_Config(); + App app; + public HttpMessage(string httpurl = "") + { + app = ((App)Application.Current); + } + + + /// + /// 心跳 + /// + public string HeatBeat() + { + try + { + if (string.IsNullOrEmpty(app.LocalIP)) + { + foreach (IPAddress _IPAddress in Dns.GetHostEntry(Dns.GetHostName()).AddressList) + { + if (_IPAddress.AddressFamily.ToString() == "InterNetwork") + { + app.LocalIP = _IPAddress.ToString(); + } + + } + } + string sendmsg = "ip=" + app.LocalIP + + + "&AppNameCH=" + app.AppPlayNameCH + + "&AppName=" + app.CurAppPlayName + + "&ContainerVersion=" + app.Containerversion + + "&AppVersion=" + app.Appversion; //// + + httpclient.url = app.HttpUrl + "/Api/Dev/DeviceHeartbeat"; + httpclient.message = sendmsg; + log.WriteLogFile(sendmsg, "DeviceHeartbeat"); + log.WriteLogFile(httpclient.url, "DeviceHeartbeat"); + string rev = httpclient.HttpPost(); + //rev = "{\"code\":\"200\",\"msg\":\"\",\"data\":{\"isShutDown\":0,\"downTime\":\"12:00\",\"isReloaded\":0}}"; + Dictionary dic = JsonConvert.DeserializeObject>(rev); + if (dic["data"] != null && dic["code"].ToString() == "200") + { + List Commands = JsonConvert.DeserializeObject>(dic["data"].ToString()); + if (Commands.Count > 0) + { + if (Commands.FindIndex(p => (p.type.Equals("downTime"))) != -1) + { + app.shutdowntime = Commands.Find(p => (p.type.Equals("downTime"))).parameter; + } + + //if (Commands.FindIndex(p => (p.type.Equals("AppName"))) != -1) + //{ + // app.NowAppName = Commands.Find(p => (p.type.Equals("AppName"))).parameter; + //} + //else + //{ + + //} + } + return "ShutDownTime"; + } + return ""; + } + catch (Exception ex) + { + + log.WriteLogFile("发送心跳包失败" + ex.ToString(), "HttpMessageErrorLog"); + return ""; + } + } + + /// + /// 心跳 + /// + public string HeatBeatForMqtt() + { + try + { + //if (string.IsNullOrEmpty(app.LocalIP)) + //{ + // foreach (IPAddress _IPAddress in Dns.GetHostEntry(Dns.GetHostName()).AddressList) + // { + // if (_IPAddress.AddressFamily.ToString() == "InterNetwork") + // { + // app.LocalIP = _IPAddress.ToString(); + // } + + // } + //} + //string sendmsg = "ip=" + app.LocalIP + + + // "&AppNameCH=" + app.AppPlayNameCH + + // "&AppName=" + app.AppPlayName + + // "&ContainerVersion=" + app.Containerversion + + // "&AppVersion=" + app.Appversion; //// + //string sendmsg = "{\"IP\":\"" + app.LocalIP + "\"}"; + // Dictionary data = new Dictionary { + // { "Code",app.deviceid}, + // { "AppName",app.AppPlayName}, + // { "AppNameCH",app.AppPlayNameCH }, + // { "CurTime",DateTime.Now.ToString("G")}, + // { "AppVersion",app.Appversion}, + // { "ContainerVersion",app.Containerversion} + //}; + // KafkaProducer.Produce(Guid.NewGuid().ToString(), JsonConvert.SerializeObject(data)); + + + + Dictionary data = new Dictionary { + { "AppName",app.AppPlayName}, + { "AppNameCH",app.AppPlayNameCH }, + { "AppVersion",app.Appversion}, + { "ContainerVersion",app.Containerversion}, + { "Code",app.deviceid} + }; + + MqServer.PublishMessage("deviceheatbeat", data, Array.Empty(), false); + //mqttClient.PublishAsync(app.mqttCredentialsModel.ClientId, JsonConvert.SerializeObject(data)); + return ""; + } + catch (Exception ex) + { + + log.WriteLogFile("发送心跳包失败" + ex.ToString(), "HttpMessageErrorLog"); + return ""; + } + } + + /// + /// 获取楼栋楼层信息 + /// + public bool GetBuildinginfo(ref string Errorlog) + { + try + { + string MethodStr = "/API/Dev/GetDeviceOptionsNew"; + var data = new { MallCode = app.mallCode }; + var ret = MyHttpClient.CryptPost(MethodStr, data); + + if (!string.IsNullOrEmpty(ret)) + { + var Jo = JObject.Parse(ret); + string code = Jo.Value("code"); + if (code == "200") + { + var Data = Jo.Value("data"); + List itemList = Data.Value("buildings").ToObject>(); + //解析漏洞信息应该是List + app.Buildinginfo.Clear(); + app.Buildinginfo = itemList; + return true; + //List itemList = JsonConvert.DeserializeObject>(Data); + //string xmlstring = WriteToConfig(itemList, "1"); + //if (!string.IsNullOrEmpty(xmlstring) && xmlstring != "") + //{ + // ScreenSavers result = CommonMethod.DeserializeXML(xmlstring); + // Mylog.WriteLogFile(result.ResList.ToString(), "HttpClient"); + // return result; + //} + } + else { + return false; + } + + } + else + return false; + + //httpclient.message = ""; + //string sendmsg = ""; + //httpclient.url = app.HttpUrl + "/Dictionary/GetBuildings"; + //httpclient.message = sendmsg; + //string rev = httpclient.HttpPost(); + ////rev = "{\"code\":\"200\",\"msg\":\"获取成功\",\"data\":[{\"id\":1,\"bName\":\"A栋\"},{\"id\":2,\"bName\":\"B栋\"}]}";http://192.168.0.142/api/account/Register?AccountName=af&Password=123456&ConfirmPassword=123456&NickName=阿福&AvatarSrc&Phone=18254698745&Email=123@123.com&RoleIDs=2,3,4,5&UserDefaultFile=true + //Dictionary dic = JsonConvert.DeserializeObject>(rev); + //if (dic["msg"] != null) + // Errorlog = dic["msg"].ToString(); + //if (dic["data"] != null && dic["code"].ToString() == "200") + //{ + // if (dic["data"].ToString().Trim().Equals("")) + // return false; + // string mes = dic["data"].ToString(); + // //解析漏洞信息应该是List + // app.Buildinginfo.Clear(); + // app.Buildinginfo = JsonConvert.DeserializeObject>(dic["data"].ToString()); + // return true; + //} + //return false; + } + catch (Exception ex) + { + if (Errorlog.Trim().Equals("")) + Errorlog = "获取楼栋信息失败"; + log.WriteLogFile("获取楼栋信息失败" + ex.ToString(), "HttpMessageErrorLog"); + return false; + } + } + + public bool CheckMallRegKey(string RegKey, ref string MallCode, ref string Errorlog) + { + try + { + + string MethodStr = "/API/Dev/GetMallByRegKey"; + var data = new { RegKey = RegKey }; + var ret = MyHttpClient.CryptPost(MethodStr, data); + + if (!string.IsNullOrEmpty(ret)) + { + var Jo = JObject.Parse(ret); + string code = Jo.Value("code"); + Errorlog = Jo.Value("msg"); + if (code == "200") + { + MallCode = Jo.Value("data"); + return true; + } + else + { + return false; + } + + } + else { + Errorlog = "获取商场信息信息失败"; + return false; + } + + } + catch (Exception ex) + { + if (Errorlog.Trim().Equals("")) + Errorlog = "获取商场信息信息失败"; + log.WriteLogFile("获取商场信息信息失败" + ex.ToString(), "HttpMessageErrorLog"); + return false; + } + } + public bool GetDeviceTypeList(ref string Errorlog) + { + try + { + + string MethodStr = "/API/Dev/GetDictListByName"; + var data = new { Name = "DeviceType" }; + var ret = MyHttpClient.CryptPost(MethodStr, data); + + if (!string.IsNullOrEmpty(ret)) + { + var Jo = JObject.Parse(ret); + string code = Jo.Value("code"); + if (code == "200") + { + //var Data = JObject.Parse(Jo.Value("data")); + List itemList = Jo.Value("data").ToObject>(); + //解析漏洞信息应该是List + app.DeviceTypeList.Clear(); + app.DeviceTypeList = itemList; + return true; + } + else + return false; + } + else + return false; + } + catch (Exception ex) + { + if (Errorlog.Trim().Equals("")) + Errorlog = "获取设备类型失败"; + log.WriteLogFile("获取设备类型失败" + ex.ToString(), "HttpMessageErrorLog"); + return false; + } + } + + + + + + [DllImport("user32")] + static extern int GetSystemMetrics(int n); + + /// + /// 上传设备信息 + /// + public bool UploadDeviceInfo(string build, string floor, string deviceType, ref string Errorlog, bool update = true) + { + try + { + //获取本机的IP地址和MAC地址.... + string AddressIP = string.Empty; + if (update) + { + foreach (IPAddress _IPAddress in Dns.GetHostEntry(Dns.GetHostName()).AddressList) + { + if (_IPAddress.AddressFamily.ToString() == "InterNetwork") + { + AddressIP = _IPAddress.ToString(); + } + } + } + else { + AddressIP = app.LocalIP; + } + + ManagementClass mc; + string mac = string.Empty; + mc = new ManagementClass("Win32_NetworkAdapterConfiguration"); + ManagementObjectCollection moc = mc.GetInstances(); + foreach (ManagementObject mo in moc) + { + if (mo["IPEnabled"].ToString() == "True") + mac = mo["MacAddress"].ToString(); + } + while (mac.IndexOf(":") >= 0) + mac = mac.Remove(mac.IndexOf(":"), 1); + //if (string.IsNullOrEmpty(app.deviceid)) + //{ + // log.WriteLogFile("设备信息上传失败:deviceid为空", "HttpMessageErrorLog"); + // return false; + //} + if (string.IsNullOrEmpty(app.devicemark)) + { + + app.devicemark = System.Net.Dns.GetHostName(); + + //return false; + } + bool isSound = IsSound(); + bool isVideo = IsVideo(); + string MethodStr = "/API/Dev/AddDevice"; + var data = new { + MallCode = app.mallCode, + IP = AddressIP, + MAC = mac, + ScreenInfo = app.ScreenWidth + "*" + app.ScreenHeight + " " + (app.ScreenWidth > app.ScreenHeight ? "横屏" : "竖屏"), + Building = build, + Floor = floor, + DevNum = app.devicemark, + SystemType = "Windows", + DeviceType = deviceType, + Code = app.deviceid, + Version = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString(), + HardWare = (isSound ? "麦克风;" : "") + (isVideo ? "摄像头;" : "") + }; + + var ret = MyHttpClient.CryptPost(MethodStr, data); + log.WriteLogFile(ret, "dev"); + if (!string.IsNullOrEmpty(ret)) + { + var Jo = JObject.Parse(ret); + string code = Jo.Value("code"); + Errorlog = Jo.Value("msg"); + if (code == "200") + { + //var Data = JObject.Parse(Jo.Value("data")); + app.Floor = floor.ToString(); + app.BuildingID = build.ToString(); + app.LocalIP = AddressIP; + app.DeviceType = deviceType; + var dicData = Jo.Value("data"); + var oldDevice = app.deviceid; + if (dicData != null) + { + app.deviceid = dicData["code"].ToString(); + RabbitMQModel rabbit = new RabbitMQModel(); + rabbit.UserName = dicData["userName"] == null ? "" : dicData["userName"].ToString(); + rabbit.Password = dicData["password"] == null ? "" : dicData["password"].ToString(); + rabbit.HostName = dicData["hostName"] == null ? "" : dicData["hostName"].ToString(); + rabbit.Port = dicData["port"] == null ? 0 : Convert.ToInt32(dicData["port"]); + app.rabbitMQ = rabbit; + app.shutdowntime = dicData["shutdownTime"] == null ? "" : dicData["shutdownTime"].ToString(); + app.BGFile = dicData["defaultPic"] == null ? "" : dicData["defaultPic"].ToString(); + app.defaultCity= dicData["city"] == null ? "" : dicData["city"].ToString(); + if (!string.IsNullOrEmpty(app.BGFile)) + { + HttpClient httpClient = new HttpClient(); + httpClient.DownLoadBGImage(app.BGFile, "pic"); + } + } + if (update || oldDevice != app.deviceid) + config.WriteToConfig(); + return true; + } + else + return false; + } + else + { + if (update) + { + return false; + } + else + { + return true; + } + } + + } + catch (Exception ex) + { + if (Errorlog.Trim().Equals("")) + Errorlog = "设备信息上传失败"; + log.WriteLogFile("设备信息上传失败" + ex.ToString(), "HttpMessageErrorLog"); + if (update) + { + return false; + } + else { + return true; + } + + } + } + + private bool IsSound() + { + //// 获取默认音频捕捉设备 + var devices = SharpDX.DirectSound.DirectSoundCapture.GetDevices(); // 枚举音频捕捉设备 + if (devices.Count > 0) + { + return true; + } + else + { + return false; + } + } + + private bool IsVideo() + { + //// 获取默认音频捕捉设备 + + var videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice); + if (videoDevices.Count > 0) + { + return true; + } + else + { + return false; + } + } + + public bool LoadAppConfig(ref string Errorlog) + { + try + { + + string MethodStr = "/API/Dev/GetDevAppList"; + var data = new { DevCode = app.deviceid, MallCode=app.mallCode, Paging=0 }; + var ret = MyHttpClient.CryptPost(MethodStr, data); + if (!string.IsNullOrEmpty(ret)) + { + log.WriteLogFile(ret,"devapp"); + var Jo = JObject.Parse(ret); + string code = Jo.Value("code"); + Class_Config con = new Class_Config(); + if (code == "200") + { + var resultData = Jo.Value("data"); + List itemList = resultData.Value("appList").ToObject>(); + List appTimes = resultData.Value("appTime").ToObject>(); + ArrayList list = new ArrayList(); + foreach (var item in itemList) + { + bool flag = httpclient.DownLoadIcon(ref item.Logo); + log.WriteLogFile("item.Logo" + item.Logo, "Icon"); + var appModel = app.AppList.Where(i => i.Code == item.Code).FirstOrDefault(); + if ((appModel == null || appModel.Version != item.Version)&&!string.IsNullOrEmpty(item.File)) { + httpclient.DownLoadFiles(item.File,ref item.File); + } + if (!string.IsNullOrEmpty(item.Startup)&&(item.Startup.ToLower().StartsWith("https://") || item.Startup.ToLower().StartsWith("http://"))) { + item.Startup = log.WriteAppStart(item.Name, item.Startup); + } + con.WriteToExeConfig(item); + list.Add(item.Code); + } + var delApp = app.AppList.Where(i => !list.Contains(i.Code)).ToList(); + foreach (var item in delApp) + { + con.RemoveExeConfig(item.Code, ref item.File, ref item.Logo, ref item.Startup); + if (!string.IsNullOrEmpty(item.File)&& Directory.Exists(item.File)) { + Directory.Delete(item.File); + } + + if (!string.IsNullOrEmpty(item.Logo) && File.Exists(item.Logo)) + { + File.Delete(item.Logo); + } + + if (!string.IsNullOrEmpty(item.Logo) &&File.Exists(item.Startup)) + { + File.Delete(item.Startup); + } + } + con.WriteToAppTimeConfig(appTimes); + //解析漏洞信息应该是List + app.AppList.Clear(); + app.AppList = itemList; + app.AppTimeList.Clear(); + app.AppTimeList = appTimes; + return true; + } + else + return false; + } + else + return false; + } + catch (Exception ex) + { + if (Errorlog.Trim().Equals("")) + Errorlog = "设备信息上传失败"; + log.WriteLogFile("设备信息上传失败" + ex.ToString(), "HttpMessageErrorLog"); + return false; + } + return false; + } + + public bool LoadAppTimeConfig() + { + try + { + + string MethodStr = "/API/Dev/GetDevAppTimeList"; + var data = new { DevCode = app.deviceid, MallCode = app.mallCode, Paging = 0 }; + var ret = MyHttpClient.CryptPost(MethodStr, data); + if (!string.IsNullOrEmpty(ret)) + { + var Jo = JObject.Parse(ret); + string code = Jo.Value("code"); + Class_Config con = new Class_Config(); + if (code == "200") + { + var resultData = Jo.Value("data"); + List appTimes = resultData.Value("appTime").ToObject>(); + con.WriteToAppTimeConfig(appTimes); + app.AppTimeList.Clear(); + app.AppTimeList = appTimes; + return true; + } + else + return false; + } + else + return false; + } + catch (Exception ex) + { + log.WriteLogFile("设备信息上传失败" + ex.ToString(), "HttpMessageErrorLog"); + return false; + } + return false; + } + + + public bool LoadScreenTime() + { + try + { + string MethodStr = "/API/Screensaver/GetScreensaver"; + var data = new { MallCode = app.mallCode }; + var ret = MyHttpClient.CryptPost(MethodStr, data); + log.WriteLogFile(ret,"screensaver"); + if (!string.IsNullOrEmpty(ret)) + { + var Jo = JObject.Parse(ret); + string code = Jo.Value("code"); + if (code == "200"||code=="201") + { + var dicData = Jo.Value("data"); + app.screensaver.ScreenTime = string.IsNullOrEmpty(dicData["time"].ToString()) ? 30 : Convert.ToInt32(dicData["time"]); + //Dictionary dicData = JsonConvert.DeserializeObject>(Jo.Value("data")); + //app.screenTime = string.IsNullOrEmpty(dicData["time"].ToString()) ? 30 : Convert.ToInt32(dicData["time"]); + string fileName = string.Empty; + if (!string.IsNullOrEmpty(dicData["screenFilePath"].ToString())) { + httpclient.DownLoadImage(dicData["screenFilePath"].ToString(), "exefile/PCScreen/config", ref fileName); + } + app.screensaver.ScreenType = string.IsNullOrEmpty(dicData["screenType"].ToString()) ? 0 : Convert.ToInt32(dicData["screenType"]); + app.screensaver.ScreenEffect = string.IsNullOrEmpty(dicData["screenEffect"].ToString()) ? 0 : Convert.ToInt32(dicData["screenEffect"]); + app.screensaver.ScreenFile = fileName; + app.screensaver.EffectType = string.IsNullOrEmpty(dicData["effectType"].ToString()) ? 0 : Convert.ToInt32(dicData["effectType"]); + // config.WriteToScreenConfig(dicData["screenType"].ToString(), dicData["screenEffect"].ToString(), fileName, dicData["effectType"].ToString()); + return true; + } + } + return false; + } + catch (Exception ex) + { + log.WriteLogFile("屏保时间同步失败" + ex.ToString(), "HttpMessageErrorLog"); + return false; + } + } + + public bool LoadBG() { + return false; + //try + //{ + // //获取本机的IP地址和MAC地址.... + // string AddressIP = string.Empty; + // if (string.IsNullOrEmpty(app.LocalIP)) + // { + // foreach (IPAddress _IPAddress in Dns.GetHostEntry(Dns.GetHostName()).AddressList) + // { + // if (_IPAddress.AddressFamily.ToString() == "InterNetwork") + // { + // AddressIP = _IPAddress.ToString(); + // } + // } + // } + // else { + // AddressIP = app.LocalIP; + // } + + // httpclient.message = ""; + // string sendmsg = "IP="+ AddressIP; + + // httpclient.url = app.HttpUrl + "/Container/GetContainerBGByScreen"; + // httpclient.message = sendmsg; + // string rev = httpclient.HttpPost(); + + // Dictionary dic = JsonConvert.DeserializeObject>(rev); + // if (dic["data"] != null && dic["code"].ToString() == "200") + // { + // app.bgPath = string.IsNullOrEmpty(dic["data"].ToString())?"": dic["data"].ToString(); + // if (!string.IsNullOrEmpty(app.bgPath)) + // { + // string filefolder = AppDomain.CurrentDomain.BaseDirectory + "/bgfile"; + // try + // { + // if (!Directory.Exists(filefolder)) + // { + // DirectoryInfo directoryInfo = new DirectoryInfo(filefolder); + // directoryInfo.Create(); + // } + // } + // catch (Exception ex) + // { + // log.WriteLogFile(ex.ToString()); + + // } + // HttpClient httpClient = new HttpClient(); + // string newname = Directory.GetCurrentDirectory() + "/exefile/PCScreen/pic/bg.png"; + // if (File.Exists(newname)) { + // File.Delete(newname); + // } + // string fileName = ""; + // httpClient.DownLoadImage(app.bgPath, "bgfile", ref fileName); + + // var nf = Path.Combine(newname);//将新的文件名称路径字符串结合成路径。 + // File.Copy(fileName, nf);//进行文件复制,第一个参数是需要复制的文件路径,第二个参数是目标文件夹中文件路径 + // //string bgName = "bg.png"; + // //httpClient.DownLoadImage(app.bgPath, "exefile/PCScreen/pic", ref bgName); + // if (app.pageBg == null) + // { + // app.pageBg = new BGPage(); + // app.pageBg.LoadImage(fileName); + // app.pageBg.Show(); + // } + // else + // { + // app.pageBg.LoadImage(fileName); + // } + // } + // else { + // if (app.pageBg == null) + // { + // app.pageBg = new BGPage(); + // app.pageBg.LoadImage(""); + // app.pageBg.Show(); + // } + // else + // { + // app.pageBg.LoadImage(""); + // } + // } + // return true; + // } + + // return false; + //} + //catch (Exception ex) + //{ + // log.WriteLogFile("设备信息上传失败" + ex.ToString(), "HttpMessageErrorLog"); + // return false; + //} + } + + + + /// + /// 下载应用程序 + /// + //public string DownLoadexe(List appList, ref string Errorlog) + //{ + // try + // { + // string filename = ""; + // app.appUrl = app.appUrl.Replace("\\", "/"); + // if (app.appUrl.Contains("/")) + // filename = app.appUrl.Substring(app.appUrl.LastIndexOf("/")); + // else + // return ""; + // //string localFile = AppDomain.CurrentDomain.BaseDirectory + "zipfile/" + filename;//本地地址 + // //string Unzippath = AppDomain.CurrentDomain.BaseDirectory + "exefile/" + filename;//本地地址 + // bool result = false; + // string iconpath = ""; + // ExeModel appModel = appList.Where(i => i.AppID == app.Appdowninfo.AppID).FirstOrDefault(); + // var appDownFlag = false; + // if (app.appUrl.LastIndexOf(".exe") >= 0) { + // appDownFlag = httpclient.DownLoadFilesExe(appModel, app.appUrl, ref filename); + // } + // else { + // appDownFlag = httpclient.DownLoadFiles(appModel, app.appUrl, ref filename); + // } + // if (appDownFlag && httpclient.DownLoadIcon(appModel,app.icourl, ref iconpath)) + // { + // log.WriteLogFile("iconpath:"+iconpath); + // app.Appdowninfo.icopath = iconpath; + // Class_Config con = new Class_Config(); + // //if (app.AppUpdate == false) + // //{ + // result = con.WriteToExeConfig(app.Appdowninfo); + // if (app.Appdowninfo.exename.ToLower().Equals(app.defaultFile.ToLower())) { + // app.configstartexe =string.IsNullOrEmpty(app.Appdowninfo.exestartname)? app.Appdowninfo.exepath:(app.Appdowninfo.exepath + "/"+ app.Appdowninfo.exestartname); + // } + // var model = new ExeModel(); + // model.AppID = app.Appdowninfo.AppID; + // model.exename = app.Appdowninfo.exename; + // model.exepath = app.Appdowninfo.exepath; + // model.exestartname = app.Appdowninfo.exestartname; + // model.icopath = app.Appdowninfo.icopath; + // model.Version = app.Appdowninfo.Version; + // app.NowAppList.Add(model); + // //} + // //else + // //{ + // // result = con.WriteToExeConfig(app.Appdowninfo); + // //} + + // if (result) + // return filename;//返回应用程序文件名 + // else + // return ""; + // } + // return ""; + // } + // catch (Exception ex) + // { + // log.WriteLogFile("下载文件信息失败" + ex.ToString(), "HttpMessageErrorLog"); + // return ""; + // } + //} + + /// + /// 上传下载状态 + /// + public string UpLoadDownLoadState(ref string Errorlog,string state) + { + try + { + httpclient.message = ""; + httpclient.url = app.HttpUrl + "/Device/DeviceFeedback"; + string sendmsg = "State=" + state + + + "&Type=DownloadApp" //+ app.appName + + + "&Parameter=" + app.appName + + + "&IP=" + app.LocalIP; + + httpclient.message = sendmsg; + + string rev = httpclient.HttpPost(); + Dictionary dic = JsonConvert.DeserializeObject>(rev); + if (dic["msg"] != null) + Errorlog = dic["msg"].ToString(); + if (dic["code"].ToString() == "200") + { + //解析楼层信息应该是List + //app.Floors = JsonConvert.DeserializeObject>(dic["data"].ToString()); + return ""; + } + return "上传失败"; + } + catch (Exception ex) + { + + log.WriteLogFile("下载文件信息失败" + ex.ToString(), "HttpMessageErrorLog"); + return ""; + } + } + /// + /// 上传图片 + /// + public string UpLoadImg(ref string Errorlog, string img, string imgname,string userName,string type) + { + try + { + + if (string.IsNullOrEmpty(app.LocalIP)) + { + foreach (IPAddress _IPAddress in Dns.GetHostEntry(Dns.GetHostName()).AddressList) + { + if (_IPAddress.AddressFamily.ToString() == "InterNetwork") + { + app.LocalIP = _IPAddress.ToString(); + } + } + } + string sendmsg = string.Empty ; + if (type.Equals("local")) { + httpclient.url = app.HttpUrl + "/api/Dev/UploadScreenshot";//接口地址 + sendmsg = "{\"Code\":\"" + app.deviceid + "\",\"FileName\":\"" + imgname + "\"}"; + } else { + httpclient.url = app.HttpUrl + "/SaasLive/Manage/UploadScreenshot";//接口地址 + sendmsg = "{\"Code\":\"" + app.deviceid + "\",\"FileName\":\"" + imgname + "\",\"UserName\":\""+ userName + "\"}"; + } + httpclient.message = sendmsg; + log.WriteLogFile(httpclient.url, "HttpMessageErrorLog"); + string rev = httpclient.HttpUploadFile(httpclient.url, img, httpclient.message); + + Dictionary dic = JsonConvert.DeserializeObject>(rev); + Errorlog = dic["msg"].ToString(); + if (dic["data"] != null && dic["code"].ToString() == "200")//成功并且返回下载地址不为空 + { + return "true";//返回应用程序文件名 + } + return ""; + } + catch (Exception ex) + { + log.WriteLogFile("上传截屏信息失败" + ex.ToString(), "HttpMessageErrorLog"); + return ""; + } + } + + + /// + /// 设置触摸屏操作 + /// + public bool ScreenOperSuccess(int status) + { + try + { + string MethodStr = "/API/Dev/SetOperable"; + var data = new { Code = app.deviceid, Status = status }; + var ret = MyHttpClient.CryptPost(MethodStr, data); + if (!string.IsNullOrEmpty(ret)) + { + var Jo = JObject.Parse(ret); + string code = Jo.Value("code"); + if (code == "200") + { + return true; + } + else { + return false; + } + } + return false; + } + catch (Exception ex) + { + log.WriteLogFile("设置触摸屏操作失败" + ex.ToString(), "HttpMessageErrorLog"); + return false; + } + } + + public bool LoadCurrentLive() + { + try + { + httpclient.message = ""; + string sendmsg = "{\"MallCode\":\"" + app.live.MallCode + "\"}"; + log.WriteLogFile(app.live.SenderID, "CurrentLiv"); + httpclient.url = app.live.SenderID + "/api/Order/GetCurrentLive"; + httpclient.message = sendmsg; + string rev = httpclient.PostMoths(httpclient.message, httpclient.url); + log.WriteLogFile(rev, "CurrentLiv"); + Dictionary dic = JsonConvert.DeserializeObject>(rev); + if (dic["data"] != null && dic["code"].ToString() == "200") + { + if (dic["data"].ToString().Trim().Equals("")) + return false; + string mes = dic["data"].ToString(); + //解析漏洞信息应该是List + //app.Buildinginfo.Clear(); + log.WriteLogFile(dic["data"].ToString()); + CurrentLive live = JsonConvert.DeserializeObject(dic["data"].ToString()); + app.curLive = live; + return true; + } + + return false; + } + catch (Exception ex) + { + log.WriteLogFile("获取直播信息失败" + ex.ToString(), "CurrentLivErrorLog"); + return false; + } + } + + + + } +} diff --git a/Container/Services/WebSocketForKiosk.cs b/Container/Services/WebSocketForKiosk.cs new file mode 100644 index 0000000..b01cb8b --- /dev/null +++ b/Container/Services/WebSocketForKiosk.cs @@ -0,0 +1,175 @@ +using Container.Business; +using Container.Common; +using Container.Model; +using Container.Win; +using Fleck; +using System; +using System.Collections.Generic; +using System.Configuration; +using System.Diagnostics; +using System.Linq; +using System.Runtime.InteropServices; +using System.Text; +using System.Threading.Tasks; +using System.Windows; + +namespace Container.Services +{ + public class WebSocketForKiosk + { + [DllImport("user32.dll", SetLastError = true)] + static extern IntPtr FindWindow(string IpClassName, string IpWindowName); + public static List allSocketsForKiosk = new List(); + private Class_Log log = new Class_Log(); + App app = ((App)Application.Current); + PlayBackManage pbm = new PlayBackManage(); + public void openSocket() + { + FleckLog.Level = LogLevel.Debug; + var ws = ConfigurationManager.AppSettings["websocketForKiosk"]; + var server = new WebSocketServer(ws); + server.Start(socket => + { + socket.OnOpen = () => //当建立Socket链接时执行此方法 + { + //var data = socket.ConnectionInfo; //通过data可以获得这个链接传递过来的Cookie信息,用来区分各个链接和用户之间的关系(如果需要后台主动推送信息到某个客户的时候,可以使用Cookie) + allSocketsForKiosk.Add(socket); + }; + + socket.OnClose = () =>// 当关闭Socket链接十执行此方法 + { + //Console.WriteLine("Close!"); + allSocketsForKiosk.Remove(socket); + }; + + socket.OnMessage = message =>// 接收客户端发送过来的信息 + { + log.WriteLogFile(message, "kiosk"); + if (message.Contains("version")) + { + app.kioskVersion = message.Substring(message.LastIndexOf(':') + 1); + app.Appversion = app.kioskVersion; + app.AppPlayNameCH = "导视"; + app.AppPlayName = "chrome"; + app.CurAppPlayName = app.AppPlayName; + WebSocketForKiosk.allSocketsForKiosk.ToList().ForEach(s => s.Send("kiosk")); + } + else if (message == "startexplorer") + { + + Process[] pro = Process.GetProcesses(); + for (int i = 0; i < pro.Length; i++) + { + //if (pro[i].ProcessName.ToLower() == "chrome" ) + if (pro[i].ProcessName.ToLower() == "chrome") + { + pro[i].CloseMainWindow(); + } + } + + System.Diagnostics.Process process = new System.Diagnostics.Process(); + System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo(); + startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; + startInfo.FileName = "cmd.exe"; + process.StartInfo = startInfo; + process.StartInfo.RedirectStandardInput = true; + process.StartInfo.RedirectStandardOutput = true; + process.StartInfo.UseShellExecute = false; + process.Start(); + process.StandardInput.WriteLine(Environment.GetEnvironmentVariable("windir") + "\\explorer.exe"); + process.StandardInput.Flush(); + process.StandardInput.Close(); + process.WaitForExit(); + deleteSchtasks("ContainerService"); + //Environment.Exit(0); + } + else if (message == "pcscreensavers") + { + bool pcstart = false; + IntPtr Win = FindWindow(null, "WindowView");//设置置顶 + if (Win != null && Win != IntPtr.Zero) + { + pcstart = true; + //SetWindowPos(Win, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE); + } + if (!pcstart) + { + App.Current.Dispatcher.Invoke((Action)(() => + { + try + { + //app.IsCanConnect = MyHttpClient.IsCanConnect(app.HttpUrl); + //if (app.IsCanConnect) + //{ + List result = pbm.GetResource(); + //ScreenSavers result = pbm.GetResourceForLoad(); + if ((result != null && result.Count > 0)) + { + app.AppPlayNameCH = "信息发布"; + app.CurAppPlayName = "pcscreensavers"; + app.AppPlayName = "pcscreensavers"; + app.Appversion = app.Containerversion; + WindowViewNew windowView = new WindowViewNew(0); + windowView.Show(); + } + //} + //else + //{ + // List> result = pbm.GetResource(1); + // if (result != null && result.Count > 0) + // { + // app.AppPlayNameCH = "信息发布"; + // app.CurAppPlayName = "pcscreensavers"; + // app.AppPlayName = "pcscreensavers"; + // app.Appversion = app.Containerversion; + // WindowView windowView = new WindowView(0); + // windowView.Show(); + // } + //} + + } + catch (Exception ex) + { + log.WriteLogFile(ex.ToString(), "errorrrr"); + } + })); + } + } + }; + }); + + } + + private void deleteSchtasks(string schtaskName) + { + try + { + Process MyProcess = new Process(); + //设定程序名 + MyProcess.StartInfo.FileName = "cmd.exe"; + + //关闭Shell的使用 + MyProcess.StartInfo.UseShellExecute = false; + //重定向标准输入 + MyProcess.StartInfo.RedirectStandardInput = true; + //重定向标准输出 + MyProcess.StartInfo.RedirectStandardOutput = true; + //重定向错误输出 + MyProcess.StartInfo.RedirectStandardError = true; + //设置不显示窗口 + MyProcess.StartInfo.CreateNoWindow = true; + string cmdtext = "schtasks /delete /tn " + schtaskName + " -f"; //关机 + log.WriteLogFile(cmdtext, "cmdexelog"); + + //执行VER命令 + MyProcess.Start(); + + MyProcess.StandardInput.WriteLine(cmdtext); + } + catch (Exception ex) + { + log.WriteLogFile(ex.ToString()); + } + } + } +} diff --git a/Container/Services/WebSocketManage.cs b/Container/Services/WebSocketManage.cs new file mode 100644 index 0000000..77567a8 --- /dev/null +++ b/Container/Services/WebSocketManage.cs @@ -0,0 +1,478 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using Transitionals; +using WebSocket4Net; +using System.Configuration; +using Container.Common; +using System.IO; +using System.Threading; +using System.Windows; +using Newtonsoft.Json; +using System.Net; +using Container.Business; + +namespace Container.Services +{ + public class WebSocketManage + { + private WebSocket websocket = null; + App app = ((App)System.Windows.Application.Current); + public delegate void WebSocketReceiveDelegate(string type, string message); + public static event WebSocketReceiveDelegate WebSocketReceiveEvent; + private Class_Log log = new Class_Log(); + private HttpClient httpclient = new HttpClient(); + private Class_Config con = new Class_Config(); + bool reconnect = false; + #region WebSocketClient + + public void OpenWebSocket() + { + try + { + if (string.IsNullOrEmpty(app.LocalIP)) + { + foreach (IPAddress _IPAddress in Dns.GetHostEntry(Dns.GetHostName()).AddressList) + { + if (_IPAddress.AddressFamily.ToString() == "InterNetwork") + { + app.LocalIP = _IPAddress.ToString(); + } + } + } + string sendmsg = "ip=" + app.LocalIP; + websocket = new WebSocket(app.configwebsocket + "?"+ sendmsg);// 地址 + + websocket.Error += new EventHandler(websocket_Error); + websocket.MessageReceived += new EventHandler(websocket_MessageReceived); + websocket.Open(); + //websocket.Opened += new EventHandler(websocket_Opened); + websocket.Closed += new EventHandler(websocket_Closed); + } + catch (Exception ex) + { + log.WriteLogFile(ex.ToString()); + } + } + + void websocket_Closed(object sender, EventArgs e) + { + if (!reconnect) + { + reconnect = true; + ReConnect(); + } + } + + public void CloseWebSocket() + { + //if (websocket != null) + // websocket.Close(); + } + + void websocket_MessageReceived(object sender, MessageReceivedEventArgs e) + { + try + { + log.WriteLogFile(e.Message, "WebSocketLog"); + + string type = ""; + Dictionary dic = Newtonsoft.Json.JsonConvert.DeserializeObject>(e.Message.ToLower()); + 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["name"].ToString())) + //{ + // app.appName = Commands["name"].ToString(); + // app.Appdowninfo.exename = Commands["name"].ToString(); + //} + //if (!string.IsNullOrEmpty(Commands["filepath"].ToString())) + //{ + // app.appUrl = dic["senderid"].ToString().TrimEnd('/') + Commands["filepath"].ToString(); + + //} + //if (!string.IsNullOrEmpty(Commands["appnameen"].ToString())) + //{ + // app.Appdowninfo.exestartname = Commands["appnameen"].ToString(); + //} + //if (!string.IsNullOrEmpty(Commands["iconfilepath"].ToString())) + //{ + // app.icourl = dic["senderid"].ToString().TrimEnd('/') + 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(); + //} + } + 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 = ""; + //if (!string.IsNullOrEmpty(Commands["appid"].ToString())) + //{ + // app.AppDownCode = Commands["appid"].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; + } + } + //app.AppUpdate = true; + //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 = dic["senderid"].ToString().TrimEnd('/') + Commands["filepath"].ToString(); + + //} + + //if (!string.IsNullOrEmpty(Commands["appnameen"].ToString())) + //{ + // app.Appdowninfo.exestartname = Commands["appnameen"].ToString(); + //} + //if (!string.IsNullOrEmpty(Commands["iconfilepath"].ToString())) + //{ + // app.icourl = dic["senderid"].ToString().TrimEnd('/') + Commands["iconfilepath"].ToString(); + //} + //if (!string.IsNullOrEmpty(Commands["appid"].ToString())) + //{ + // app.Appdowninfo.AppID = Commands["appid"].ToString(); + //} + } + 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())) + { + Dictionary dicNum = Newtonsoft.Json.JsonConvert.DeserializeObject>(e.Message); + Dictionary CommandsNum = JsonConvert.DeserializeObject>(dicNum["Content"].ToString()); + app.devicemark = CommandsNum["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("updateprog")) { + PlayBackManage pbm = new PlayBackManage(); + pbm.DownResource(); + } + } + if (WebSocketReceiveEvent != null) + { + WebSocketReceiveEvent(type, ""); + } + } + catch (Exception ex) + { + log.WriteLogFile(ex.ToString(), "WebSocketLog"); + + } + } + + void websocket_Error(object sender, SuperSocket.ClientEngine.ErrorEventArgs e) + { + + log.WriteLogFile(e.Exception.Message + e.Exception.StackTrace,"WebSocketErrorLog"); + //try + //{ + // if (websocket != null) + // websocket.Close(); + //} + //catch + //{ + //} + //ReConnect(); + } + + /// + /// websocket重连 + /// + private void ReConnect() + { + try + { + Action ac = new Action(() => + { + while (true) + { + try + { + if (websocket.State == WebSocketState.Closed) + { + Thread.Sleep(30000); + + if (websocket.State == WebSocketState.Closed) + websocket.Open(); + } + + if (websocket.State == WebSocketState.Open) + { + //reconnect = false; + break; + } + } + catch (Exception ex) + { + log.WriteLogFile(ex.ToString(), "WebSocketErrorLog"); + } + finally + { + Thread.Sleep(3000); + } + + + } + }); + ac.BeginInvoke((o) => + { + reconnect = false; + }, null); + } + catch (Exception ex) + { + log.WriteLogFile(ex.ToString(), "WebSocketErrorLog"); + } + } + + #endregion + } +} diff --git a/Container/Services/WebSocketManageForLive.cs b/Container/Services/WebSocketManageForLive.cs new file mode 100644 index 0000000..949f353 --- /dev/null +++ b/Container/Services/WebSocketManageForLive.cs @@ -0,0 +1,345 @@ +using Container.Common; +using Container.Model; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Configuration; +using System.IO; +using System.Runtime.InteropServices; +using System.Runtime.Serialization; +using System.Runtime.Serialization.Formatters.Binary; +using System.Threading; +using System.Windows; +using WebSocket4Net; + +namespace Container.Services +{ + public class WebSocketManageForLive + { + private WebSocket websocket = null; + App app = ((App)System.Windows.Application.Current); + public delegate void WebSocketReceiveDelegate(string type, string message); + public static event WebSocketReceiveDelegate WebSocketReceiveEvent; + private Class_Log log = new Class_Log(); + bool reconnect = false; + #region WebSocketClient + + public void OpenWebSocket() + { + try + { + log.WriteLogFile(app.deviceid, "live"); + string sendmsg = "ip=" + app.deviceid; + websocket = new WebSocket(ConfigurationManager.AppSettings["websocketForLive"] + "?" + sendmsg);// 地址 + log.WriteLogFile(ConfigurationManager.AppSettings["websocketForLive"], "live"); + websocket.Error += new EventHandler(websocket_Error); + websocket.MessageReceived += new EventHandler(websocket_MessageReceived); + websocket.Open(); + //websocket.Opened += new EventHandler(websocket_Opened); + websocket.Closed += new EventHandler(websocket_Closed); + } + catch (Exception ex) + { + log.WriteLogFile(ex.ToString()); + } + } + + void websocket_Closed(object sender, EventArgs e) + { + if (!reconnect) + { + reconnect = true; + ReConnect(); + } + } + + public void CloseWebSocket() + { + //if (websocket != null) + // websocket.Close(); + } + + void websocket_MessageReceived(object sender, MessageReceivedEventArgs e) + { + try + { + log.WriteLogFile(e.Message, "WebSocketForLiveLog"); + + string type = ""; + Dictionary dic = Newtonsoft.Json.JsonConvert.DeserializeObject>(e.Message); + if (dic["Content"] != null && dic["SenderID"] != null) + { + Dictionary Commands = JsonConvert.DeserializeObject>(dic["Content"].ToString()); + + if (!string.IsNullOrEmpty(Commands["Type"].ToString())) + { + type = Commands["Type"].ToString().ToLower(); + } + if (type.Trim().Equals("live")) + { + string liveCode = string.Empty; + string mallCode = string.Empty; + //Live live = JsonConvert.DeserializeObject(Commands["parameter"].ToString()); + //app.live.HFilePath = live.HFilePath; + //app.live.Likes = live.Likes; + //app.live.LiveCode = live.LiveCode; + //app.live.liveurl = live.liveurl; + //app.live.MallCode = live.MallCode; + //app.live.SenderID = live.SenderID; + //app.live.VFilePath = live.VFilePath; + //app.live.WatchNum = live.WatchNum; + //app.live = live; + Dictionary liveData = JsonConvert.DeserializeObject>(Commands["Parameter"].ToString()); + if (!string.IsNullOrEmpty(liveData["MallCode"].ToString())) + { + mallCode = liveData["MallCode"].ToString(); + } + if (!string.IsNullOrEmpty(liveData["LiveCode"].ToString())) + { + liveCode = liveData["LiveCode"].ToString(); + } + app.live.LiveCode = liveCode; + app.live.MallCode = mallCode; + app.live.MallName = string.IsNullOrEmpty(liveData["MallName"].ToString()) ? "" : liveData["MallName"].ToString(); + app.live.QRCode = string.IsNullOrEmpty(liveData["QrCode"].ToString()) ? "" : liveData["QrCode"].ToString(); + app.live.ShopName = string.IsNullOrEmpty(liveData["shopName"].ToString()) ? "" : liveData["shopName"].ToString(); + string livePath = string.Empty; + if (!string.IsNullOrEmpty(liveData["liveurl"].ToString())) + { + livePath = liveData["liveurl"].ToString(); + } + app.live.LiveUrl = livePath; + app.live.FloorName = string.IsNullOrEmpty(liveData["floorName"].ToString()) ? "" : liveData["floorName"].ToString(); + app.live.HouseNum = string.IsNullOrEmpty(liveData["HouseNum"].ToString()) ? "" : liveData["HouseNum"].ToString(); + app.live.LogoPath = string.IsNullOrEmpty(liveData["LogoPath"].ToString()) ? "" : liveData["LogoPath"].ToString(); + var senderid = dic["SenderID"].ToString(); + app.live.SenderID = senderid.LastIndexOf('/') == senderid.Length - 1 ? senderid.Substring(0, senderid.LastIndexOf('/')) : senderid; + app.live.HFilePath = string.IsNullOrEmpty(liveData["HFilePath"].ToString()) ? "" : liveData["HFilePath"].ToString(); + app.live.VFilePath = JsonConvert.DeserializeObject>(liveData["VFilePath"].ToString()); + + app.live.CouponInfo = liveData["couponInfo"] ==null?null: JsonConvert.DeserializeObject(liveData["couponInfo"].ToString()); + log.WriteLogFile("------" + JsonConvert.SerializeObject(app.live.CouponInfo), "222"); + } + else if (type.Trim().Equals("shutdownlive")) + { + app.live.LiveUrl = ""; + app.live.HFilePath = ""; + app.live.VFilePath = new List(); + app.live.LiveCode = ""; + app.live.MallCode = ""; + app.live.OldLiveCode = ""; + } + else if (type.Trim().Equals("like") || type.Trim().Equals("watchnum")) + { + Dictionary liveData = JsonConvert.DeserializeObject>(Commands["Parameter"].ToString()); + app.live.Likes = Convert.ToInt32(liveData["Likes"].ToString()); + app.live.WatchNum = Convert.ToInt32(liveData["WatchNum"].ToString()); + } + else if (type.Trim().Equals("livecoupon")||type.Trim().Equals( "getcoupon")) + { + app.live.CouponInfo = JsonConvert.DeserializeObject(Commands["Parameter"].ToString()); + app.curLive.CouponInfo = app.live.CouponInfo; + } + else if (type.Trim().Equals("shutdowncoupon")) + { + app.live.CouponInfo = null; + app.curLive.CouponInfo = null; + } + else if (type.Trim().Equals("playprog")) + { + Dictionary progData = JsonConvert.DeserializeObject>(Commands["Parameter"].ToString()); + if (!string.IsNullOrEmpty(progData["ServerTime"].ToString())) + { + WebSocketManageForLive.SetLocalTimeByStr(progData["ServerTime"].ToString()); + string closeTime = Convert.ToDateTime(progData["ServerTime"]).AddHours(1).ToString("yyyy-MM-dd HH" + ":00:00"); + app.CloseServerTime = Convert.ToDateTime(closeTime); + } + List itemList = JsonConvert.DeserializeObject>(progData["Orders"].ToString()); + if (app.ScreenWidth > app.ScreenHeight) + { + itemList = itemList.FindAll(i => i.OrderType == 1); + } + else + { + itemList = itemList.FindAll(i => i.OrderType == 2); + } + foreach (var item in itemList) + { + HttpClient httpClient = new HttpClient(); + string fileName = ""; + + if (httpClient.DownLoadImage(item.FilePath, "BrandImageFile", ref fileName)) + { + item.FilePath = fileName; + } + else + { + log.WriteLogFile("商户发布广告图下载失败"); + } + } + app.playProgList = itemList; + } + else if (type.Trim().Equals("shutdownprog")) + { + Dictionary progData = JsonConvert.DeserializeObject>(Commands["Parameter"].ToString()); + if (!string.IsNullOrEmpty(progData["ServerTime"].ToString())) + { + WebSocketManageForLive.SetLocalTimeByStr(progData["ServerTime"].ToString()); + string closeTime = Convert.ToDateTime(progData["ServerTime"]).AddHours(1).ToString("yyyy-MM-dd HH" + ":00:00"); + app.CloseServerTime = Convert.ToDateTime(closeTime); + } + List itemList = JsonConvert.DeserializeObject>(progData["Orders"].ToString()); + app.shutDownProgList = itemList; + //List deepCopyList = Clone(app.playProgList); + //foreach (var item in app.playProgList) + //{ + // if (itemList.FindAll(i => i.Code == item.Code).Count > 0) + // { + // deepCopyList.Remove(item); + // } + //} + //app.playProgList = deepCopyList; + } + } + if (WebSocketReceiveEvent != null) + { + WebSocketReceiveEvent(type, ""); + } + } + catch (Exception ex) + { + log.WriteLogFile(ex.ToString(), "WebSocketLogLive"); + + } + } + /// + /// Clones the specified list. + /// + /// + /// The list. + /// List{``0}. + public List Clone(object List) + { + using (Stream objectStream = new MemoryStream()) + { + IFormatter formatter = new BinaryFormatter(); + formatter.Serialize(objectStream, List); + objectStream.Seek(0, SeekOrigin.Begin); + return formatter.Deserialize(objectStream) as List; + } + } + + [DllImport("Kernel32.dll")] + public static extern bool SetLocalTime(ref SystemTime sysTime); + + [StructLayout(LayoutKind.Sequential)] + public struct SystemTime + { + [MarshalAs(UnmanagedType.U2)] + public short wYear; + [MarshalAs(UnmanagedType.U2)] + public short wMonth; + [MarshalAs(UnmanagedType.U2)] + public short wDayOfWeek; + [MarshalAs(UnmanagedType.U2)] + public short wDay; + [MarshalAs(UnmanagedType.U2)] + public short wHour; + [MarshalAs(UnmanagedType.U2)] + public short wMinute; + [MarshalAs(UnmanagedType.U2)] + public short wSecond; + [MarshalAs(UnmanagedType.U2)] + public short wMilliseconds; + } + + public static bool SetLocalTimeByStr(string timestr) + { + bool flag = false; + SystemTime sysTime = new SystemTime(); + DateTime dt = Convert.ToDateTime(timestr); + sysTime.wYear = Convert.ToInt16(dt.Year); + sysTime.wMonth = Convert.ToInt16(dt.Month); + sysTime.wDay = Convert.ToInt16(dt.Day); + sysTime.wHour = Convert.ToInt16(dt.Hour); + sysTime.wMinute = Convert.ToInt16(dt.Minute); + sysTime.wSecond = Convert.ToInt16(dt.Second); + try + { + flag = WebSocketManageForLive.SetLocalTime(ref sysTime); + } + catch (Exception e) + { + Console.WriteLine("SetSystemDateTime函数执行异常" + e.Message); + } + return flag; + } + + void websocket_Error(object sender, SuperSocket.ClientEngine.ErrorEventArgs e) + { + + log.WriteLogFile(e.Exception.Message + e.Exception.StackTrace, "WebSocketErrorLog"); + //try + //{ + // if (websocket != null) + // websocket.Close(); + //} + //catch + //{ + //} + //ReConnect(); + } + + /// + /// websocket重连 + /// + private void ReConnect() + { + try + { + Action ac = new Action(() => + { + while (true) + { + try + { + if (websocket.State == WebSocketState.Closed) + { + Thread.Sleep(30000); + + if (websocket.State == WebSocketState.Closed) + websocket.Open(); + } + + if (websocket.State == WebSocketState.Open) + { + //reconnect = false; + break; + } + } + catch (Exception ex) + { + log.WriteLogFile(ex.ToString(), "WebSocketErrorLog"); + } + finally + { + Thread.Sleep(3000); + } + + + } + }); + ac.BeginInvoke((o) => + { + reconnect = false; + }, null); + } + catch (Exception ex) + { + log.WriteLogFile(ex.ToString(), "WebSocketErrorLog"); + } + } + + #endregion + } +} diff --git a/Container/Viewmodel/BuildingViewModel.cs b/Container/Viewmodel/BuildingViewModel.cs new file mode 100644 index 0000000..4aa0ae5 --- /dev/null +++ b/Container/Viewmodel/BuildingViewModel.cs @@ -0,0 +1,185 @@ +using Container.Model; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Microsoft.Practices.Prism.ViewModel; +using Microsoft.Practices.Prism.Commands; +using System.ComponentModel; +using System.Windows; +using Container.Services; + +namespace Container.Viewmodel +{ + public class BuildingViewModel : NotificationObject + { + //public event PropertyChangedEventHandler PropertyChanged; + /// + /// 当ComboBox选中项更改时发生 + /// + //public BuildingModel BuildingModel { set; get; } + + private string Code; + + public string code + { + get { return Code; } + set + { + Code = value; + this.RaisePropertyChanged("Code"); + } + } + + private string NAME; + + public string name + { + get { return NAME; } + set + { + NAME = value; + this.RaisePropertyChanged("ID"); + } + } + private bool isSelected; + + public bool IsSelected + { + get { return isSelected; } + set + { + isSelected = value; + this.RaisePropertyChanged("isSelected"); + } + } + + //private BuildingModel _selectLocation; + //public BuildingModel SelectLocation + //{ + // get + // { + // return this._selectLocation; + // } + // set + // { + // this._selectLocation = value; + // if (this.PropertyChanged != null) + // PropertyChanged(this, new PropertyChangedEventArgs("SelectLocation")); + // } + //} + + //private ObservableCollection _locationRoad = null; + } + + public class BuildingOperate : NotificationObject + { + public DelegateCommand DetailPlaceOrderCom { get; set; } + public DelegateCommand SelectMenuItemCom { get; set; } + private List buildingMenu; + + public List BuildingMenu + { + get { return buildingMenu; } + set + { + buildingMenu = value; + this.RaisePropertyChanged("buildingMenu"); + } + } + private string buildingid; + + public string BuildingID + { + get { return buildingid; } + set + { + buildingid = value; + this.RaisePropertyChanged("buildingid"); + } + } + + public BuildingOperate(int type) + { + LoadBuilding(type); + } + public void LoadBuilding(int type) + { + App app = ((App)Application.Current); + if (type == 1) + { + this.BuildingMenu = new List(); + for (int i = 0; i < app.Buildinginfo.Count; i++) + { + BuildingViewModel Buildinginfo = new BuildingViewModel(); + Building BuildingsInfo = (Building)app.Buildinginfo[i]; + Buildinginfo.code = BuildingsInfo.code; + Buildinginfo.name = BuildingsInfo.buildingName; + Buildinginfo.IsSelected = false; + BuildingMenu.Add(Buildinginfo); + //app.Buildings.FindAll(p => p.BNAME == ""); + } + } + else + if (type == 2) + { + this.BuildingMenu = new List(); + for (int i = 0; i < app.Floors.Count; i++) + { + BuildingViewModel Building = new BuildingViewModel(); + Floor BuildingsInfo = (Floor)app.Floors[i]; + Building.code = BuildingsInfo.code; + Building.name = BuildingsInfo.floorName; + Building.IsSelected = false; + BuildingMenu.Add(Building); + + } + } + else if (type == 3) + { + this.BuildingMenu = new List(); + for (int i = 0; i < app.DeviceTypeList.Count; i++) + { + BuildingViewModel Buildinginfo = new BuildingViewModel(); + DeviceType BuildingsInfo = (DeviceType)app.DeviceTypeList[i]; + Buildinginfo.code = BuildingsInfo.code; + Buildinginfo.name = BuildingsInfo.dictValue; + Buildinginfo.IsSelected = false; + BuildingMenu.Add(Buildinginfo); + //app.Buildings.FindAll(p => p.BNAME == ""); + } + } + else if (type == 4) { + this.BuildingMenu = new List(); + BuildingViewModel Buildinginfo = new BuildingViewModel(); + Buildinginfo.code = "本地部署"; + Buildinginfo.IsSelected = false; + BuildingMenu.Add(Buildinginfo); + + BuildingViewModel Buildinginfo1 = new BuildingViewModel(); + Buildinginfo1.code = "前置离线"; + Buildinginfo1.IsSelected = false; + BuildingMenu.Add(Buildinginfo1); + + BuildingViewModel Buildinginfo2 = new BuildingViewModel(); + Buildinginfo2.code = "直联云"; + Buildinginfo2.IsSelected = false; + BuildingMenu.Add(Buildinginfo2); + } + this.DetailPlaceOrderCom = new DelegateCommand(new Action(this.BuildingNAMEOrderComExecute)); + this.SelectMenuItemCom = new DelegateCommand(new Action(this.SelectMenuItemComExecute)); + + } + + private void BuildingNAMEOrderComExecute() + { + var selectedDishes = this.BuildingMenu.Where(i => i.IsSelected == true).Select(i => i.name).ToList(); + } + private void SelectMenuItemComExecute() + { + this.BuildingID = this.BuildingMenu.Where(i => i.IsSelected == true).Select(i => i.code).ToString(); + } + + } +} diff --git a/Container/Viewmodel/FormItemModel.cs b/Container/Viewmodel/FormItemModel.cs new file mode 100644 index 0000000..ff45ce8 --- /dev/null +++ b/Container/Viewmodel/FormItemModel.cs @@ -0,0 +1,57 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Container.Viewmodel +{ + /// + /// 表单数据项 + /// + public class FormItemModel + { + /// + /// 表单键,request["key"] + /// + public string Key { set; get; } + /// + /// 表单值,上传文件时忽略,request["key"].value + /// + public string Value { set; get; } + /// + /// 是否是文件 + /// + public bool IsFile + { + get + { + if (FileContent == null || FileContent.Length == 0) + return false; + + if (FileContent != null && FileContent.Length > 0 && string.IsNullOrWhiteSpace(FileName)) + throw new Exception("上传文件时 FileName 属性值不能为空"); + return true; + } + } + /// + /// 上传的文件名 + /// + public string FileName { set; get; } + + /// + /// 上传的文件名 + /// + public string voiceCode { set; get; } + + /// + /// 上传的文件名 + /// + public string mallCode { set; get; } + /// + /// 上传的文件内容 + /// + public Stream FileContent { set; get; } + } +} diff --git a/Container/Viewmodel/RabbitMQModel.cs b/Container/Viewmodel/RabbitMQModel.cs new file mode 100644 index 0000000..9208aac --- /dev/null +++ b/Container/Viewmodel/RabbitMQModel.cs @@ -0,0 +1,19 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Container.Viewmodel +{ + class RabbitMQModel + { + public string UserName { get; set; } + + public string Password { get; set; } + + public string HostName { get; set; } + + public int Port { get; set; } + } +} diff --git a/Container/Viewmodel/WeatherViewModel.cs b/Container/Viewmodel/WeatherViewModel.cs new file mode 100644 index 0000000..05d23ef --- /dev/null +++ b/Container/Viewmodel/WeatherViewModel.cs @@ -0,0 +1,23 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Container.Viewmodel +{ + public class WeatherViewModel + { + public string windPower { get; set; } + + public string humidity { get; set; } + + public string pm25 { get; set; } + + public string aqi { get; set; } + + public string temperature { get; set; } + public string status { get; set; } + } + +} diff --git a/Container/Win/BrandProg.xaml b/Container/Win/BrandProg.xaml new file mode 100644 index 0000000..e5d105f --- /dev/null +++ b/Container/Win/BrandProg.xaml @@ -0,0 +1,14 @@ + + + + + + diff --git a/Container/Win/BrandProg.xaml.cs b/Container/Win/BrandProg.xaml.cs new file mode 100644 index 0000000..3ddf2e1 --- /dev/null +++ b/Container/Win/BrandProg.xaml.cs @@ -0,0 +1,389 @@ +using Container.Common; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Net; +using System.Net.Sockets; +using System.Runtime.InteropServices; +using System.Runtime.Serialization; +using System.Runtime.Serialization.Formatters.Binary; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Data; +using System.Windows.Documents; +using System.Windows.Input; +using System.Windows.Media; +using System.Windows.Media.Imaging; +using System.Windows.Shapes; +using Transitionals; + +namespace Container.Win +{ + /// + /// BrandProg.xaml 的交互逻辑 + /// + public partial class BrandProg : Window + { + App app = ((App)Application.Current); + Class_Log log = new Class_Log(); + UserControl MyUc = new UserControl(); + private Thread th1;//播放屏保的线程 + private bool isStop = false;//是否关闭线程 + int ImageShowTime = 0; + private Socket _socket; + private string CurCode = string.Empty; + //MouseHook mh = new MouseHook(); + private List> ucList = new List>(); //记录插播列表 + public BrandProg() + { + InitializeComponent(); + this.Width = app.ScreenWidth; + this.Height = app.ScreenHeight; + } + + + private void LoadScoket() + { + //1、创建Socket对象 + Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); + _socket = socket; + //2、连接服务器,绑定IP 与 端口 + IPEndPoint iPEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8000); + try + { + socket.Connect(iPEndPoint); + } + catch (Exception) + { + //MessageBox.Show("连接失败,请重新连接!", "提示"); + //return; + } + //3、接收消息 + ThreadPool.QueueUserWorkItem(new WaitCallback(ReceiveServerMsg), socket); + } + + /// + /// 不断接收客户端信息子线程方法 + /// + /// 参数Socke对象 + private void ReceiveServerMsg(object obj) + { + var proxSocket = obj as Socket; + //创建缓存内存,存储接收的信息 ,不能放到while中,这块内存可以循环利用 + byte[] data = new byte[1020 * 1024]; + while (true) + { + int len; + try + { + //接收消息,返回字节长度 + len = proxSocket.Receive(data, 0, data.Length, SocketFlags.None); + } + catch (Exception ex) + { + return;//让方法结束,终结当前客户端数据的异步线程,方法退出,即线程结束 + } + + if (len > 0)//判断接收的字节数 + { + ////将消息显示到TxtLog + string msgStr = Encoding.Default.GetString(data, 0, len); + Dictionary Commands = JsonConvert.DeserializeObject>(msgStr); + var type = Commands["Type"].ToString(); + if (type == "playprog") + { + //isStartRunProg = true; + //if (app.isProgramServer) + //{ + // app.websocketForProgramServer.CloasSocket(); + // app.isProgramServer = false; + //} + //if (app.isProgramSync) + //{ + // app.webSocketForProgram.CloseWebSocket(); + // app.isProgramSync = false; + //} + //this.ProgramSyncTimer.Stop(); + //if (isplay) + //{ + // isplay = false; + // vlc_player_.Stop(); + // VCDTimer.Stop(); + //} + } + else if (type == "shutdownprog") + { + var curIndex = app.currentIndex > 0 ? app.currentIndex - 1 : 0; + bool flag = false; + List> deepCopyList = Clone>(ucList); + deepCopyList.GetRange(curIndex, deepCopyList.Count - curIndex -1); + foreach (var item in deepCopyList) + { + if (app.shutDownProgList.FindAll(i => i.Code == item.Item3).Count > 0) { + ucList.Remove(item); + } + } + if (app.shutDownProgList.FindAll(i => i.Code == CurCode).Count > 0) + { + ImageShowTime = 0; + } + //this.ProgramSyncTimer.Start(); + } + } + } + } + + /// + /// Clones the specified list. + /// + /// + /// The list. + /// List{``0}. + public List Clone(object List) + { + using (Stream objectStream = new MemoryStream()) + { + IFormatter formatter = new BinaryFormatter(); + formatter.Serialize(objectStream, List); + objectStream.Seek(0, SeekOrigin.Begin); + return formatter.Deserialize(objectStream) as List; + } + } + + + /// + /// 根据获取到的信息生成UseControl + /// + private void GetUControl() + { + try + { + ucList.Clear(); + this.mainp.Dispatcher.Invoke(new Action(delegate + { + mainp.Visibility = Visibility.Visible; + })); + + //生成useControl,并记录相对应的效果 + foreach (var item in app.playProgList) + { + if (app.shutDownProgList.FindAll(i => i.Code == item.Code).Count > 0) { + continue; + } + try + { + if (File.Exists(item.FilePath)) + { + this.Dispatcher.Invoke(new Action(delegate + { + UCImageText ucimg = new UCImageText(item.FilePath); + ucimg.Width = mainp.Width; + ucimg.Height = mainp.Height; + Color colorimg = (Color)ColorConverter.ConvertFromString("Black"); + ucimg.Background = new SolidColorBrush(colorimg); + Transition t = CommonMethod.GetTransition("渐入"); + ucList.Add(new Tuple(ucimg, t, item.Code)); + })); + } + } + catch (Exception ex) { log.WriteLogFile(ex.ToString(), "AddimgError"); } + + } + } + catch (Exception ex) + { + log.WriteLogFile(ex.ToString(), "WindowViewErrorlog"); + } + } + + [DllImport("user32.dll", EntryPoint = "ShowCursor", CharSet = CharSet.Auto)] + public static extern void ShowCursor(int status); + + private void BrandProg_Load(object sender, RoutedEventArgs e) + { + + try + { + //LoadScoket(); + this.Width =app.ScreenWidth; + this.Height = app.ScreenHeight; + ShowCursor(0); + MyUc.Width = mainp.Width; + MyUc.Height = mainp.Height; + Color color = (Color)ColorConverter.ConvertFromString("Black"); + MyUc.Background = new SolidColorBrush(color); + app.currentIndex = 0; + GetUControl(); + StartPlay(); + + } + catch (Exception ex) + { + log.WriteLogFile(ex.ToString(), "WindowViewErrorlog"); + } + + } + + /// + /// 开始播放 + /// + private void StartPlay() + { + MyUc.Width = mainp.Width; + MyUc.Height = mainp.Height; + Color color = (Color)ColorConverter.ConvertFromString("Black"); + MyUc.Background = new SolidColorBrush(color); + this.Background = new SolidColorBrush(color); + this.main.Background = new SolidColorBrush(color); + try + { + if (th1 == null) + { + th1 = new Thread(new ThreadStart(() => + { + + while (!isStop)//停止播放 + { + try + { + if (app.CloseServerTime.HasValue && app.CloseServerTime.Value.ToString("yyyy-MM-dd HH:mm:ss") == DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")) + { + CloseWindows(); + } + if (ImageShowTime > 1) + { + ImageShowTime--; + Thread.Sleep(1000); + continue; + } + + //播放完后重新获取最新屏保 + if (app.currentIndex >= ucList.Count || app.currentIndex < 0) + { + GetUControl(); + app.currentIndex = 0; + } + if (ucList.Count > 0) + { + this.Dispatcher.Invoke(new Action(() => + { + try + { + mainp.Transition = ucList[app.currentIndex].Item2; + mainp.Content = ucList[app.currentIndex].Item1; + CurCode = ucList[app.currentIndex].Item3; + ImageShowTime = 30; + app.currentIndex++; + + } + catch { } + })); + + } + else + { + + CloseWindows(); + + } + } + catch (Exception ex) + { + log.WriteLogFile(ex.ToString(), "WindowViewErrorlog"); + } + } + + + })); + } + th1.IsBackground = true; + th1.Start(); + } + catch (Exception ex) + { + + log.WriteLogFile(ex.ToString(), "WindowViewErrorlog"); + } + } + + private void CloseWindows() { + app.CloseServerTime = null; + IntPtr windowWin = FindWindow(null, "WindowViewNew"); //置顶窗体 + if ((windowWin == null || windowWin == IntPtr.Zero)) + { + Action UploadApp = new Action(() => + { + App.Current.Dispatcher.Invoke((Action)(() => + { + try + { + WindowViewNew windowView = new WindowViewNew(0); + windowView.Show(); + } + catch (Exception ex) + { + log.WriteLogFile(ex.ToString(), "errorrrr"); + } + })); + }); + UploadApp.BeginInvoke(null, null); + } + this.Dispatcher.Invoke((Action)(() => + { + this.Close(); + })); + + } + + const int WM_CLOSE = 0x0010;//关闭窗体 + + [DllImport("user32.dll", SetLastError = true)] + static extern IntPtr FindWindow(string IpClassName, string IpWindowName); + + [DllImport("User32.dll", EntryPoint = "SendMessage")] + public static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam); + + + private void BrandProg_Closing(object sender, System.ComponentModel.CancelEventArgs e) + { + + try + { + app.CloseServerTime = null; + isStop = true; + //if (th1 != null) + // th1.Abort(); + + //mh.UnHook(); + //webForFace.CloseWebSocket(); + } + catch (Exception ex) + { + log.WriteLogFile("--------" + ex.ToString(), "WindowViewErrorlog"); + } + //try + //{ + + // log.WriteLogFile("程序关闭 isclose" + isclose.ToString() + " Mainclose" + Mainclose.ToString(), "WindowViewErrorlog"); + // //if (!isclose && !Mainclose) + // //{ + // // Process[] process = Process.GetProcesses(); + // // foreach (Process prc in process) + // // { + // // if (prc.ProcessName.Equals(System.Diagnostics.Process.GetCurrentProcess().ProcessName)) + // // prc.Kill(); + // // } + // //} + //} + //catch (Exception ex) + //{ + // log.WriteLogFile(ex.ToString(), "WindowViewErrorlog"); + //} + } + } +} diff --git a/Container/Win/ClockControl.xaml b/Container/Win/ClockControl.xaml new file mode 100644 index 0000000..737a5fc --- /dev/null +++ b/Container/Win/ClockControl.xaml @@ -0,0 +1,99 @@ + + + + + + + + + + + + + + + + + + + + + diff --git a/Container/Win/ClockControl.xaml.cs b/Container/Win/ClockControl.xaml.cs new file mode 100644 index 0000000..1980f6a --- /dev/null +++ b/Container/Win/ClockControl.xaml.cs @@ -0,0 +1,365 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Data; +using System.Windows.Documents; +using System.Windows.Input; +using System.Windows.Media; +using System.Windows.Media.Imaging; +using System.Windows.Navigation; +using System.Windows.Shapes; +using System.Windows.Threading; + +namespace Container.Win +{ + /// + /// ClockControl.xaml 的交互逻辑 + /// + public partial class ClockControl : UserControl + { + bool isStop = false; + Thread thImage; + Task task; + CancellationTokenSource source1 = new CancellationTokenSource(); + string[] weekdays = { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" }; + public ClockControl() + { + InitializeComponent(); + } + public void BindClock(int type,int width,int height,string backgroundColor,string fontColor) { + TextBlock textTime = new TextBlock(); + TextBlock textWeek = new TextBlock(); + TextBlock textDate = new TextBlock(); + this.Width = width; + this.Height = height; + gridMain.Width = width; + gridMain.Height = Height; + BrushConverter converter = new BrushConverter(); + if (!string.IsNullOrEmpty(backgroundColor)) + { + Brush newFill = (Brush)converter.ConvertFromString(backgroundColor); + gridMain.Background = newFill; + } + if (!string.IsNullOrEmpty(fontColor)) + { + Brush newFill = (Brush)converter.ConvertFromString(fontColor); + textTime.Foreground = newFill; + textWeek.Foreground = newFill; + textDate.Foreground = newFill; + } + if (type == 4) { + Viewbox viewbox = new Viewbox(); + viewbox.Width = width; + viewbox.Height = height; + gridMain.Children.Add(viewbox); + Grid grid = new Grid(); + grid.Width = 320; + grid.Height = 80; + ColumnDefinition column1 = new ColumnDefinition(); + column1.Width = GridLength.Auto; + grid.ColumnDefinitions.Add(column1); + grid.ColumnDefinitions.Add(new ColumnDefinition()); + grid.RowDefinitions.Add(new RowDefinition()); + grid.RowDefinitions.Add(new RowDefinition()); + grid.Children.Add(textTime); + textTime.SetValue(Grid.ColumnProperty,0); + textTime.SetValue(Grid.RowSpanProperty, 2); + textTime.VerticalAlignment = VerticalAlignment.Center; + textTime.HorizontalAlignment = HorizontalAlignment.Left; + textTime.FontSize = 36; + textTime.FontWeight = FontWeights.Bold; + textTime.Margin = new Thickness(18, 0, 8, -10); + textTime.FontFamily= new FontFamily(Application.Current.Resources["BrownStd"].ToString()); + + grid.Children.Add(textDate); + textDate.SetValue(Grid.ColumnProperty, 1); + textDate.SetValue(Grid.RowProperty, 0); + textDate.VerticalAlignment = VerticalAlignment.Bottom; + textDate.HorizontalAlignment = HorizontalAlignment.Left; + textDate.FontSize = 14; + textDate.FontWeight = FontWeights.Light; + textDate.FontFamily = new FontFamily(Application.Current.Resources["BrownStd"].ToString()); + + grid.Children.Add(textWeek); + textWeek.SetValue(Grid.ColumnProperty, 1); + textWeek.SetValue(Grid.RowProperty, 1); + textWeek.VerticalAlignment = VerticalAlignment.Top; + textWeek.HorizontalAlignment = HorizontalAlignment.Left; + textWeek.FontSize = 14; + textWeek.FontFamily = new FontFamily(Application.Current.Resources["CNRegular"].ToString()); + viewbox.Stretch = Stretch.Uniform; + viewbox.StretchDirection = StretchDirection.Both; + viewbox.Child = grid; + } + else if (type == 0) + { + Viewbox viewbox = new Viewbox(); + viewbox.Width = width; + viewbox.Height = height; + gridMain.Children.Add(viewbox); + Grid grid = new Grid(); + grid.Width = 320; + grid.Height = 80; + ColumnDefinition column1 = new ColumnDefinition(); + column1.Width = GridLength.Auto; + ColumnDefinition column2 = new ColumnDefinition(); + ColumnDefinition column3 = new ColumnDefinition(); + column3.Width = GridLength.Auto; + grid.ColumnDefinitions.Add(column1); + grid.ColumnDefinitions.Add(column2); + grid.ColumnDefinitions.Add(column3); + grid.Children.Add(textTime); + textTime.SetValue(Grid.ColumnProperty, 0); + textTime.VerticalAlignment = VerticalAlignment.Center; + textTime.HorizontalAlignment = HorizontalAlignment.Left; + textTime.FontSize = 24; + textTime.FontWeight = FontWeights.Bold; + textTime.Margin = new Thickness(18, 0, 0, 0); + textTime.FontFamily = new FontFamily(Application.Current.Resources["BrownStd"].ToString()); + + grid.Children.Add(textWeek); + textWeek.SetValue(Grid.ColumnProperty, 1); + textWeek.VerticalAlignment = VerticalAlignment.Center; + textWeek.HorizontalAlignment = HorizontalAlignment.Center; + textWeek.FontSize = 20; + textWeek.Margin = new Thickness(0, 0, 0, 4); + textWeek.FontFamily = new FontFamily(Application.Current.Resources["CNRegular"].ToString()); + + grid.Children.Add(textDate); + textDate.SetValue(Grid.ColumnProperty, 2); + textDate.VerticalAlignment = VerticalAlignment.Center; + textDate.HorizontalAlignment = HorizontalAlignment.Left; + textDate.FontSize = 24; + textDate.FontWeight = FontWeights.Light; + textDate.Margin = new Thickness(0, 0, 25, 0); + textDate.FontFamily = new FontFamily(Application.Current.Resources["BrownStd"].ToString()); + viewbox.Stretch = Stretch.Uniform; + viewbox.StretchDirection = StretchDirection.Both; + viewbox.Child = grid; + } + else if (type == 1) + { + Viewbox viewbox = new Viewbox(); + viewbox.Width = width; + viewbox.Height = height; + gridMain.Children.Add(viewbox); + Grid grid = new Grid(); + grid.Width = 320; + grid.Height = 80; + ColumnDefinition column1= new ColumnDefinition(); + column1.Width = GridLength.Auto; + ColumnDefinition column2 = new ColumnDefinition(); + ColumnDefinition column3 = new ColumnDefinition(); + column3.Width = GridLength.Auto; + grid.ColumnDefinitions.Add(column1); + grid.ColumnDefinitions.Add(column2); + grid.ColumnDefinitions.Add(column3); + + + grid.Children.Add(textDate); + textDate.SetValue(Grid.ColumnProperty, 0); + textDate.VerticalAlignment = VerticalAlignment.Center; + textDate.HorizontalAlignment = HorizontalAlignment.Left; + textDate.FontSize = 24; + textDate.FontWeight = FontWeights.Light; + textDate.Margin = new Thickness(18,0,0,0); + textDate.FontFamily = new FontFamily(Application.Current.Resources["BrownStd"].ToString()); + + grid.Children.Add(textTime); + textTime.SetValue(Grid.ColumnProperty, 1); + textTime.VerticalAlignment = VerticalAlignment.Center; + textTime.HorizontalAlignment = HorizontalAlignment.Center; + textTime.FontSize = 24; + textTime.FontWeight = FontWeights.Bold; + textTime.FontFamily = new FontFamily(Application.Current.Resources["BrownStd"].ToString()); + + grid.Children.Add(textWeek); + textWeek.SetValue(Grid.ColumnProperty, 2); + textWeek.VerticalAlignment = VerticalAlignment.Center; + textWeek.HorizontalAlignment = HorizontalAlignment.Left; + textWeek.FontSize = 20; + textWeek.Margin = new Thickness(0, 0, 25, 4); + textWeek.FontFamily = new FontFamily(Application.Current.Resources["CNRegular"].ToString()); + viewbox.Stretch = Stretch.Uniform; + viewbox.StretchDirection = StretchDirection.Both; + viewbox.Child = grid; + } + else if (type == 2) + { + Viewbox viewbox = new Viewbox(); + viewbox.Width = width; + viewbox.Height = height; + gridMain.Children.Add(viewbox); + Grid grid = new Grid(); + grid.Width = 320; + grid.Height = 80; + ColumnDefinition column = new ColumnDefinition(); + column.Width = GridLength.Auto; + grid.ColumnDefinitions.Add(column); + grid.ColumnDefinitions.Add(new ColumnDefinition()); + grid.RowDefinitions.Add(new RowDefinition()); + grid.RowDefinitions.Add(new RowDefinition()); + + + grid.Children.Add(textTime); + textTime.SetValue(Grid.ColumnProperty, 0); + textTime.SetValue(Grid.RowProperty, 0); + textTime.VerticalAlignment = VerticalAlignment.Bottom; + textTime.HorizontalAlignment = HorizontalAlignment.Left; + textTime.FontSize = 24; + textTime.FontWeight = FontWeights.Bold; + textTime.Margin = new Thickness(18,0,0,0); + textTime.FontFamily = new FontFamily(Application.Current.Resources["BrownStd"].ToString()); + + grid.Children.Add(textDate); + textDate.SetValue(Grid.ColumnProperty, 0); + textDate.SetValue(Grid.RowProperty, 1); + textDate.VerticalAlignment = VerticalAlignment.Top; + textDate.HorizontalAlignment = HorizontalAlignment.Left; + textDate.FontSize = 18; + textDate.FontWeight = FontWeights.Light; + textDate.Margin = new Thickness(18,0,0,0); + textDate.FontFamily = new FontFamily(Application.Current.Resources["BrownStd"].ToString()); + + grid.Children.Add(textWeek); + textWeek.SetValue(Grid.ColumnProperty, 1); + textWeek.SetValue(Grid.RowProperty, 1); + textWeek.VerticalAlignment = VerticalAlignment.Top; + textWeek.HorizontalAlignment = HorizontalAlignment.Left; + textWeek.FontSize = 14; + textWeek.Margin = new Thickness(12, -1, 0, 0); + textWeek.FontFamily = new FontFamily(Application.Current.Resources["CNRegular"].ToString()); + viewbox.Stretch = Stretch.Uniform; + viewbox.StretchDirection = StretchDirection.Both; + viewbox.Child = grid; + } + else + { + Viewbox viewbox = new Viewbox(); + viewbox.Width = width; + viewbox.Height = height; + gridMain.Children.Add(viewbox); + Grid grid = new Grid(); + grid.Width = 320; + grid.Height = 80; + ColumnDefinition column1 = new ColumnDefinition(); + column1.Width = GridLength.Auto; + ColumnDefinition column2 = new ColumnDefinition(); + ColumnDefinition column3 = new ColumnDefinition(); + column3.Width = GridLength.Auto; + grid.ColumnDefinitions.Add(column1); + grid.ColumnDefinitions.Add(column2); + grid.ColumnDefinitions.Add(column3); + + grid.Children.Add(textTime); + + textTime.SetValue(Grid.ColumnProperty, 0); + textTime.VerticalAlignment = VerticalAlignment.Center; + textTime.HorizontalAlignment = HorizontalAlignment.Left; + textTime.FontSize = 24; + textTime.FontWeight = FontWeights.Bold; + textTime.Margin = new Thickness(18,0,0,0); + textTime.FontFamily = new FontFamily(Application.Current.Resources["BrownStd"].ToString()); + + grid.Children.Add(textDate); + textDate.SetValue(Grid.ColumnProperty, 1); + textDate.VerticalAlignment = VerticalAlignment.Center; + textDate.HorizontalAlignment = HorizontalAlignment.Center; + textDate.FontSize = 14; + textDate.FontWeight = FontWeights.Light; + textDate.Margin = new Thickness(0, 0, 0, -6.5); + textDate.FontFamily = new FontFamily(Application.Current.Resources["BrownStd"].ToString()); + + grid.Children.Add(textWeek); + textWeek.SetValue(Grid.ColumnProperty, 2); + textWeek.VerticalAlignment = VerticalAlignment.Center; + textWeek.HorizontalAlignment = HorizontalAlignment.Left; + textWeek.FontSize = 11; + textWeek.Margin = new Thickness(0,0,110,-5); + textWeek.FontFamily = new FontFamily(Application.Current.Resources["CNRegular"].ToString()); + viewbox.Stretch = Stretch.Uniform; + viewbox.StretchDirection = StretchDirection.Both; + viewbox.Child = grid; + } + + + gridMain.Dispatcher.Invoke(new Action(() => + { + DateTime dtNow = DateTime.Now; + textDate.Text = dtNow.ToString("yyyy-MM-dd"); + textWeek.Text = weekdays[Convert.ToInt32(DateTime.Now.DayOfWeek)]; + textTime.Text = dtNow.ToShortTimeString().ToString(); + + })); + CancellationToken token = source1.Token; + TaskFactory factory = new TaskFactory(token); + task = factory.StartNew(() => + { + var curDate = DateTime.Now; + while (!isStop) + { + if (token.IsCancellationRequested) + { + // 释放资源操作等等... + break; + } + if (curDate.AddMilliseconds(2000) <= DateTime.Now) + { + gridMain.Dispatcher.Invoke(new Action(() => + { + DateTime dtNow = DateTime.Now; + textDate.Text = dtNow.ToString("yyyy-MM-dd"); + textWeek.Text = weekdays[Convert.ToInt32(DateTime.Now.DayOfWeek)]; + textTime.Text = dtNow.ToShortTimeString().ToString(); + + })); + curDate = DateTime.Now; + } + else + { + Thread.Sleep(100); + } + + //Thread.Sleep(duration); + } + }); + + + //if (thImage == null) { + // thImage = new Thread(new ThreadStart(async () => + // { + // while (!isStop) + // { + // gridMain.Dispatcher.Invoke(new Action(() => + // { + // DateTime dtNow = DateTime.Now; + // textDate.Text = dtNow.ToString("yyyy-MM-dd"); + // textWeek.Text = dtNow.DayOfWeek.ToString(); + // textTime.Text = dtNow.ToShortTimeString().ToString(); + + // })); + // task = Task.Delay(2000); + // await task; + // } + // })); + // thImage.IsBackground = true; + // thImage.Start(); + //} + + } + + public void Dispose() { + isStop = true; + if (task != null && (task.IsCanceled || task.IsCompleted || task.IsFaulted)) + { + task.Dispose(); + } + source1.Cancel(); + } + } +} diff --git a/Container/Win/CountDown.xaml b/Container/Win/CountDown.xaml new file mode 100644 index 0000000..926c9ee --- /dev/null +++ b/Container/Win/CountDown.xaml @@ -0,0 +1,17 @@ + + + + + + + + + + diff --git a/Container/Win/CountDown.xaml.cs b/Container/Win/CountDown.xaml.cs new file mode 100644 index 0000000..7f6469a --- /dev/null +++ b/Container/Win/CountDown.xaml.cs @@ -0,0 +1,86 @@ +using Container.Common; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Data; +using System.Windows.Documents; +using System.Windows.Input; +using System.Windows.Media; +using System.Windows.Media.Animation; +using System.Windows.Media.Imaging; +using System.Windows.Shapes; + +namespace Container.Win +{ + /// + /// CountDown.xaml 的交互逻辑 + /// + public partial class CountDown : Window + { + public CountDown() + { + InitializeComponent(); + } + Class_Log log = new Class_Log(); + private void Window_Loaded(object sender, RoutedEventArgs e) + { + LoadPics(); + } + + private void LoadPics() + { + try + { + Storyboard _storyboard = new Storyboard(); + + for (int i = 0; i < 220; i++) + { + ObjectAnimationUsingKeyFrames oauf = new ObjectAnimationUsingKeyFrames(); + //ObjectAnimationUsingKeyFrames 可以对指定 Duration 内的一组 KeyFrames 中的 Object 属性值进行动画处理 + BitmapImage bitmap = new BitmapImage(); + bitmap.BeginInit(); + string name = i.ToString().PadLeft(5, '0'); + bitmap.UriSource = new Uri("pack://application:,,,/Container;component/image/CountDowmImage/倒计时透明度_" + name + ".png"); + bitmap.CacheOption = BitmapCacheOption.Default; + bitmap.EndInit(); + + ImageBrush imgBrush = new ImageBrush(bitmap); + //读取图片文件 + DiscreteObjectKeyFrame dokf = new DiscreteObjectKeyFrame(); + //DiscreteObjectKeyFrame 通过使用离散内插,可以在前一个关键帧的 Object 值及其自己的 Value 之间进行动画处理。 + dokf.KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromMilliseconds(i * 30)); + //KeyTime 获取或设置应到达关键帧的目标 Value 的时间 + //这里每隔40毫秒设置一张图片,也就是每秒1000/40=25帧 + dokf.Value = imgBrush; + oauf.KeyFrames.Add(dokf); + Storyboard.SetTargetProperty(oauf, new PropertyPath("(Rectangle.Fill)")); + //把动画应用到窗体的Rectangle中 + Storyboard.SetTarget(oauf, RectDisImage); + //RectDis是Rectangle的名称 + _storyboard.Children.Add(oauf); + //把ObjectAnimationUsingKeyFrames动画添加到Storyboard中 + } + _storyboard.Completed += new EventHandler(time_Completed); + //_storyboard.RepeatBehavior = RepeatBehavior.Forever; + _storyboard.Begin(); + + } + catch (Exception ex) + { + + log.WriteLogFile(ex.Message, "error"); + } + } + + void time_Completed(object sender, EventArgs e) + { + WindowViewNew window = new WindowViewNew(); + window.Show(); + this.Close(); + } + } +} diff --git a/Container/Win/LiveShow.xaml b/Container/Win/LiveShow.xaml new file mode 100644 index 0000000..4c0c026 --- /dev/null +++ b/Container/Win/LiveShow.xaml @@ -0,0 +1,254 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Container/Win/LiveShow.xaml.cs b/Container/Win/LiveShow.xaml.cs new file mode 100644 index 0000000..3720cdb --- /dev/null +++ b/Container/Win/LiveShow.xaml.cs @@ -0,0 +1,1218 @@ +using Container.Common; +using Container.Services; +using Newtonsoft.Json; +using QRCoder; +using System; +using System.Collections; +using System.Collections.Generic; +using System.Drawing; +using System.Drawing.Imaging; +using System.IO; +using System.Linq; +using System.Net; +using System.Net.Sockets; +using System.Reflection; +using System.Runtime.InteropServices; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Data; +using System.Windows.Documents; +using System.Windows.Input; +using System.Windows.Media; +using System.Windows.Media.Animation; +using System.Windows.Media.Imaging; +using System.Windows.Shapes; +using System.Windows.Threading; +using Vlc.DotNet.Wpf; +using Image = System.Windows.Controls.Image; + +namespace Container.Win +{ + /// + /// LiveShow.xaml 的交互逻辑 + /// + public partial class LiveShow : Window + { + App app = ((App)System.Windows.Application.Current); + private readonly DirectoryInfo vlcLibDirectory; + DispatcherTimer LiveTimer = new DispatcherTimer();//定时获取是否有直播的线程 + Class_Log log = new Class_Log(); + //private VlcControl control; + long playTime = 0; + DateTime curDate = DateTime.Now; + DateTime bengindTime = DateTime.Now; + bool isLoad = false; + bool falg = false; + DateTime? dtLiveStop = null; + Dictionary livsStopList = new Dictionary(); + List stopList = new List(); + private Socket _socket; + int agreeBeginTop = 730; + int agreeBeginMaxWidth = 700; + int agreeBeginLeft = 625; + + /// + /// 创建双精度动画对象 + /// + DoubleAnimation doubleAnimation = new DoubleAnimation(); + /// + /// 创建双精度动画对象 + /// + DoubleAnimation doubleAnimationEnd = new DoubleAnimation(); + + /// + /// 创建双精度动画对象 + /// + DoubleAnimation doubleAnimationImage = new DoubleAnimation(); + /// + /// 创建双精度动画对象 + /// + DoubleAnimation doubleAnimationImageEnd = new DoubleAnimation(); + List liveImageList = new List(); + //需要移除的图片列表 + List ElementList = new List(); + int curImageCount = 0; + DispatcherTimer timer = new DispatcherTimer(); + public LiveShow() + { + InitializeComponent(); + try + { + + this.Width = app.ScreenWidth; + this.Height =app.ScreenHeight; + this.gradLive.Width= app.ScreenWidth; + this.gradLive.Height = app.ScreenHeight; + gLoading.SetValue(Canvas.TopProperty, (this.Height - 200) / 2); + gLoading.SetValue(Canvas.LeftProperty, (this.Width - 200) / 2); + //if (this.Width > this.Height) + //{ + // control.Width = 608; + // control.Height = 1080; + // control.Margin = new Thickness(640, 0, 0, 0); + // gridMsg.Width = 1920; + // gridMsg.Height = 1080; + // bgGrid.Opacity = 0; + // rightWidth.Width = new GridLength(54); + // leftWidth.Width = new GridLength(48); + // //gLoading.SetValue(Canvas.LeftProperty, 1180); + + // cvsAgreeGround.Width = 700; + // cvsAgreeGround.Margin = new Thickness(1050, 0, 0, 250); + // //agreeGrid.SetValue(Canvas.LeftProperty, (object)600); + // Canvas.SetLeft(agreeGrid, 600); + // agreeBeginTop = 710; + // agreeBeginMaxWidth = 700; + // agreeBeginLeft = 600; + + //} + //else + //{ + // control.Width = 1080; + // control.Height = 1920; + // control.Margin = new Thickness(0, 0, 0, 0); + // gridMsg.Width = 1080; + // gridMsg.Height = 1920; + // bgGrid.Opacity = 0.5; + // rightWidth.Width = new GridLength(30); + // leftWidth.Width = new GridLength(36); + // gLoading.SetValue(Canvas.LeftProperty, (this.Width - 200) / 2); + + // cvsAgreeGround.Width = 280; + // cvsAgreeGround.Margin = new Thickness(800, 0, 0, 550); + // //agreeGrid.SetValue(Canvas.LeftProperty, (object)120); + // Canvas.SetLeft(agreeGrid, 120); + + // agreeBeginTop = 1250; + // agreeBeginMaxWidth = 280; + // agreeBeginLeft = 120; + //} + var currentAssembly = Assembly.GetEntryAssembly(); + var currentDirectory = new FileInfo(currentAssembly.Location).DirectoryName; + // Default installation path of VideoLAN.LibVLC.Windows + vlcLibDirectory = new DirectoryInfo(currentDirectory); + } + catch (Exception e) + { + + log.WriteLogFile(e.ToString(), "liveshowerror"); + } + } + const int WM_CLOSE = 0x0010;//关闭窗体 + [DllImport("user32.dll", SetLastError = true)] + static extern IntPtr FindWindow(string IpClassName, string IpWindowName); + + [DllImport("User32.dll", EntryPoint = "SendMessage")] + public static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam); + + private void Window_Loaded(object sender, RoutedEventArgs e) + { + try + { + //HttpMessage httpmessage = new HttpMessage(); + + LiveTimer.Tick += new EventHandler(LiveTimer_Tick); + LiveTimer.Interval = TimeSpan.FromSeconds(1); + + timer.Interval = TimeSpan.FromMilliseconds(2000); + timer.Tick += new EventHandler(timer_Tick); + + AniamtionLoad(); + LoadScoket(); + + //httpmessage.LoadCurrentLive(); + + Action ac = new Action(()=> { + ConvertLive(); + LoadData(); + //app.curLive.hFilePath = app.live.HFilePath; + StartVideo(app.curLive.liveurl); + LiveTimer.Start(); + }); + ac.BeginInvoke(null,null); + } + catch (Exception ex) + { + + log.WriteLogFile(ex.ToString(), "liveshowerror"); + } + } + + private void ConvertLive() { + var live = app.live; + app.curLive.CouponInfo = live.CouponInfo; + app.curLive.floorName = live.FloorName; + app.curLive.hFilePath = live.HFilePath; + app.curLive.houseNum = live.HouseNum; + app.curLive.likes = live.Likes; + app.curLive.liveurl = live.LiveUrl; + app.curLive.logoPath = live.LogoPath; + app.curLive.mallName = live.MallName; + app.curLive.qrCode = live.QRCode; + app.curLive.shopName = live.ShopName; + app.curLive.vFilePath = live.VFilePath; + app.curLive.watchNum = live.WatchNum; + } + + private void LoadScoket() + { + //1、创建Socket对象 + Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); + _socket = socket; + //2、连接服务器,绑定IP 与 端口 + IPEndPoint iPEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8000); + try + { + socket.Connect(iPEndPoint); + } + catch (Exception) + { + //MessageBox.Show("连接失败,请重新连接!", "提示"); + //return; + } + //3、接收消息 + ThreadPool.QueueUserWorkItem(new WaitCallback(ReceiveServerMsg), socket); + } + + /// + /// 不断接收客户端信息子线程方法 + /// + /// 参数Socke对象 + private void ReceiveServerMsg(object obj) + { + var proxSocket = obj as Socket; + //创建缓存内存,存储接收的信息 ,不能放到while中,这块内存可以循环利用 + byte[] data = new byte[1020 * 1024]; + while (true) + { + int len; + try + { + //接收消息,返回字节长度 + len = proxSocket.Receive(data, 0, data.Length, SocketFlags.None); + } + catch (Exception ex) + { + return;//让方法结束,终结当前客户端数据的异步线程,方法退出,即线程结束 + } + + if (len > 0)//判断接收的字节数 + { + ////将消息显示到TxtLog + string msgStr = Encoding.Default.GetString(data, 0, len); + Dictionary Commands = JsonConvert.DeserializeObject>(msgStr); + var type = Commands["Type"].ToString(); + if (type == "like") + { + Dictionary Parameter = JsonConvert.DeserializeObject>(Commands["Parameter"].ToString()); + Random rd = new Random(); + ControlsLoadAgree(rd.Next(2, 6)); + } + else if (type == "watchnum") + { + Dictionary Parameter = JsonConvert.DeserializeObject>(Commands["Parameter"].ToString()); + this.TxtDistance.Dispatcher.Invoke(new Action(delegate + { + if (string.IsNullOrEmpty(app.curLive.floorName)) + { + this.TxtDistance.Text = "扫码人数 " + Parameter["watchNum"].ToString(); + } + else + { + this.TxtDistance.Text = "扫码人数 " + Parameter["watchNum"].ToString() + " | " + app.curLive.floorName; + } + + })); + } + else if (type == "livecoupon") + { + + this.gridCoupon.Dispatcher.Invoke(new Action(delegate + { + this.gridCoupon.Visibility = Visibility.Visible; + if (!string.IsNullOrEmpty(app.curLive.CouponInfo.Title)) + { + this.couponName.Text = app.curLive.CouponInfo.Title; + } + else + { + //this.TxtDistance.Text = "扫码人数 " + app.curLive.watchNum + " | " + app.curLive.floorName; + this.couponName.Text = ""; + } + + if (!string.IsNullOrEmpty(app.curLive.CouponInfo.Intro)) + { + this.couponIntro.Text = app.curLive.CouponInfo.Intro; + } + else + { + //this.TxtDistance.Text = "扫码人数 " + app.curLive.watchNum + " | " + app.curLive.floorName; + this.couponIntro.Text = ""; + } + + this.couponNum.Text = app.curLive.CouponInfo.Received + "/" + app.curLive.CouponInfo.TotalNum; + + })); + CreateQR(app.curLive.CouponInfo.QrCode); + + } + else if (type == "getcoupon") { + this.gridCoupon.Dispatcher.Invoke(new Action(delegate + { + this.couponNum.Text = app.curLive.CouponInfo.Received + "/" + app.curLive.CouponInfo.TotalNum; + })); + } + else if (type == "shutdowncoupon") + { + this.gridCoupon.Dispatcher.Invoke(new Action(delegate + { + this.gridCoupon.Visibility = Visibility.Hidden; + })); + } + else if (type == "ADImage") + { + //this.cvsAD.Dispatcher.Invoke(new Action(delegate + //{ + // try + // { + // string filefolder = AppDomain.CurrentDomain.BaseDirectory + "/liveadfile"; + // try + // { + // if (!Directory.Exists(filefolder)) + // { + // DirectoryInfo directoryInfo = new DirectoryInfo(filefolder); + // directoryInfo.Create(); + // } + // } + // catch (Exception ex) + // { + // log.WriteLogFile(ex.ToString()); + + // } + // HttpClient httpClient = new HttpClient(); + // string fileName = ""; + // if (httpClient.DownLoadImage(app.curLive.hFilePath, "liveadfile", ref fileName)) + // { + // Image simpleImage = new Image(); + // simpleImage.Width = 800; + // simpleImage.Height = 250; + // simpleImage.Stretch = Stretch.Fill; + // //simpleImage.Margin = new Thickness(0, 0, 20, 0); + // Canvas.SetLeft(simpleImage, 0); + // BitmapImage bi = new BitmapImage(); + // // BitmapImage.UriSource must be in a BeginInit/EndInit block. + // bi.BeginInit(); + // bi.UriSource = new Uri(fileName, UriKind.RelativeOrAbsolute); + // bi.EndInit(); + // simpleImage.Stretch = Stretch.Fill; + // simpleImage.Source = bi; + // //cvsAD.Children.Clear(); + // //cvsAD.Children.Add(simpleImage); + // } + // else + // { + // log.WriteLogFile("直播广告图下载失败"); + // } + // } + // catch (Exception ex) + // { + // log.WriteLogFile(ex.ToString()); + + // } + //})); + } + else if (type == "Image") + { + this.cvsGround.Dispatcher.Invoke(new Action(delegate + { + try + { + List imageList = new List(); + bool isLoad = false; + foreach (var item in app.curLive.vFilePath) + { + + + string filefolder = AppDomain.CurrentDomain.BaseDirectory + "/liveImageFile"; + + try + { + if (!Directory.Exists(filefolder)) + { + DirectoryInfo directoryInfo = new DirectoryInfo(filefolder); + directoryInfo.Create(); + } + } + catch (Exception ex) + { + log.WriteLogFile(ex.ToString()); + + } + HttpClient httpClient = new HttpClient(); + string fileName = ""; + if (!httpClient.CheckImageIsExists(item, "liveImageFile", ref fileName)) + { + if (httpClient.DownLoadImage(item, "liveImageFile", ref fileName)) + imageList.Add(fileName); + else + { + log.WriteLogFile("直播广告图下载失败"); + } + isLoad = true; + } + else + { + imageList.Add(fileName); + if (JsonConvert.SerializeObject(liveImageList).Contains(fileName.Substring(fileName.LastIndexOf('/')+1))) + { + isLoad = true; + } + } + } + if (isLoad) + { + liveImageList = imageList; + cvsGround.Children.Clear(); + ControlsLoad(imageList); + if (imageList.Count > 4) + { + timer.Start(); + } + else + { + timer.Stop(); + } + curImageCount = 0; + } + } + catch (Exception ex) + { + log.WriteLogFile(ex.ToString()); + + } + })); + } + } + } + } + + + private void timer_Tick(object sender, EventArgs e) + { + //Random rd = new Random(); + //ControlsLoadAgree(rd.Next(2, 6)); + DoMove(-206); + } + + /// + /// 图片的运动方法 + /// + private void AniamtionLoad() + { + doubleAnimation.Duration = TimeSpan.FromSeconds(0.5);//设置动画时间线长度 + doubleAnimation.AccelerationRatio = 0.1;//动画加速 + doubleAnimation.DecelerationRatio = 0.5;//动画减速 + doubleAnimation.FillBehavior = FillBehavior.HoldEnd;//设置动画完成后执行的操作 + + doubleAnimationEnd.Duration = TimeSpan.FromSeconds(0.5);//设置动画时间线长度 + doubleAnimationEnd.AccelerationRatio = 0.1;//动画加速 + doubleAnimationEnd.DecelerationRatio = 0.5;//动画减速 + doubleAnimationEnd.To = -800; + + doubleAnimationImage.Duration = TimeSpan.FromSeconds(0.5);//设置动画时间线长度 + doubleAnimationImage.AccelerationRatio = 0.1;//动画加速 + doubleAnimationImage.DecelerationRatio = 0.5;//动画减速 + doubleAnimationImage.FillBehavior = FillBehavior.HoldEnd;//设置动画完成后执行的操作 + + doubleAnimationImageEnd.Duration = TimeSpan.FromSeconds(0.5);//设置动画时间线长度 + doubleAnimationImageEnd.AccelerationRatio = 0.1;//动画加速 + doubleAnimationImageEnd.DecelerationRatio = 0.5;//动画减速 + doubleAnimationImageEnd.To = -206; + } + + private async void LoadData() + { + Class_Log log = new Class_Log(); + try + { + + if (app.curLive != null) + { + if (!string.IsNullOrEmpty(app.curLive.logoPath)) + { + this.ImgLogo.Dispatcher.Invoke(new Action(delegate + { + log.WriteLogFile(app.curLive.logoPath.Replace("\\", @"/"), "22222"); + Uri uriLogo = new Uri(app.curLive.logoPath.Replace("\\",@"/"), UriKind.Absolute); + this.ImgLogo.Source = BitmapFrame.Create(uriLogo); + })); + } + else + { + this.ImgLogo.Dispatcher.Invoke(new Action(delegate + { + Uri uriLogo = new Uri(@"/image/liveicon/admin.png", UriKind.RelativeOrAbsolute); + this.ImgLogo.Source = BitmapFrame.Create(uriLogo); + })); + } + this.TxtName.Dispatcher.Invoke(new Action(delegate + { + this.TxtName.Content = string.IsNullOrEmpty(app.curLive.shopName) ? app.curLive.mallName : app.curLive.shopName; + this.TxtName.TextSource = string.IsNullOrEmpty(app.curLive.shopName) ? app.curLive.mallName : app.curLive.shopName; + })); + this.TxtDistance.Dispatcher.Invoke(new Action(delegate + { + + if (string.IsNullOrEmpty(app.curLive.floorName)) + { + this.TxtDistance.Text = ""; + } + else + { + //this.TxtDistance.Text = "扫码人数 " + app.curLive.watchNum + " | " + app.curLive.floorName; + this.TxtDistance.Text = app.curLive.floorName+" | "+app.curLive.houseNum; + } + + })); + if (app.curLive.CouponInfo != null) + { + + + this.gridCoupon.Dispatcher.Invoke(new Action(delegate + { + this.gridCoupon.Visibility = Visibility.Visible; + if (!string.IsNullOrEmpty(app.curLive.CouponInfo.Title)) + { + this.couponName.Text = app.curLive.CouponInfo.Title; + } + else + { + //this.TxtDistance.Text = "扫码人数 " + app.curLive.watchNum + " | " + app.curLive.floorName; + this.couponName.Text = ""; + } + + if (!string.IsNullOrEmpty(app.curLive.CouponInfo.Intro)) + { + this.couponIntro.Text = app.curLive.CouponInfo.Intro; + } + else + { + //this.TxtDistance.Text = "扫码人数 " + app.curLive.watchNum + " | " + app.curLive.floorName; + this.couponIntro.Text = ""; + } + + this.couponNum.Text = app.curLive.CouponInfo.Received+ "/"+app.curLive.CouponInfo.TotalNum; + + })); + CreateQR(app.curLive.CouponInfo.QrCode); + } + else { + this.gridCoupon.Dispatcher.Invoke(new Action(delegate + { + this.gridCoupon.Visibility = Visibility.Hidden; + })); + } + //this.TxtName.Text = app.curLive.shopName; + //this.TxtDistance.Text = "扫码人数 " + app.curLive.likes + " | " + app.curLive.floorName; + + //this.Dispatcher.Invoke(new Action(() => + //{ + //if (this.Width > this.Height) + //{ + + // //SFile.Visibility = Visibility.Hidden; + // LogoBG.Color = (System.Windows.Media.Color)System.Windows.Media.ColorConverter.ConvertFromString("White"); + // LogoQR.Color = (System.Windows.Media.Color)System.Windows.Media.ColorConverter.ConvertFromString("White"); + //} + //else + //{ + // LogoBG.Color = (System.Windows.Media.Color)System.Windows.Media.ColorConverter.ConvertFromString("Black"); + // LogoQR.Color = (System.Windows.Media.Color)System.Windows.Media.ColorConverter.ConvertFromString("Black"); + //} + + //this.cvsAD.Dispatcher.Invoke(new Action(delegate + //{ + // try + // { + // string filefolder = AppDomain.CurrentDomain.BaseDirectory + "/liveadfile"; + // //IntPtr Win = FindWindow(null, "ADInsert"); + // //if (Win != null) + // //{ + // // //SetWindowPos(Win, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE); + // // SendMessage(Win, WM_CLOSE, 0, 0); // 调用了 发送消息 发送关闭窗口的消息 + // //} + // try + // { + // if (!Directory.Exists(filefolder)) + // { + // DirectoryInfo directoryInfo = new DirectoryInfo(filefolder); + // directoryInfo.Create(); + // } + // } + // catch (Exception ex) + // { + // log.WriteLogFile(ex.ToString()); + + // } + // HttpClient httpClient = new HttpClient(); + // string fileName = ""; + // if (httpClient.DownLoadImage(app.curLive.hFilePath, "liveadfile", ref fileName)) + // { + // Image simpleImage = new Image(); + // simpleImage.Width = 800; + // simpleImage.Height = 250; + // simpleImage.Stretch = Stretch.Fill; + // //simpleImage.Margin = new Thickness(0, 0, 20, 0); + // Canvas.SetLeft(simpleImage, 0); + // BitmapImage bi = new BitmapImage(); + // // BitmapImage.UriSource must be in a BeginInit/EndInit block. + // bi.BeginInit(); + // bi.UriSource = new Uri(fileName, UriKind.RelativeOrAbsolute); + // bi.EndInit(); + // simpleImage.Stretch = Stretch.Fill; + // simpleImage.Source = bi; + // cvsAD.Children.Add(simpleImage); + + // //double transferLeft = Convert.ToDouble(simpleImage.GetValue(Canvas.LeftProperty)); + // //doubleAnimation.To = 0; + // //simpleImage.BeginAnimation(Canvas.LeftProperty, doubleAnimation);//设置动画应用的属性并启动动画 + + // //cvsAD.Children[0].BeginAnimation(Canvas.LeftProperty, doubleAnimationEnd);//设置动画应用的属性并启动动画 + // //doubleAnimationEnd.Completed += SbQueOnCompleted; //设置动画结束后的事件 + // } + // else + // { + // log.WriteLogFile("直播广告图下载失败"); + // } + // } + // catch (Exception ex) + // { + // log.WriteLogFile(ex.ToString()); + + // } + //})); + + this.cvsGround.Dispatcher.Invoke(new Action(delegate + { + try + { + List imageList = new List(); + foreach (var item in app.curLive.vFilePath) + { + + + string filefolder = AppDomain.CurrentDomain.BaseDirectory + "/liveImageFile"; + + try + { + if (!Directory.Exists(filefolder)) + { + DirectoryInfo directoryInfo = new DirectoryInfo(filefolder); + directoryInfo.Create(); + } + } + catch (Exception ex) + { + log.WriteLogFile(ex.ToString()); + + } + HttpClient httpClient = new HttpClient(); + string fileName = ""; + if (httpClient.DownLoadImage(item, "liveImageFile", ref fileName)) + { + + imageList.Add(fileName); + } + else + { + log.WriteLogFile("直播广告图下载失败"); + } + } + + liveImageList = imageList; + + ControlsLoad(imageList); + if (imageList.Count > 4) + { + timer.Start(); + } + else { + timer.Stop(); + } + curImageCount = 0; + + + } + catch (Exception ex) + { + log.WriteLogFile(ex.ToString()); + + } + })); + // })); + } + } + catch (Exception ex) + { + log.WriteLogFile(ex.ToString(), "LivePage"); + } + } + + /// + /// 循环产生图片 + /// + /// 产生图片的个数 + /// 产生图片的方向 + /// 产生图片的位置 + /// + private void ControlsLoadAgree(int num) + { + List tbList = new List(); + Random rd = new Random(); + for (int i = 0; i < num; i++) + { + double timeSpan = rd.Next(1, 7); + int liveImagePath = rd.Next(1, 6); + Image simpleImage = new Image(); + simpleImage.Width = 75; + simpleImage.Height = 75; + Canvas.SetRight(simpleImage, 75); + Canvas.SetBottom(simpleImage, 35); + BitmapImage bi = new BitmapImage(); + // BitmapImage.UriSource must be in a BeginInit/EndInit block. + bi.BeginInit(); + bi.UriSource = new Uri(@"/image/liveicon/" + liveImagePath + ".png", UriKind.RelativeOrAbsolute); + bi.EndInit(); + simpleImage.Stretch = Stretch.Fill; + simpleImage.Source = bi; + //cvsAgreeGround.Children.Add(simpleImage); + DoubleAnimation doubleAnimation1 = new DoubleAnimation(); + doubleAnimation1.From = agreeBeginLeft; + doubleAnimation1.To = rd.Next(0, agreeBeginMaxWidth); + DoubleAnimation doubleAnimation2 = new DoubleAnimation(); + doubleAnimation1.Duration = TimeSpan.FromSeconds(timeSpan);//设置动画时间线长度 + //doubleAnimation1.AccelerationRatio = 0;//动画加速 + //doubleAnimation1.DecelerationRatio = 0.5;//动画减速 + doubleAnimation2.Duration = TimeSpan.FromSeconds(timeSpan);//设置动画时间线长度 + //doubleAnimation2.AccelerationRatio = 0;//动画加速 + //doubleAnimation2.DecelerationRatio = 0.5;//动画减速 + simpleImage.BeginAnimation(Canvas.LeftProperty, doubleAnimation1);//设置动画应用的属性并启动动 + doubleAnimation2.From = agreeBeginTop; + doubleAnimation2.To = 0; + simpleImage.BeginAnimation(Canvas.TopProperty, doubleAnimation2);//设置动画应用的属性并启动动 + + DoubleAnimation da = new DoubleAnimation(); + da.From = 1; + da.To = 0.3; + da.Duration = TimeSpan.FromSeconds(timeSpan); + //da.Completed += (s, e) => + //{ + // cvsAgreeGround.Children.Remove(simpleImage); + //}; + simpleImage.BeginAnimation(OpacityProperty, da); + + //TextBlock textBlock = new TextBlock(); + //textBlock.Width = 75; + //textBlock.Height = 75; + //Canvas.SetRight(textBlock, 75); + //Canvas.SetBottom(textBlock, 35); + //textBlock.Text = "♥"; + //textBlock.FontSize = 60; + //textBlock.Foreground = PickRandomBrush(rd); + //cvsAgreeGround.Children.Add(textBlock); + //tbList.Add(textBlock); + //DoubleAnimation doubleAnimation1 = new DoubleAnimation(); + //doubleAnimation1.From = agreeBeginLeft; + //doubleAnimation1.To = rd.Next(0, agreeBeginMaxWidth); + //DoubleAnimation doubleAnimation2 = new DoubleAnimation(); + //doubleAnimation1.Duration = TimeSpan.FromSeconds(timeSpan);//设置动画时间线长度 + ////doubleAnimation1.AccelerationRatio = 0;//动画加速 + ////doubleAnimation1.DecelerationRatio = 0.5;//动画减速 + //doubleAnimation2.Duration = TimeSpan.FromSeconds(timeSpan);//设置动画时间线长度 + ////doubleAnimation2.AccelerationRatio = 0;//动画加速 + ////doubleAnimation2.DecelerationRatio = 0.5;//动画减速 + //textBlock.BeginAnimation(Canvas.LeftProperty, doubleAnimation1);//设置动画应用的属性并启动动 + //doubleAnimation2.From = agreeBeginTop; + //doubleAnimation2.To = 0; + //textBlock.BeginAnimation(Canvas.TopProperty, doubleAnimation2);//设置动画应用的属性并启动动 + + //DoubleAnimation da = new DoubleAnimation(); + //da.From = 1; + //da.To = 0.3; + //da.Duration = TimeSpan.FromSeconds(timeSpan); + //da.Completed += (s, e) => + //{ + // cvsAgreeGround.Children.Remove(textBlock); + //}; + //textBlock.BeginAnimation(OpacityProperty, da); + } + } + + private System.Windows.Media.Brush PickRandomBrush(Random rnd) + { + System.Windows.Media.Brush result = System.Windows.Media.Brushes.Transparent; + + Type brushesType = typeof(System.Windows.Media.Brushes); + PropertyInfo[] properties = brushesType.GetProperties(); + int random = rnd.Next(properties.Length); + result = (System.Windows.Media.Brush)properties[random].GetValue(null, null); + return result; + } + + private void SbQueOnCompleted(object sender, EventArgs eventArgs) + { + //循环删除图片 + //cvsAD.Children.RemoveAt(0); + + } + + private void SbImageQueOnCompleted(object sender, EventArgs eventArgs) + { + //循环删除图片 + foreach (UIElement element in ElementList) + { + cvsGround.Children.Remove(element); + } + + } + + private void ControlsLoad(List imageList) + { + + for (int i = 0; i < imageList.Count; i++) + { + // Create the image element. + Image simpleImage = new Image(); + simpleImage.Width = 180; + simpleImage.Height = 180; + simpleImage.Stretch = Stretch.Fill; + Canvas.SetTop(simpleImage, i * 206); + simpleImage.Stretch = Stretch.Fill; + BitmapImage bi = new BitmapImage(); + // BitmapImage.UriSource must be in a BeginInit/EndInit block. + bi.BeginInit(); + bi.UriSource = new Uri(imageList[i], UriKind.RelativeOrAbsolute); + bi.EndInit(); + simpleImage.Source = bi; + cvsGround.Children.Add(simpleImage); + } + + } + + private void DoMove(double to) + { + int Direction = 0; + ElementList.Clear(); + //添加图片的位置 + double endDouble = 0; + + //循环移动图片的位置 并且判断需要删除的图片 + foreach (UIElement element in cvsGround.Children) + { + double transferLeft = Convert.ToDouble(element.GetValue(Canvas.TopProperty)); + doubleAnimationImage.To = to + transferLeft; + element.BeginAnimation(Canvas.TopProperty, doubleAnimationImage);//设置动画应用的属性并启动动画 + transferLeft = Convert.ToDouble(element.GetValue(Canvas.TopProperty)); + if (to < 0) + { + if (transferLeft <= 0) + { + ElementList.Add(element); + } + if (transferLeft > endDouble) + { + endDouble = transferLeft; + } + Direction = 1; + } + else + { + if (transferLeft > cvsGround.Width) + { + ElementList.Add(element); + } + if (transferLeft < endDouble) + { + endDouble = transferLeft; + } + Direction = 0; + } + } + List imgList = new List(); + + //考虑每次移动的误差 endDouble 都要 加上图片的 宽度 + if (to <= 0) + { + imgList = ControlsLoad(ElementList.Count, Direction, endDouble + 206); + } + else + { + imgList = ControlsLoad(ElementList.Count, Direction, endDouble - 206); + } + curImageCount = (curImageCount + ElementList.Count >= liveImageList.Count) ? (curImageCount + ElementList.Count - liveImageList.Count) : (curImageCount + ElementList.Count); + + //循环移动 添加的图片 + foreach (UIElement element in imgList) + { + double transferLeft = Convert.ToDouble(element.GetValue(Canvas.TopProperty)); + doubleAnimationImage.To = to + transferLeft; + element.BeginAnimation(Canvas.TopProperty, doubleAnimationImage);//设置动画应用的属性并启动动画 + } + //循环删除图片 + foreach (UIElement element in ElementList) + { + element.BeginAnimation(Canvas.TopProperty, doubleAnimationImageEnd);//设置动画应用的属性并启动动画 + + doubleAnimationImageEnd.Completed += SbImageQueOnCompleted; //设置动画结束后的事件 + } + //System.Windows.Forms.MessageBox.Show(cvsGround.Children.Count + ""); + } + + + /// + /// 循环产生图片 + /// + /// 产生图片的个数 + /// 产生图片的方向 + /// 产生图片的位置 + /// + private List ControlsLoad(int num, int Direction, double Location) + { + List imgList = new List(); + for (int i = 0; i < num; i++) + { + + Image simpleImage = new Image(); + simpleImage.Width = 180; + simpleImage.Height = 180; + simpleImage.Stretch = Stretch.Fill; + //simpleImage.Margin = new Thickness(0, 0, 20, 0); + Canvas.SetTop(simpleImage, i * 206 + Location); + BitmapImage bi = new BitmapImage(); + // BitmapImage.UriSource must be in a BeginInit/EndInit block. + bi.BeginInit(); + string fileName = string.Empty; + if (curImageCount + i >= liveImageList.Count) + { + fileName = liveImageList[curImageCount + i - liveImageList.Count]; + } + else + { + fileName = liveImageList[curImageCount + i]; + } + bi.UriSource = new Uri(fileName, UriKind.RelativeOrAbsolute); + bi.EndInit(); + simpleImage.Source = bi; + cvsGround.Children.Add(simpleImage); + imgList.Add(simpleImage); + } + return imgList; + } + + private void CreateQR(string plainText) + { + this.couponQR.Dispatcher.Invoke(new Action(delegate + { + Class_Log log = new Class_Log(); + try + { + QRCodeGenerator qrGenerator = new QRCoder.QRCodeGenerator(); + //QRCodeGenerator.ECCLevel:纠错能力,Q级:约可纠错25%的数据码字 + QRCodeData qrCodeData = qrGenerator.CreateQrCode(plainText, QRCodeGenerator.ECCLevel.Q); + QRCode qrcode = new QRCode(qrCodeData); + Bitmap qrCodeImage = qrcode.GetGraphic(15); + MemoryStream ms = new MemoryStream(); + qrCodeImage.Save(ms, ImageFormat.Png); + ImageSourceConverter imageSourceConverter = new ImageSourceConverter(); + + couponQR.Source = (ImageSource)imageSourceConverter.ConvertFrom(ms); + } + catch (Exception ex) + { + log.WriteLogFile(ex.ToString(), "qr"); + + } + })); + + } + + private void StartVideo(string videoPath) + { + try + { + //this.control?.Dispose(); + //this.control = new VlcControl(); + //this.mainp.Content = this.control; + this.control.SourceProvider.CreatePlayer(this.vlcLibDirectory); + this.control.SourceProvider.MediaPlayer.PositionChanged += (_, args) => + { + curDate = DateTime.Now; + //log.WriteLogFile(args.NewPosition.ToString(), "PositionChanged"); + //this.control.SourceProvider.MediaPlayer.Position= + //string message = $"libVlc : {args.Level} {args.Message} @ {args.Module}"; + //System.Diagnostics.Debug.WriteLine(message); + }; + + this.control.SourceProvider.MediaPlayer.Buffering += (_, args) => + { + bengindTime = DateTime.Now; + //string message = $"libVlc : {args.Level} {args.Message} @ {args.Module}"; + //System.Diagnostics.Debug.WriteLine(message); + }; + var options = new string[] + { + "-I", + "dummy", + "--ignore-config", + "--extraintf=logger", + "--verbose=2", + "--fullscreen", + "--network-caching=300", + "--live-caching=300", + "--sout-mux-caching=300", + "--file-caching=300", + "--codec=mediacodec,iomx,all", + "--quiet-synchro", + " --clock-synchro=300", + "--network-synchronisation" + // "--plugin-path=" + this.vlcLibDirectory+ "\\plugins\\", + // "-I", + // "--no-sout-bridge-in-placeholder-switch-on-iframe", + // "--mosaic-delay=0", + // "--sout-display-delay=0", + //"dummy", + //"--ignore-config", + //"--extraintf=logger", + //"--verbose=2", + //"--fullscreen", + //"--network-caching=100", + //"--live-caching=100", + //"--sout-mux-caching=100", + //"--file-caching=100", + //"--codec=mediacodec,iomx,all", + //"--quiet-synchro", + //" --clock-synchro=100", + //"--network-synchronisation", + //"--screen-caching=100", + //"--rtsp-caching=100", + //"--fake-caching=100", + //"--http-caching=100", + //"--mms-caching=100", + //"--realrtsp-caching=100", + //"--skip-frames", + //"--drop-late-frames" + //, "--sout=#transcode{vcodec=h264,acodec=mpga,ab=128,channels=2,samplerate=44100}" + }; + //control.SourceProvider.MediaPlayer.Rate = 2.5f; + control.SourceProvider.MediaPlayer.Play(new Uri(videoPath)); + dtLiveStop = DateTime.Now; + //timer.Start(); + //control.SourceProvider.MediaPlayer.Time = 8000; + } + catch (Exception ex) + { + + log.WriteLogFile(ex.ToString(), "liveshowerror"); + } + } + + + private void LiveTimer_Tick(object sender, EventArgs e) + { + Class_Log log = new Class_Log(); + if (!this.control.SourceProvider.MediaPlayer.IsPlaying()) + { + loading.Dispatcher.Invoke((Action)(() => + { + loading.Visibility = Visibility.Visible; + })); + if ((dtLiveStop.HasValue && dtLiveStop.Value.AddMinutes(1) <= DateTime.Now)) + { + IntPtr WinLivePage = FindWindow(null, "LivePage"); //置顶窗体 + if (WinLivePage != null && WinLivePage != IntPtr.Zero) + { + SendMessage(WinLivePage, WM_CLOSE, 0, 0); + } + app.isLoadLive = false; + IntPtr windowWin = FindWindow(null, "WindowViewNew"); //置顶窗体 + if ((windowWin == null || windowWin == IntPtr.Zero)) + { + Action UploadApp = new Action(() => + { + App.Current.Dispatcher.Invoke((Action)(() => + { + try + { + WindowViewNew windowView = new WindowViewNew(0); + windowView.Show(); + } + catch (Exception ex) + { + log.WriteLogFile(ex.ToString(), "errorrrr"); + } + })); + }); + UploadApp.BeginInvoke(null, null); + } + this.Dispatcher.Invoke((Action)(() => + { + LiveTimer.Stop(); + this.control?.Dispose(); + this.Close(); + })); + } + return; + } + Action ac = new Action(() => + { + var curLiveDate = DateTime.Now; + try + { + //if ((dtLiveStop.HasValue && dtLiveStop.Value.AddMinutes(1) <= DateTime.Now) ) + var removeList = stopList.Where(i => i < curLiveDate.AddMinutes(-1)).ToList(); + stopList.RemoveRange(0, removeList.Count); + if ((dtLiveStop.HasValue && dtLiveStop.Value.AddMinutes(1) <= DateTime.Now) || stopList.Count >= 5) + //if ((dtLiveStop.HasValue && dtLiveStop.Value.AddMinutes(1) <= DateTime.Now)|| (livsStopList.Keys.Contains(curLiveDate.ToShortTimeString())&&livsStopList[curLiveDate.ToShortTimeString()]>=6)) + { + + IntPtr WinLivePage = FindWindow(null, "LivePage"); //置顶窗体 + if (WinLivePage != null && WinLivePage != IntPtr.Zero) + { + SendMessage(WinLivePage, WM_CLOSE, 0, 0); + } + app.isLoadLive = false; + IntPtr windowWin = FindWindow(null, "WindowViewNew"); //置顶窗体 + if ((windowWin == null || windowWin == IntPtr.Zero)) + { + Action UploadApp = new Action(() => + { + App.Current.Dispatcher.Invoke((Action)(() => + { + try + { + WindowViewNew windowView = new WindowViewNew(0); + windowView.Show(); + } + catch (Exception ex) + { + log.WriteLogFile(ex.ToString(), "errorrrr"); + } + })); + }); + UploadApp.BeginInvoke(null, null); + } + this.Dispatcher.Invoke((Action)(() => + { + LiveTimer.Stop(); + this.control?.Dispose(); + this.Close(); + })); + } + else + { + isLoad = true; + if (curDate <= DateTime.Now) + { + + if (playTime < this.control.SourceProvider.MediaPlayer.Time) + { + playTime = this.control.SourceProvider.MediaPlayer.Time; + loading.Dispatcher.Invoke((Action)(() => + { + loading.Visibility = Visibility.Hidden; + })); + + dtLiveStop = null; + } + else + { + if (!dtLiveStop.HasValue) + { + dtLiveStop = DateTime.Now; + stopList.Add(curLiveDate); + } + loading.Dispatcher.Invoke((Action)(() => + { + loading.Visibility = Visibility.Visible; + })); + + } + } + else + { + loading.Dispatcher.Invoke((Action)(() => + { + loading.Visibility = Visibility.Hidden; + })); + dtLiveStop = null; + } + } + } + catch (Exception ex) + { + + log.WriteLogFile(ex.ToString(), "errorrrrrrr"); + } + + }); + ac.BeginInvoke(null, null); + } + + private void WindowView_Closing(object sender, EventArgs e) + { + try + { + app.isLoadLive = false; + this.control?.Dispose(); + LiveTimer.Stop(); + } + catch (Exception ex) + { + log.WriteLogFile(ex.ToString(), "WindowViewErrorlog"); + } + } + } +} diff --git a/Container/Win/MarqueeControl.xaml b/Container/Win/MarqueeControl.xaml new file mode 100644 index 0000000..422b236 --- /dev/null +++ b/Container/Win/MarqueeControl.xaml @@ -0,0 +1,29 @@ + + + + + + + + + + + + + + + + + + + + + + diff --git a/Container/Win/MarqueeControl.xaml.cs b/Container/Win/MarqueeControl.xaml.cs new file mode 100644 index 0000000..71daf43 --- /dev/null +++ b/Container/Win/MarqueeControl.xaml.cs @@ -0,0 +1,256 @@ +using Container.Common; +using Container.SaversViewModel; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Data; +using System.Windows.Documents; +using System.Windows.Input; +using System.Windows.Media; +using System.Windows.Media.Animation; +using System.Windows.Media.Imaging; +using System.Windows.Navigation; +using System.Windows.Shapes; + +namespace Container.Win +{ + /// + /// MarqueeControl.xaml 的交互逻辑 + /// + public partial class MarqueeControl : UserControl + { + App app = ((App)Application.Current); + Storyboard std = null; + DoubleAnimation animation = null; + int total; + Class_Log log = new Class_Log(); + public MarqueeControl() + { + InitializeComponent(); + + } + + public MarqueeType ShowType + { + get { return (MarqueeType)this.GetValue(ShowTypeProperty); } + set { this.SetValue(ShowTypeProperty, value); } + } + public static readonly DependencyProperty ShowTypeProperty = DependencyProperty.Register("ShowType", typeof(MarqueeType), typeof(MarqueeControl), new PropertyMetadata(MarqueeType.Up)); + + + public double Speed + { + get { return (double)this.GetValue(SpeedProperty); } + set { this.SetValue(SpeedProperty, value); } + } + public static readonly DependencyProperty SpeedProperty = DependencyProperty.Register("Speed", typeof(double), typeof(MarqueeControl), new PropertyMetadata(1.5)); + + + public int SubTitleType + { + get { return (int)this.GetValue(SubTitleTypeProperty); } + set { this.SetValue(SubTitleTypeProperty, value); } + } + public static readonly DependencyProperty SubTitleTypeProperty = DependencyProperty.Register("SubTitleType", typeof(int), typeof(MarqueeControl), new PropertyMetadata(1)); + + + private void UserControl_Loaded(object sender, RoutedEventArgs e) + { + if (ShowType == MarqueeType.Up || ShowType == MarqueeType.Down) + { + std = (Storyboard)canvas.Resources["stdUp"]; + content.Width = canvas.ActualWidth; + txtItem.TextWrapping = TextWrapping.Wrap; + } + if (ShowType == MarqueeType.Left || ShowType == MarqueeType.Right) + { + std = (Storyboard)canvas.Resources["stdLeft"]; + content.Height = canvas.ActualHeight; + } + + + animation = (DoubleAnimation)std.Children[0]; + std.Completed += (t, r) => changeItem(); + } + + + private List itemsSource; + public List ItemsSource + { + get { return itemsSource; } + set + { + + this.Dispatcher.BeginInvoke(new Action(() => + { + if (std != null) + { + std.Stop(); + txtItem.Text = ""; + itemsSource = value; + if (itemsSource != null && itemsSource.Count > 0) + { + if (SubTitleType == 1) + { + app.TopSubTitleIndex = 0; + } + else + { + app.BottomSubTitleIndex = 0; + } + total = value.Count; + changeItem(); + } + } + })); + } + } + + + private void changeItem() + { + try + { + + if (SubTitleType == 1) + { + if (app.TopSubTitleIndex >= itemsSource.Count) + { + app.TopSubTitleIndex = 0; + ItemsSource = null; + app.TopSubTitle.Clear(); + if (std != null) + { + std.Begin(); + } + return; + } + txtItem.Text = app.TopSubTitle[app.TopSubTitleIndex].text.Replace("\n", "").ToString(); + txtItem.FontSize = app.TopSubTitle[app.TopSubTitleIndex].fontSize; + canvas.Height = 24 * (txtItem.FontSize / 16); + content.Height = canvas.Height; + canvas.VerticalAlignment = VerticalAlignment.Top; + if (!string.IsNullOrEmpty(app.TopSubTitle[app.TopSubTitleIndex].fontColor)) + { + BrushConverter converter = new BrushConverter(); + Brush newFill = (Brush)converter.ConvertFromString(app.TopSubTitle[app.TopSubTitleIndex].fontColor); + txtItem.Foreground = newFill; + } + } + else + { + if (app.BottomSubTitleIndex >= itemsSource.Count) + { + app.BottomSubTitleIndex = 0; + ItemsSource = null; + //ItemsSource = app.BottomSubTitle; + app.BottomSubTitle.Clear(); + if (std != null) + { + std.Begin(); + } + return; + } + txtItem.Text = app.BottomSubTitle[app.BottomSubTitleIndex].text.Replace("\n", "").ToString(); + txtItem.FontSize = app.BottomSubTitle[app.BottomSubTitleIndex].fontSize; + canvas.Height = 24 * (txtItem.FontSize / 16); + content.Height = canvas.Height; + canvas.VerticalAlignment = VerticalAlignment.Bottom; + if (!string.IsNullOrEmpty(app.BottomSubTitle[app.BottomSubTitleIndex].fontColor)) + { + BrushConverter converter = new BrushConverter(); + Brush newFill = (Brush)converter.ConvertFromString(app.BottomSubTitle[app.BottomSubTitleIndex].fontColor); + txtItem.Foreground = newFill; + } + + } + + //if (index >= itemsSource.Count) + //{ + // index = 0; + // if (SubTitleType == 1) + // { + // //ItemsSource = app.TopSubTitle; + // ItemsSource = null; + // app.TopSubTitle.Clear(); + // log.WriteLogFile("清空app.TopSubTitle" + app.TopSubTitle.Count); + // } + // else + // { + // ItemsSource = null; + // //ItemsSource = app.BottomSubTitle; + // app.BottomSubTitle.Clear(); + // log.WriteLogFile("清空app.BottomSubTitle" + app.BottomSubTitle.Count); + // } + // if (std != null) + // { + // std.Begin(); + // } + //} + + + txtItem.UpdateLayout(); + //double canvasWidth = canvas.ActualWidth; + double canvasWidth = canvas.ActualWidth; + double canvasHeight = canvas.ActualHeight; + double txtWidth = txtItem.ActualWidth; + double txtHeight = txtItem.ActualHeight; + if (ShowType == MarqueeType.Up) + { + animation.From = canvasHeight; + animation.To = -txtHeight; + } + else if (ShowType == MarqueeType.Down) + { + animation.From = -txtHeight; + animation.To = canvasHeight; + } + else if (ShowType == MarqueeType.Left) + { + animation.From = canvasWidth; + animation.To = -txtWidth; + } + else if (ShowType == MarqueeType.Right) + { + animation.From = -txtWidth; + animation.To = canvasWidth; + } + int time = 0; + if (ShowType == MarqueeType.Up || ShowType == MarqueeType.Down) + { + //time = (int)(txtHeight / canvasHeight * Speed); + time = (int)((canvasHeight + txtHeight) / Speed); + } + if (ShowType == MarqueeType.Left || ShowType == MarqueeType.Right) + { + //time = (int)(txtWidth / canvasWidth * Speed); + time = (int)((canvasWidth + txtWidth) / Speed); + } + if (time < 2) time = 2; + animation.Duration = new Duration(new TimeSpan(0, 0, time)); + if (std != null) + { + std.Begin(); + } + if (SubTitleType == 1) + { + app.TopSubTitleIndex++; + } + else + { + app.BottomSubTitleIndex++; + } + //index++; + } + catch (Exception e) + { + log.WriteLogFile(e.Message, "subtitle"); + //throw; + } + } + } +} diff --git a/Container/Win/MarqueeControlNew.xaml b/Container/Win/MarqueeControlNew.xaml new file mode 100644 index 0000000..50bee62 --- /dev/null +++ b/Container/Win/MarqueeControlNew.xaml @@ -0,0 +1,37 @@ + + + + + + + + + + + + + + + + + + + + + + diff --git a/Container/Win/MarqueeControlNew.xaml.cs b/Container/Win/MarqueeControlNew.xaml.cs new file mode 100644 index 0000000..75446bc --- /dev/null +++ b/Container/Win/MarqueeControlNew.xaml.cs @@ -0,0 +1,203 @@ +using Container.Common; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Data; +using System.Windows.Documents; +using System.Windows.Input; +using System.Windows.Media; +using System.Windows.Media.Animation; +using System.Windows.Media.Imaging; +using System.Windows.Navigation; +using System.Windows.Shapes; + +namespace Container.Win +{ + /// + /// MarqueeControlNew.xaml 的交互逻辑 + /// + public partial class MarqueeControlNew : UserControl + { + App app = ((App)Application.Current); + Storyboard std = null; + DoubleAnimation animation = null; + int total; + Class_Log log = new Class_Log(); + int Speed = 150; + string showText = string.Empty; + public MarqueeControlNew() + { + InitializeComponent(); + } + public void Load(string text, double width, double height, string fontSize, string backgroundColor, int? backgroundOpacity, string fontColor, string fontStyle, string animationSpeed) + { + try + { + + + std = (Storyboard)canvas.Resources["stdLeft"]; + this.Height = height; + this.Width = width; + canvas.Width = width; + canvas.Height = height; + content.Height = height; + canvas.VerticalAlignment = VerticalAlignment.Center; + content.VerticalAlignment = VerticalAlignment.Center; + + txtItem.FontSize = Convert.ToDouble(fontSize); + BrushConverter converter = new BrushConverter(); + if (!string.IsNullOrEmpty(backgroundColor)) + { + SolidColorBrush brush = (SolidColorBrush)converter.ConvertFromString(backgroundColor); + if (backgroundOpacity != null) + { + brush.Opacity = backgroundOpacity.Value / 100.0; + } + + canvas.Background = brush; + } + + if (!string.IsNullOrEmpty(fontColor)) + { + Brush newFill = (Brush)converter.ConvertFromString(fontColor); + txtItem.Foreground = newFill; + } + if (!string.IsNullOrEmpty(fontStyle)) + { + switch (fontStyle) + { + case "正常": + txtItem.FontStyle = FontStyles.Normal; + break; + case "加粗": + txtItem.FontWeight = FontWeights.Bold; + break; + case "斜体": + txtItem.FontStyle = FontStyles.Italic; + break; + case "加粗、斜体": + txtItem.FontStyle = FontStyles.Italic; + txtItem.FontWeight = FontWeights.Bold; + break; + default: + break; + } + } + if (!string.IsNullOrEmpty(animationSpeed)) + { + switch (animationSpeed) + { + case "慢": + Speed = 50; + break; + case "中等": + Speed = 90; + break; + case "快": + Speed = 130; + break; + case "很快": + Speed = 180; + break; + default: + Speed = 90; + break; + } + } + animation = (DoubleAnimation)std.Children[0]; + std.Completed += (t, r) => changeItem(); + showText = text; + std.Completed += delegate + { + if (txtItem.Visibility != Visibility.Visible) + { + txtItem.Visibility = Visibility.Visible; + txtItem.Text = showText; + } + + }; + changeItem(); + } + catch (Exception e) + { + + Class_Log log = new Class_Log(); + log.WriteLogFile(e.ToString()); + } + } + + private void changeItem() + { + try + { + txtItem.Text = showText; + txtItem.UpdateLayout(); + //double canvasWidth = canvas.ActualWidth; + double canvasWidth = canvas.ActualWidth; + double canvasHeight = canvas.ActualHeight; + double txtWidth = txtItem.ActualWidth; + double txtHeight = txtItem.ActualHeight; + //if (ShowType == MarqueeType.Up) + //{ + // animation.From = canvasHeight; + // animation.To = -txtHeight; + //} + //else if (ShowType == MarqueeType.Down) + //{ + // animation.From = -txtHeight; + // animation.To = canvasHeight; + //} + //else if (ShowType == MarqueeType.Left) + //{ + animation.From = canvasWidth; + animation.To = -txtWidth; + //} + //else if (ShowType == MarqueeType.Right) + //{ + // animation.From = -txtWidth; + // animation.To = canvasWidth; + //} + int time = 0; + //if (ShowType == MarqueeType.Up || ShowType == MarqueeType.Down) + //{ + // //time = (int)(txtHeight / canvasHeight * Speed); + // time = (int)((canvasHeight + txtHeight) / Speed); + //} + //if (ShowType == MarqueeType.Left || ShowType == MarqueeType.Right) + //{ + // //time = (int)(txtWidth / canvasWidth * Speed); + // time = (int)((canvasWidth + txtWidth) / Speed); + //} + time = (int)((canvasWidth + txtWidth) / Speed); + if (time < 2) time = 2; + animation.Duration = new Duration(new TimeSpan(0, 0, time)); + + if (std != null) + { + + std.Begin(); + + + //Canvas.SetLeft(content, 0); + } + //index++; + } + catch (Exception e) + { + log.WriteLogFile(e.Message, "subtitle"); + //throw; + } + } + + public void Dispose() + { + std.Stop(); + std.Children.Clear(); + } + } +} diff --git a/Container/Win/NavGuide.xaml b/Container/Win/NavGuide.xaml new file mode 100644 index 0000000..bd4f6a8 --- /dev/null +++ b/Container/Win/NavGuide.xaml @@ -0,0 +1,51 @@ + + + + ../Resources/SourceHanSansCN-Light_0.otf#Source Han Sans CN + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Container/Win/NavGuide.xaml.cs b/Container/Win/NavGuide.xaml.cs new file mode 100644 index 0000000..1bf5d1e --- /dev/null +++ b/Container/Win/NavGuide.xaml.cs @@ -0,0 +1,94 @@ +using Container.Common; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Data; +using System.Windows.Documents; +using System.Windows.Input; +using System.Windows.Media; +using System.Windows.Media.Imaging; +using System.Windows.Navigation; +using System.Windows.Shapes; + +namespace Container.Win +{ + /// + /// NavGuide.xaml 的交互逻辑 + /// + public partial class NavGuide : UserControl + { + Class_Log log = new Class_Log(); + + public NavGuide(double width, int height, string logo, string name = "", string distance = "", double angle = 0) + { + InitializeComponent(); + try + { + //this.Width = width; + //log.WriteLogFile(width.ToString(), "NavGuide"); + //log.WriteLogFile(height.ToString(), "NavGuide"); + //log.WriteLogFile((width - 40).ToString(), "NavGuide"); + //WinRect.Rect = new Rect(0, 0,width - 80, 200); + ImgRotate.Angle = angle; + Uri uri = new Uri(logo, UriKind.Absolute); + this.ImgLogo.Source = BitmapFrame.Create(uri); + TxtName.Text = name; + TxtDistance.Text = distance; + } + catch (Exception e) + { + log.WriteLogFile(e.ToString(), "NavGuide"); + } + } + + + + public static byte[] GetImageFromResponse(string url, string cookie = null) + { + redo: + try + { + System.Net.WebRequest request = System.Net.WebRequest.Create(url); + if (!string.IsNullOrWhiteSpace(cookie)) + { + request.Headers[System.Net.HttpRequestHeader.Cookie] = cookie; + } + + + System.Net.WebResponse response = request.GetResponse(); + + + using (Stream stream = response.GetResponseStream()) + { + using (MemoryStream ms = new MemoryStream()) + { + Byte[] buffer = new Byte[1024]; + int current = 0; + do + { + ms.Write(buffer, 0, current); + } while ((current = stream.Read(buffer, 0, buffer.Length)) != 0); + return ms.ToArray(); + } + } + } + catch (System.Net.WebException ex) + { + if (ex.Message == "基础连接已经关闭: 发送时发生错误。") + { + goto redo; + } + else + { + throw; + } + } + } + + } +} diff --git a/Container/Win/ProgControl.xaml b/Container/Win/ProgControl.xaml new file mode 100644 index 0000000..18be481 --- /dev/null +++ b/Container/Win/ProgControl.xaml @@ -0,0 +1,11 @@ + + + + diff --git a/Container/Win/ProgControl.xaml.cs b/Container/Win/ProgControl.xaml.cs new file mode 100644 index 0000000..2067388 --- /dev/null +++ b/Container/Win/ProgControl.xaml.cs @@ -0,0 +1,1154 @@ +using CefSharp.Wpf; +using Container.Business; +using Container.ChildWindows; +using Container.Common; +using Container.Model; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Data; +using System.Windows.Documents; +using System.Windows.Input; +using System.Windows.Media; +using System.Windows.Media.Animation; +using System.Windows.Media.Imaging; +using System.Windows.Navigation; +using System.Windows.Shapes; +using Transitionals.Controls; +using Vlc.DotNet.Wpf; + +namespace Container.Win +{ + /// + /// ProgControl.xaml 的交互逻辑 + /// + public partial class ProgControl : UserControl + { + string outLinePath; + App app = ((App)System.Windows.Application.Current); + DirectoryInfo vlcLibDirectory; + backgroundMaterialInfo backgroundMaterial; + string backgroundColor; + List components; + private Thread th1;//播放屏保的线程 + bool isStop = false; + BrushConverter converter = new BrushConverter(); + List tasks = new List(); + List marqueeControlNews = new List(); + List clockControls = new List(); + List weatherControls = new List(); + List imageControls = new List(); + List mediaControls = new List(); + List chromiumWebBrowsers = new List(); + List mediaElements = new List(); + List canvasWebBrowsers = new List(); + + + List cancellationTokens = new List(); + string[] options; + public ProgControl() + { + InitializeComponent(); + var currentAssembly = Assembly.GetEntryAssembly(); + var currentDirectory = new FileInfo(currentAssembly.Location).DirectoryName; + // Default installation path of VideoLAN.LibVLC.Windows + //vlcLibDirectory = new DirectoryInfo(currentDirectory); + ////初始化配置,指定引用库 + //vlcControl1.SourceProvider.CreatePlayer(vlcLibDirectory); + ////初始化配置,指定引用库 + //vlcControl2.SourceProvider.CreatePlayer(vlcLibDirectory); + + // Default installation path of VideoLAN.LibVLC.Windows + vlcLibDirectory = new DirectoryInfo(currentDirectory); + //初始化配置,指定引用库 + //vlcControl1.SourceProvider.CreatePlayer(vlcLibDirectory); + + + // options = new string[]{ + // "-I", + //"dummy", + //"--ignore-config", + //"--extraintf=logger", + //"--verbose=2", + //"--fullscreen", + //"--network-caching=300", + //"--live-caching=300", + //"--sout-mux-caching=300", + //"--file-caching=300", + //"--codec=mediacodec,iomx,all", + //"--quiet-synchro", + //" --clock-synchro=300", + //"--network-synchronisation", + //"--cr-average=10000" + // }; + //options = new string[] { "-I", "dummy", "--network-caching=<300", ":sout=#transcode{vcodec=h264,acodec=mpga,ab=128,channels=2,samplerate=44100" }; + + //canvas.Children.Add(vlcControl1); + //canvas.Children.Add(vlcControl2); + + } + + + + public void LoadProg(double width, double height, backgroundMaterialInfo backgroundmaterial, string backgroundcolor, List componentList) + { + Canvas canvas = new Canvas(); + Class_Log log = new Class_Log(); + canvas.Visibility = Visibility.Hidden; + backgroundMaterial = backgroundmaterial; + backgroundColor = backgroundcolor; + components = componentList; + this.Width = width; + this.Height = height; + canvas.Width = width; + canvas.Height = height; + DisposeNew(); + try + { + outLinePath = AppDomain.CurrentDomain.BaseDirectory + "/OutlineFiles"; + if (backgroundMaterial != null) + { + string fileExtension = string.Empty; + if (backgroundMaterial.filePath.Contains("?")) + { + fileExtension = backgroundMaterial.filePath.Substring(backgroundMaterial.filePath.LastIndexOf("."), backgroundMaterial.filePath.LastIndexOf("?") - backgroundMaterial.filePath.LastIndexOf(".")).ToLower(); + } + else + { + fileExtension = backgroundMaterial.filePath.Substring(backgroundMaterial.filePath.LastIndexOf(".")).ToLower(); + } + string url = outLinePath + "/Main/" + backgroundMaterial.fileHash + fileExtension; + if (File.Exists(url)) + { + Image image = new Image();//新建图片对象 + image.Source = new BitmapImage(new Uri(url));//读取图片 + ImageBrush ib = new ImageBrush();//新建图片对象 + ib.ImageSource = image.Source;//赋值为背景图片 + canvas.Background = ib;//将图片对象赋值给Canvas的Background + } + + } + else if (!string.IsNullOrEmpty(backgroundColor)) + { + Color color = (Color)ColorConverter.ConvertFromString(backgroundColor); + canvas.Background = new SolidColorBrush(color); + } + + int vlcCount = 0; + + isStop = false; + foreach (var item in components) + { + if ((item.materials == null || item.materials.Count == 0) && (item.typeCode == "text" || item.typeCode == "image" || item.typeCode == "video"||item.typeCode== "audio" || item.typeCode == "html" || item.typeCode == "url")) + { + continue; + } + if (item.typeCode == "image") + { + Image image = new Image(); + image.Width = item.width; + image.Height = item.height; + imageControls.Add(image); + canvas.Children.Add(image); + Canvas.SetLeft(image, item.offsetX); + Canvas.SetZIndex(image, item.zIndex); + Canvas.SetTop(image, item.offsetY); + image.Stretch = Stretch.Fill; + PlayImage(image, item.materials, item.config); + } + if (item.typeCode == "video"&& item.materials.Count>0) + { + //if (item.materials.Count > 1) + //{ + + // //TransitionElement element = new TransitionElement(); + + // //MediaElement media = new MediaElement(); + // //media.LoadedBehavior = MediaState.Manual; + // Canvas canvasM = new Canvas(); + // canvasM.Width = item.width; + // canvasM.Height = item.height; + // canvasM.Background = Brushes.Black; + // //media.Width = item.width; + // //media.Height = item.height; + // //media.Stretch = Stretch.Fill; + // //element.Width = item.width; + // //element.Height = item.height; + // //element.Content = media; + // //canvasM.Children.Add(element); + // Canvas.SetLeft(canvasM, item.offsetX); + // Canvas.SetZIndex(canvasM, item.zIndex); + // Canvas.SetTop(canvasM, item.offsetY); + // canvas.Children.Add(canvasM); + // canvasWebBrowsers.Add(canvasM); + // //mediaElements.Add(media); + // PlayVideo(canvasM, item.materials, item.config, 1); + // //media.Volume = 1; + + //} + if (item.materials.Count > 1) + { + int curIndex = 1; + string fileExtension = string.Empty; + string url = string.Empty; + + if (item.materials[curIndex].fileUrl.Contains("?")) + { + fileExtension = item.materials[curIndex-1].fileUrl.Substring(item.materials[curIndex-1].fileUrl.LastIndexOf("."), item.materials[curIndex-1].fileUrl.LastIndexOf("?") - item.materials[curIndex-1].fileUrl.LastIndexOf(".")).ToLower(); + } + else + { + fileExtension = item.materials[curIndex-1].fileUrl.Substring(item.materials[curIndex-1].fileUrl.LastIndexOf(".")).ToLower(); + } + url = outLinePath + "/Main/" + item.materials[curIndex-1].fileHash + fileExtension; + Canvas canvasM = new Canvas(); + canvasM.Width = item.width; + canvasM.Height = item.height; + canvasM.Background = Brushes.Transparent; + + string fileExtension1 = string.Empty; + string url1 = string.Empty; + + if (item.materials[curIndex].fileUrl.Contains("?")) + { + fileExtension1 = item.materials[curIndex].fileUrl.Substring(item.materials[curIndex].fileUrl.LastIndexOf("."), item.materials[curIndex].fileUrl.LastIndexOf("?") - item.materials[curIndex].fileUrl.LastIndexOf(".")).ToLower(); + } + else + { + fileExtension1 = item.materials[curIndex].fileUrl.Substring(item.materials[curIndex].fileUrl.LastIndexOf(".")).ToLower(); + } + + url1 = outLinePath + "/Main/" + item.materials[curIndex].fileHash + fileExtension1; + MediaElement media = new MediaElement(); + MediaElement media1 = new MediaElement(); + media.MediaEnded += new RoutedEventHandler((send, e) => + { + + string fileExtensionCur = string.Empty; + string urlCur = string.Empty; + List hashList = item.materials.Select(i => i.fileHash).ToList(); + string curUrl = media.Source.ToString(); + string curHash = curUrl.Substring(curUrl.LastIndexOf("/")+1, curUrl.LastIndexOf(".") - curUrl.LastIndexOf("/")-1); + curIndex= hashList.ToList().IndexOf(curHash); + if (curIndex + 2 >= item.materials.Count) + { + curIndex = curIndex + 2 - item.materials.Count; + } + else + { + curIndex = curIndex + 2; + } + //if (curIndex >= item.materials.Count) + //{ + // curIndex = 0; + //} + if (item.materials[curIndex].fileUrl.Contains("?")) + { + fileExtensionCur = item.materials[curIndex].fileUrl.Substring(item.materials[curIndex].fileUrl.LastIndexOf("."), item.materials[curIndex].fileUrl.LastIndexOf("?") - item.materials[curIndex].fileUrl.LastIndexOf(".")).ToLower(); + } + else + { + fileExtensionCur = item.materials[curIndex].fileUrl.Substring(item.materials[curIndex].fileUrl.LastIndexOf(".")).ToLower(); + } + urlCur = outLinePath + "/Main/" + item.materials[curIndex].fileHash + fileExtension; + + media1.Play(); + Thread.Sleep(500); + Canvas.SetZIndex(media1, 2); + Canvas.SetZIndex(media, 0); + Canvas.SetZIndex(media1, 1); + + media.Source = new Uri(urlCur); + media.Play(); + //media.Position = new TimeSpan(0, 0, 0, 0, 100); + media.Pause(); + // media.Position = new TimeSpan(0, 0, 0, 0, 100); + //curIndex++; + }); + + + media1.MediaEnded += new RoutedEventHandler((send, e) => + { + + string fileExtensionCur = string.Empty; + string urlCur = string.Empty; + List hashList = item.materials.Select(i => i.fileHash).ToList(); + string curUrl = media1.Source.ToString(); + string curHash = curUrl.Substring(curUrl.LastIndexOf("/") + 1, curUrl.LastIndexOf(".") - curUrl.LastIndexOf("/") - 1); + curIndex = hashList.ToList().IndexOf(curHash); + if (curIndex + 2 >= item.materials.Count) + { + curIndex = curIndex + 2 - item.materials.Count; + } + else + { + curIndex = curIndex + 2; + } + //if (curIndex >= item.materials.Count) + //{ + // curIndex = 0; + //} + if (item.materials[curIndex].fileUrl.Contains("?")) + { + fileExtensionCur = item.materials[curIndex].fileUrl.Substring(item.materials[curIndex].fileUrl.LastIndexOf("."), item.materials[curIndex].fileUrl.LastIndexOf("?") - item.materials[curIndex].fileUrl.LastIndexOf(".")).ToLower(); + } + else + { + fileExtensionCur = item.materials[curIndex].fileUrl.Substring(item.materials[curIndex].fileUrl.LastIndexOf(".")).ToLower(); + } + urlCur = outLinePath + "/Main/" + item.materials[curIndex].fileHash + fileExtension; + + media.Play(); + Thread.Sleep(500); + Canvas.SetZIndex(media, 2); + Canvas.SetZIndex(media1, 0); + Canvas.SetZIndex(media, 1); + media1.Source = new Uri(urlCur); + media1.Play(); + //media.Position = new TimeSpan(0, 0, 0, 0, 100); + media1.Pause(); + // media.Position = new TimeSpan(0, 0, 0, 0, 100); + //curIndex++; + }); + + media.LoadedBehavior = MediaState.Manual; + media.Stretch = Stretch.Fill; + media.Width = item.width; + media.Height = item.height; + media.Source = new Uri(url); + + + + media1.LoadedBehavior = MediaState.Manual; + media1.Stretch = Stretch.Fill; + media1.Width = item.width; + media1.Height = item.height; + media1.Source = new Uri(url1); + media1.Play(); + media1.Pause(); + + + canvasM.Children.Add(media); + canvasM.Children.Add(media1); + + Canvas.SetZIndex(media, 1); + Canvas.SetZIndex(media1, 0); + + + Canvas.SetLeft(canvasM, item.offsetX); + Canvas.SetZIndex(canvasM, item.zIndex); + Canvas.SetTop(canvasM, item.offsetY); + canvas.Children.Add(canvasM); + canvasWebBrowsers.Add(canvasM); + + mediaElements.Add(media); + media.Play(); + curIndex=2; + //PlayVideo(media, item.materials, item.config, 1); + + } + else if (item.materials.Count == 1) + { + + string fileExtension = string.Empty; + string url = string.Empty; + if (item.materials[0].fileUrl.Contains("?")) + { + fileExtension = item.materials[0].fileUrl.Substring(item.materials[0].fileUrl.LastIndexOf("."), item.materials[0].fileUrl.LastIndexOf("?") - item.materials[0].fileUrl.LastIndexOf(".")).ToLower(); + } + else + { + fileExtension = item.materials[0].fileUrl.Substring(item.materials[0].fileUrl.LastIndexOf(".")).ToLower(); + } + url = outLinePath + "/Main/" + item.materials[0].fileHash + fileExtension; + MediaElement media = new MediaElement(); + media.MediaEnded += new RoutedEventHandler((send, e) => + { + media.Position = new TimeSpan(0,0,0,0,100); + }); + media.LoadedBehavior = MediaState.Manual; + media.Stretch = Stretch.Fill; + media.Source = new Uri(url); + Canvas canvasM = new Canvas(); + canvasM.Width = item.width; + canvasM.Height = item.height; + canvasM.Background = Brushes.Transparent; + media.Width = item.width; + media.Height = item.height; + canvasM.Children.Add(media); + Canvas.SetLeft(canvasM, item.offsetX); + Canvas.SetZIndex(canvasM, item.zIndex); + Canvas.SetTop(canvasM, item.offsetY); + canvas.Children.Add(canvasM); + canvasWebBrowsers.Add(canvasM); + mediaElements.Add(media); + media.Play(); + //PlayVideo(media, item.materials, item.config, 1); + media.Volume = 1; + } + //else if (item.materials.Count == 1) + //{ + + // string fileExtension = string.Empty; + // string url = string.Empty; + // if (item.materials[0].fileUrl.Contains("?")) + // { + // fileExtension = item.materials[0].fileUrl.Substring(item.materials[0].fileUrl.LastIndexOf("."), item.materials[0].fileUrl.LastIndexOf("?") - item.materials[0].fileUrl.LastIndexOf(".")).ToLower(); + // } + // else + // { + // fileExtension = item.materials[0].fileUrl.Substring(item.materials[0].fileUrl.LastIndexOf(".")).ToLower(); + // } + // url = outLinePath + "/Main/" + item.materials[0].fileHash + fileExtension; + // MediaElement media = new MediaElement(); + // media.LoadedBehavior = MediaState.Manual; + // media.Volume = 1; + // EventTrigger eventTrigger = new EventTrigger(); + // eventTrigger.RoutedEvent = MediaElement.LoadedEvent; + // eventTrigger.SourceName = media.Name; + // BeginStoryboard begin = new BeginStoryboard(); + // Storyboard storyboard = new Storyboard(); + // MediaTimeline timeline = new MediaTimeline(); + // //timeline.FillBehavior = FillBehavior.Stop; + // timeline.Source = new Uri(url); + // timeline.RepeatBehavior = RepeatBehavior.Forever; + + // Storyboard.SetTarget(timeline, media); + // storyboard.Children.Add(timeline); + // begin.Storyboard = storyboard; + // eventTrigger.Actions.Add(begin); + // media.Triggers.Add(eventTrigger); + + // Canvas canvasM = new Canvas(); + // canvasM.Width = item.width; + // canvasM.Height = item.height; + // canvasM.Background = Brushes.Transparent; + // media.Width = item.width; + // media.Height = item.height; + // canvasM.Children.Add(media); + // Canvas.SetLeft(canvasM, item.offsetX); + // Canvas.SetZIndex(canvasM, item.zIndex); + // Canvas.SetTop(canvasM, item.offsetY); + // canvas.Children.Add(canvasM); + // canvasWebBrowsers.Add(canvasM); + // mediaElements.Add(media); + //} + + //vlcCount++; + //if (vlcCount == 1) + //{ + // canvasM1.Width= item.width; + // canvasM1.Height = item.height; + // media1.Width = item.width; + // media1.Height = item.height; + // Canvas.SetLeft(canvasM1, item.offsetX); + // Canvas.SetZIndex(canvasM1, item.zIndex); + // Canvas.SetTop(canvasM1, item.offsetY); + // PlayVideo(media1, item.materials, item.config, 1); + //} + //else + //{ + // canvasM2.Width = item.width; + // canvasM2.Height = item.height; + // media2.Width = item.width; + // media2.Height = item.height; + // Canvas.SetLeft(canvasM2, item.offsetX); + // Canvas.SetZIndex(canvasM2, item.zIndex); + // Canvas.SetTop(canvasM2, item.offsetY); + // PlayVideo(media2, item.materials, item.config, 2); + //} + + } + if (item.typeCode == "text" && item.materials != null && item.materials.Count > 0) + { + var textBackgroundColor = item.config.Value("backgroundColor"); + var textBackgroundOpacity = item.config.Value("backgroundOpacity"); + var textFontColor = item.config.Value("fontColor"); + var textFontSize = item.config.Value("fontSize"); + var textFontStyle = item.config.Value("fontStyle"); + var textAnimationSpeed = item.config.Value("animationSpeed"); + + string fileExtension = string.Empty; + string url = string.Empty; + if (item.materials[0].fileUrl.Contains("?")) + { + fileExtension = item.materials[0].fileUrl.Substring(item.materials[0].fileUrl.LastIndexOf("."), item.materials[0].fileUrl.LastIndexOf("?") - item.materials[0].fileUrl.LastIndexOf(".")).ToLower(); + } + else + { + fileExtension = item.materials[0].fileUrl.Substring(item.materials[0].fileUrl.LastIndexOf(".")).ToLower(); + } + url = outLinePath + "/Main/" + item.materials[0].fileHash + fileExtension; + string textContent = DownLoadMethod.ReadContext(url); + textContent = textContent.Replace("\r\n", " "); + MarqueeControlNew marqueeControlNew = new MarqueeControlNew(); + marqueeControlNew.Load(textContent, item.width, item.height, textFontSize, textBackgroundColor, textBackgroundOpacity, textFontColor, textFontStyle, textAnimationSpeed); + canvas.Children.Add(marqueeControlNew); + marqueeControlNews.Add(marqueeControlNew); + Canvas.SetLeft(marqueeControlNew, item.offsetX); + Canvas.SetZIndex(marqueeControlNew, item.zIndex); + Canvas.SetTop(marqueeControlNew, item.offsetY); + } + if (item.typeCode == "clock") + { + var backgroundColor = item.config.Value("backgroundColor"); + var fontColor = item.config.Value("fontColor"); + var style = item.config.Value("style"); + ClockControl clock = new ClockControl(); + clock.BindClock(style.Value, item.width, item.height, backgroundColor, fontColor); + canvas.Children.Add(clock); + clockControls.Add(clock); + Canvas.SetLeft(clock, item.offsetX); + Canvas.SetZIndex(clock, item.zIndex); + Canvas.SetTop(clock, item.offsetY); + } + if (item.typeCode == "weather") + { + var backgroundColor = item.config.Value("backgroundColor"); + var fontColor = item.config.Value("fontColor"); + var style = item.config.Value("style"); + var city = item.config.Value("cityName"); + if (string.IsNullOrEmpty(city)) + { + city = app.defaultCity; + } + if (!string.IsNullOrEmpty(city)) + { + WeatherControl weather = new WeatherControl(); + weather.LoadWeather(city, style.Value, item.width, item.height, backgroundColor, fontColor); + canvas.Children.Add(weather); + weatherControls.Add(weather); + Canvas.SetLeft(weather, item.offsetX); + Canvas.SetZIndex(weather, item.zIndex); + Canvas.SetTop(weather, item.offsetY); + } + } + if (item.typeCode == "audio" && item.materials != null && item.materials.Count > 0) + { + MediaPlayer media = new MediaPlayer(); + string fileExtension = string.Empty; + string url = string.Empty; + if (item.materials[0].fileUrl.Contains("?")) + { + fileExtension = item.materials[0].fileUrl.Substring(item.materials[0].fileUrl.LastIndexOf("."), item.materials[0].fileUrl.LastIndexOf("?") - item.materials[0].fileUrl.LastIndexOf(".")).ToLower(); + } + else + { + fileExtension = item.materials[0].fileUrl.Substring(item.materials[0].fileUrl.LastIndexOf(".")).ToLower(); + } + url = outLinePath + "/Main/" + item.materials[0].fileHash + fileExtension; + media.Open(new Uri(url, UriKind.Relative)); + media.MediaEnded += (sender, e) => + {//播放结束后 又重新播放 + media.Position = new TimeSpan(0); + }; + media.Play(); + mediaControls.Add(media); + } + if (item.typeCode == "html" && item.materials != null && item.materials.Count > 0) + { + string fileExtension = string.Empty; + string url = string.Empty; + if (item.materials[0].fileUrl.Contains("?")) + { + fileExtension = item.materials[0].fileUrl.Substring(item.materials[0].fileUrl.LastIndexOf("."), item.materials[0].fileUrl.LastIndexOf("?") - item.materials[0].fileUrl.LastIndexOf(".")).ToLower(); + } + else + { + fileExtension = item.materials[0].fileUrl.Substring(item.materials[0].fileUrl.LastIndexOf(".")).ToLower(); + } + url = outLinePath + "/Main/" + item.materials[0].fileHash + fileExtension; + ChromiumWebBrowser webBrowser = new ChromiumWebBrowser(); + webBrowser.Width = item.width; + webBrowser.Height = item.height; + webBrowser.Address = url.Replace(@"/", @"\").Replace(@"\\",@"\") ; + //webBrowser.GetBrowser().Reload(); + //webBrowser.Address = "file:///D:/360MoveData/Users/jiaxl/Desktop/Websocket.html"; + webBrowser.Background = Brushes.Black; + Canvas canvas1 = new Canvas(); + canvas1.Width = item.width; + canvas1.Height = item.height; + canvas1.Background = Brushes.White; + canvas1.Children.Add(webBrowser); + //webBrowser.Load(url); + canvas.Children.Add(canvas1); + canvasWebBrowsers.Add(canvas1); + chromiumWebBrowsers.Add(webBrowser); + Canvas.SetLeft(canvas1, item.offsetX); + Canvas.SetZIndex(canvas1, item.zIndex); + Canvas.SetTop(canvas1, item.offsetY); + } + if (item.typeCode == "url" && item.materials != null && item.materials.Count > 0 && item.materials[0].mediaInfo != null && !string.IsNullOrEmpty(item.materials[0].mediaInfo.url)) + { + ChromiumWebBrowser webBrowser = new ChromiumWebBrowser(); + webBrowser.Width = item.width; + webBrowser.Height = item.height; + webBrowser.Address = item.materials[0].mediaInfo.url; + webBrowser.Background = Brushes.Black; + Canvas canvas1 = new Canvas(); + canvas1.Width = item.width; + canvas1.Height = item.height; + canvas1.Background = Brushes.White; + canvas1.Children.Add(webBrowser); + //webBrowser.Load(url); + canvas.Children.Add(canvas1); + canvasWebBrowsers.Add(canvas1); + chromiumWebBrowsers.Add(webBrowser); + Canvas.SetLeft(canvas1, item.offsetX); + Canvas.SetZIndex(canvas1, item.zIndex); + Canvas.SetTop(canvas1, item.offsetY); + } + } + + } + catch (Exception ex) + { + + Class_Log _Log = new Class_Log(); + _Log.WriteLogFile(ex.ToString()); + } + canvasMain.Children.Add(canvas); + canvas.Visibility = Visibility.Visible; + if (canvasMain.Children.Count > 1) + { + canvasMain.Children[0].Visibility = Visibility.Hidden; + } + + } + + //private void PlayImage(Image image, List materials, JObject config) + //{ + // CancellationTokenSource source1 = new CancellationTokenSource(); + // cancellationTokens.Add(source1); + // CancellationToken token = source1.Token; + // TaskFactory factory = new TaskFactory(token); + // Task tsk1 = factory.StartNew(() => + // { + // var curPlayIndex = 0; + // var transitionPeriod = config.Value("transitionPeriod"); + // var transition = config.Value("transition"); + // string fileExtension = string.Empty; + // string url = string.Empty; + // DateTime? curDate = null; + // while (!isStop) + // { + // if (token.IsCancellationRequested) + // { + // //isStop = true; + // // 释放资源操作等等... + // break; + // } + // if (!curDate.HasValue||curDate.Value.AddMilliseconds(transitionPeriod * 1000) <= DateTime.Now) + // { + // if (materials[curPlayIndex].fileUrl.Contains("?")) + // { + // fileExtension = materials[curPlayIndex].fileUrl.Substring(materials[curPlayIndex].fileUrl.LastIndexOf("."), materials[curPlayIndex].fileUrl.LastIndexOf("?") - materials[curPlayIndex].fileUrl.LastIndexOf(".")).ToLower(); + // } + // else + // { + // fileExtension = materials[curPlayIndex].fileUrl.Substring(materials[curPlayIndex].fileUrl.LastIndexOf(".")).ToLower(); + // } + // curDate = DateTime.Now; + // url = outLinePath + "/Main/" + materials[curPlayIndex].fileHash + fileExtension; + // BindImage(image, url, transition); + // curPlayIndex++; + // if (curPlayIndex >= materials.Count) + // { + // curPlayIndex = 0; + // } + // } + // else + // { + // Thread.Sleep(1); + // } + // } + // }); + // //var thImage = new Thread(new ThreadStart(async () => + // //{ + // // var curPlayIndex = 0; + // // var transitionPeriod = config.Value("transitionPeriod"); + // // var transition = config.Value("transition"); + // // string fileExtension = string.Empty; + // // string url = string.Empty; + // // while (!isStop) + // // { + + // // if (materials[curPlayIndex].fileUrl.Contains("?")) + // // { + // // fileExtension = materials[curPlayIndex].fileUrl.Substring(materials[curPlayIndex].fileUrl.LastIndexOf("."), materials[curPlayIndex].fileUrl.LastIndexOf("?") - materials[curPlayIndex].fileUrl.LastIndexOf(".")).ToLower(); + // // } + // // else + // // { + // // fileExtension = materials[curPlayIndex].fileUrl.Substring(materials[curPlayIndex].fileUrl.LastIndexOf(".")).ToLower(); + // // } + // // url = outLinePath + "/Main/" + materials[curPlayIndex].fileHash + fileExtension; + // // BindImage(image, url, transition); + // // curPlayIndex++; + // // if (curPlayIndex >= materials.Count) + // // { + // // curPlayIndex = 0; + // // } + // // var taskProg = Task.Delay(transitionPeriod * 1000); + // // tasks.Add(taskProg); + // // await taskProg; + // // if (taskProg != null && taskProg.Status != TaskStatus.Canceled) + // // { + // // taskProg.Dispose(); + // // tasks.Remove(taskProg); + // // } + // // } + // //})); + // //thImage.IsBackground = true; + // //thImage.Start(); + + //} + + private void PlayImage(Image image, List materials, JObject config) + { + CancellationTokenSource source1 = new CancellationTokenSource(); + cancellationTokens.Add(source1); + CancellationToken token = source1.Token; + TaskFactory factory = new TaskFactory(token); + Task tsk1 = factory.StartNew(async () => + { + var curPlayIndex = 0; + var transitionPeriod = config.Value("transitionPeriod"); + var transition = config.Value("transition"); + string fileExtension = string.Empty; + string url = string.Empty; + DateTime? curDate = null; + while (!isStop) + { + if (token.IsCancellationRequested) + { + //isStop = true; + // 释放资源操作等等... + break; + } + //if (!curDate.HasValue || curDate.Value.AddMilliseconds(transitionPeriod * 1000) <= DateTime.Now) + //{ + if (materials[curPlayIndex].fileUrl.Contains("?")) + { + fileExtension = materials[curPlayIndex].fileUrl.Substring(materials[curPlayIndex].fileUrl.LastIndexOf("."), materials[curPlayIndex].fileUrl.LastIndexOf("?") - materials[curPlayIndex].fileUrl.LastIndexOf(".")).ToLower(); + } + else + { + fileExtension = materials[curPlayIndex].fileUrl.Substring(materials[curPlayIndex].fileUrl.LastIndexOf(".")).ToLower(); + } + curDate = DateTime.Now; + url = outLinePath + "/Main/" + materials[curPlayIndex].fileHash + fileExtension; + BindImage(image, url, transition); + curPlayIndex++; + if (curPlayIndex >= materials.Count) + { + curPlayIndex = 0; + } + if (token.IsCancellationRequested) + { + //isStop = true; + // 释放资源操作等等... + break; + } + else + { + await Task.Delay(transitionPeriod * 1000, token); + } + + //} + //else + //{ + // Thread.Sleep(1); + //} + } + }); + + } + + private void BindImage(Image image, string img, string transition) + { + Action action = new Action(()=> { + image.Dispatcher.Invoke(new Action(() => + { + if (img.ToLower().EndsWith(".gif")) + { + //FileStream stream = new FileStream(img, FileMode.Open, FileAccess.Read); + //XamlAnimatedGif.AnimationBehavior.SetSourceStream(image, stream); + //FileStream s = new FileStream(outLinePath + "/Main/" + ucList[app.currentIndex].sourceId + fileExtension, FileMode.Open, FileAccess.Read); + XamlAnimatedGif.AnimationBehavior.SetSourceUri(image, new Uri(img)); + XamlAnimatedGif.AnimationBehavior.SetRepeatBehavior(image, RepeatBehavior.Forever); + XamlAnimatedGif.AnimationBehavior.SetAutoStart(image, true); + } + else + { + image.Source = new BitmapImage(new Uri(img)); + } + })); + }); + action.BeginInvoke(null,null); + } + + private void PlayVideo(Canvas canvasM, List materials, JObject config,int type) + { + Action action = new Action(async delegate + { + + try + { + Class_Log log = new Class_Log(); + + //if (th1 == null) + //{ + CancellationTokenSource source1 = new CancellationTokenSource(); + cancellationTokens.Add(source1); + CancellationToken token = source1.Token; + TaskFactory factory = new TaskFactory(token); + Task tsk1 = factory.StartNew(async () => + { + var curPlayIndex = 0; + string fileExtension = string.Empty; + string url = string.Empty; + var curDate = DateTime.Now; + var duration = 0; + while (!isStop) + { + if (token.IsCancellationRequested) + { + //isStop = true; + // 释放资源操作等等... + break; + } + //log.WriteLogFile("-----curDate" + curDate.ToString("yyyy-MM-dd HH:mm:ss") + " url=" + url + " duration=" + duration); + //if (curDate.AddMilliseconds(duration) <= DateTime.Now) + //{ + if (materials[curPlayIndex].fileUrl.Contains("?")) + { + fileExtension = materials[curPlayIndex].fileUrl.Substring(materials[curPlayIndex].fileUrl.LastIndexOf("."), materials[curPlayIndex].fileUrl.LastIndexOf("?") - materials[curPlayIndex].fileUrl.LastIndexOf(".")).ToLower(); + } + else + { + fileExtension = materials[curPlayIndex].fileUrl.Substring(materials[curPlayIndex].fileUrl.LastIndexOf(".")).ToLower(); + } + url = outLinePath + "/Main/" + materials[curPlayIndex].fileHash + fileExtension; + duration = materials[curPlayIndex].duration; + //log.WriteLogFile("curDate" + curDate.ToString("yyyy-MM-dd HH:mm:ss") + " url=" + url + " duration=" + duration); + curDate = DateTime.Now; + //StopVideo(media); + log.WriteLogFile("播放","sssss"); + StartVideo(canvasM, url); + curPlayIndex++; + if (curPlayIndex >= materials.Count) + { + curPlayIndex = 0; + } + //var taskProg = Task.Delay(duration); + //tasks.Add(taskProg); + //await taskProg; + //if (taskProg != null && taskProg.Status != TaskStatus.Canceled) + //{ + // taskProg.Dispose(); + // tasks.Remove(taskProg); + //} + + //if (token.IsCancellationRequested) + //{ + // //isStop = true; + // // 释放资源操作等等... + // break; + //} + //else + //{ + await Task.Delay(duration - 5000, token); + + // } + //} + //else + //{ + // Thread.Sleep(1); + //} + + //Thread.Sleep(duration); + } + }); + //var thVideo = new Thread(new ThreadStart(async () => + // { + // var curPlayIndex = 0; + // string fileExtension = string.Empty; + // string url = string.Empty; + // while (!isStop) + // { + + // if (materials[curPlayIndex].fileUrl.Contains("?")) + // { + // fileExtension = materials[curPlayIndex].fileUrl.Substring(materials[curPlayIndex].fileUrl.LastIndexOf("."), materials[curPlayIndex].fileUrl.LastIndexOf("?") - materials[curPlayIndex].fileUrl.LastIndexOf(".")).ToLower(); + // } + // else + // { + // fileExtension = materials[curPlayIndex].fileUrl.Substring(materials[curPlayIndex].fileUrl.LastIndexOf(".")).ToLower(); + // } + // url = outLinePath + "/Main/" + materials[curPlayIndex].fileHash + fileExtension; + // int duration = materials[curPlayIndex].duration; + // StartVideo(vlcControl, url); + // curPlayIndex++; + // if (curPlayIndex >= materials.Count) + // { + // curPlayIndex = 0; + // } + + // var taskProg = Task.Delay(duration); + // tasks.Add(taskProg); + // await taskProg; + // if (taskProg != null && taskProg.Status != TaskStatus.Canceled) + // { + // taskProg.Dispose(); + // tasks.Remove(taskProg); + // } + // //Thread.Sleep(duration); + // } + // })); + //thVideo.IsBackground = true; + //thVideo.Start(); + //} + + } + catch (Exception ex) + { + Class_Log log = new Class_Log(); + log.WriteLogFile(ex.ToString(), "WindowViewErrorlog"); + } + }); + action.BeginInvoke(null, null); + + } + + private void StartVideo(Canvas canvasM, string videoPath) + { + try + { + Class_Log log = new Class_Log(); + + + //media1.Position = new TimeSpan(0, 0, 0, 100); + //Thread.Sleep(100); + canvasM.Dispatcher.Invoke(new Action(() => + { + MediaElement media1 = new MediaElement(); + media1.LoadedBehavior = MediaState.Manual; + media1.Width = canvasM.Width; + media1.Height = canvasM.Height; + media1.Stretch = Stretch.Fill; + //bool isStart = false; + media1.Visibility = Visibility.Hidden; + media1.Source = new Uri(videoPath); + media1.Play(); + + canvasM.Children.Add(media1); + Canvas.SetLeft(media1, 0); + Canvas.SetTop(media1, 0); + //Action action = new Action(()=> { + if (canvasM.Children.Count > 1) + { + Thread.Sleep(5000); + //media1.Position = new TimeSpan(0, 0, 0, 0, 1000); + } + media1.Visibility = Visibility.Visible; + if (canvasM.Children.Count > 1) + { + Thread.Sleep(5000); + int mediaCount = canvasM.Children.Count; + if (mediaCount > 2) + { + canvasM.Children.RemoveRange(0, mediaCount - 2); + } + if (canvasM.Children.Count > 1) + { + ((MediaElement)canvasM.Children[0]).Stop(); + } + } + //}); + //action.BeginInvoke(null,null); + + + //element.Content = media1; + //media.Stop(); + //media.Close(); + })); + //vlcControl.SourceProvider.MediaPlayer.Play(new Uri(videoPath)); + } + catch (Exception ex) + { + + // MessageBox.Show(ex.Message); + } + } + + private void StopVideo(MediaElement media) + { + try + { + media.Dispatcher.Invoke(new Action(() => + { + media.Stop(); + })); + //if (vlcControl.SourceProvider.MediaPlayer.IsPlaying()) + //{ + // vlcControl.SourceProvider.MediaPlayer.Pause(); + //} + + } + catch (Exception e) + { + + // MessageBox.Show(e.Message); + } + } + + + private async void UserControl_Loaded(object sender, RoutedEventArgs e) + { + + } + + public void DisposeNew() + { + try + { + isStop = true; + foreach (var item in tasks) + { + if (item != null && (item.IsCanceled || item.IsCompleted || item.IsFaulted)) + { + item.Dispose(); + } + } + tasks.Clear(); + foreach (var item in marqueeControlNews) + { + item.Dispose(); + } + marqueeControlNews.Clear(); + foreach (var item in clockControls) + { + item.Dispose(); + } + clockControls.Clear(); + foreach (var item in weatherControls) + { + item.Dispose(); + + } + weatherControls.Clear(); + foreach (var item in cancellationTokens) + { + item.Cancel(); + } + cancellationTokens.Clear(); + foreach (var item in mediaElements) + { + item.Stop(); + } + mediaElements.Clear(); + foreach (var item in mediaControls) + { + item.Stop(); + item.Close(); + } + mediaControls.Clear(); + + foreach (var item in chromiumWebBrowsers) + { + item.Dispose(); + } + chromiumWebBrowsers.Clear(); + + } + catch (Exception e) + { + Class_Log _Log = new Class_Log(); + _Log.WriteLogFile(e.ToString(), "prog"); + } + } + public void Dispose() + { + //try + //{ + // isStop = true; + // foreach (var item in tasks) + // { + // if (item != null && (item.IsCanceled || item.IsCompleted || item.IsFaulted)) + // { + // item.Dispose(); + // } + // } + // tasks.Clear(); + // foreach (var item in marqueeControlNews) + // { + // item.Dispose(); + // canvas.Children.Remove(item); + // } + // marqueeControlNews.Clear(); + // foreach (var item in clockControls) + // { + // item.Dispose(); + // canvas.Children.Remove(item); + + // } + // clockControls.Clear(); + // foreach (var item in weatherControls) + // { + // item.Dispose(); + // canvas.Children.Remove(item); + + // } + // weatherControls.Clear(); + // foreach (var item in cancellationTokens) + // { + // item.Cancel(); + // } + // cancellationTokens.Clear(); + // foreach (var item in mediaElements) + // { + // item.Stop(); + // } + // mediaElements.Clear(); + // foreach (var item in imageControls) + // { + // canvas.Children.Remove(item); + // } + // imageControls.Clear(); + // foreach (var item in mediaControls) + // { + // item.Stop(); + // item.Close(); + // } + // mediaControls.Clear(); + + // foreach (var item in chromiumWebBrowsers) + // { + // item.Dispose(); + // canvas.Children.Remove(item); + // } + // chromiumWebBrowsers.Clear(); + // foreach (var item in canvasWebBrowsers) + // { + // canvas.Children.Remove(item); + // } + // canvasWebBrowsers.Clear(); + + //} + //catch (Exception e) + //{ + // Class_Log _Log = new Class_Log(); + // _Log.WriteLogFile(e.ToString(), "prog"); + //} + } + } +} diff --git a/Container/Win/RichAD.xaml b/Container/Win/RichAD.xaml new file mode 100644 index 0000000..8122360 --- /dev/null +++ b/Container/Win/RichAD.xaml @@ -0,0 +1,104 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Container/Win/RichAD.xaml.cs b/Container/Win/RichAD.xaml.cs new file mode 100644 index 0000000..9f8f3eb --- /dev/null +++ b/Container/Win/RichAD.xaml.cs @@ -0,0 +1,135 @@ +using Container.Common; +using QRCoder; +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Drawing.Imaging; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Data; +using System.Windows.Documents; +using System.Windows.Input; +using System.Windows.Media; +using System.Windows.Media.Imaging; +using System.Windows.Navigation; +using System.Windows.Shapes; + +namespace Container.Win +{ + /// + /// RichAD.xaml 的交互逻辑 + /// + public partial class RichAD : UserControl + { + Class_Log log = new Class_Log(); + App app = ((App)Application.Current); + public RichAD(string logo, string name,string devNum, string floor, string floorOrder, string houseNum,string xaxis, string shopFormatName,string shopFormatIcon,string applets) + { + InitializeComponent(); + try + { + this.TxtName.Text = name; + this.TxtFloor.Text = floor; + logo = app.HttpUrl+ logo; + var httpPath = logo.Substring(0, logo.IndexOf("://") + 3); + var fileBackPath = logo.Substring(logo.IndexOf("://") + 3).Replace("//", "/").Replace("\\", "/").Replace(@"\", @"/"); + logo = httpPath + fileBackPath; + Uri uri = new Uri(logo, UriKind.Absolute); + this.ImgLogo.Source = BitmapFrame.Create(uri); + if (string.IsNullOrEmpty(shopFormatIcon)) + { + this.imgType.Visibility = Visibility.Hidden; + this.TxtType.Margin = new Thickness(320,-20,0,0); + } + else { + this.imgType.Visibility = Visibility.Visible; + shopFormatIcon = app.HttpUrl + shopFormatIcon; + var httpIconPath = shopFormatIcon.Substring(0, shopFormatIcon.IndexOf("://") + 3); + var fileBackIconPath = shopFormatIcon.Substring(shopFormatIcon.IndexOf("://") + 3).Replace("//", "/").Replace("\\", "/").Replace(@"\", @"/"); + shopFormatIcon = httpIconPath + fileBackIconPath; + Uri uriIcon = new Uri(shopFormatIcon, UriKind.Absolute); + this.iconImage.Source = BitmapFrame.Create(uriIcon); + this.TxtType.Margin = new Thickness(380, -20, 0, 0); + } + this.TxtType.Text = shopFormatName; + CreateQR(applets+ "?sname="+ devNum + "&spoint="+xaxis+"&sfloororder="+floorOrder+"&ehousenum="+houseNum); + + } + catch (Exception e) + { + log.WriteLogFile(e.ToString(), "RichAD"); + } + + } + + private void CreateQR(string plainText) + { + Class_Log log = new Class_Log(); + try + { + + + QRCodeGenerator qrGenerator = new QRCoder.QRCodeGenerator(); + //QRCodeGenerator.ECCLevel:纠错能力,Q级:约可纠错25%的数据码字 + QRCodeData qrCodeData = qrGenerator.CreateQrCode(plainText, QRCodeGenerator.ECCLevel.Q); + QRCode qrcode = new QRCode(qrCodeData); + Bitmap qrCodeImage = qrcode.GetGraphic(15); + MemoryStream ms = new MemoryStream(); + qrCodeImage.Save(ms, ImageFormat.Png); + ImageSourceConverter imageSourceConverter = new ImageSourceConverter(); + QRImage.Source = (ImageSource)imageSourceConverter.ConvertFrom(ms); + } + catch (Exception ex) + { + log.WriteLogFile(ex.ToString(), "qr"); + + } + } + + public static byte[] GetImageFromResponse(string url, string cookie = null) + { + redo: + try + { + System.Net.WebRequest request = System.Net.WebRequest.Create(url); + if (!string.IsNullOrWhiteSpace(cookie)) + { + request.Headers[System.Net.HttpRequestHeader.Cookie] = cookie; + } + + + System.Net.WebResponse response = request.GetResponse(); + + + using (Stream stream = response.GetResponseStream()) + { + using (MemoryStream ms = new MemoryStream()) + { + Byte[] buffer = new Byte[1024]; + int current = 0; + do + { + ms.Write(buffer, 0, current); + } while ((current = stream.Read(buffer, 0, buffer.Length)) != 0); + return ms.ToArray(); + } + } + } + catch (System.Net.WebException ex) + { + if (ex.Message == "基础连接已经关闭: 发送时发生错误。") + { + goto redo; + } + else + { + throw; + } + } + } + } +} diff --git a/Container/Win/UCImageText.xaml b/Container/Win/UCImageText.xaml new file mode 100644 index 0000000..6d74a16 --- /dev/null +++ b/Container/Win/UCImageText.xaml @@ -0,0 +1,12 @@ + + + + + + diff --git a/Container/Win/UCImageText.xaml.cs b/Container/Win/UCImageText.xaml.cs new file mode 100644 index 0000000..ba01ac5 --- /dev/null +++ b/Container/Win/UCImageText.xaml.cs @@ -0,0 +1,185 @@ +using Container.Common; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Data; +using System.Windows.Documents; +using System.Windows.Input; +using System.Windows.Media; +using System.Windows.Media.Imaging; +using System.Windows.Navigation; +using System.Windows.Shapes; + +namespace Container.Win +{ + /// + /// UCImageText.xaml 的交互逻辑 + /// + public partial class UCImageText : UserControl + { + App app = ((App)System.Windows.Application.Current); + public UCImageText(string img="", string text = "", string ScreenMatch = "") + { + InitializeComponent(); + if (!string.IsNullOrEmpty(img)) { + try + { + //this.UCText.Text = text; + ////Uri uri = new Uri(img, UriKind.RelativeOrAbsolute); + ////ImageBrush ib = new ImageBrush(); + ////ib.ImageSource = new BitmapImage(uri); + ////this.Img.Source = ib.ImageSource; + + //BinaryReader binReader = new BinaryReader(File.Open(img, FileMode.Open)); + + //FileInfo fileInfo = new FileInfo(img); + + //byte[] bytes = binReader.ReadBytes((int)fileInfo.Length); + + //binReader.Close(); + + //// 将图片字节赋值给BitmapImage + //BitmapImage bitmap = new BitmapImage(); + + //bitmap.BeginInit(); + //bitmap.StreamSource = new MemoryStream(bytes); + + //bitmap.EndInit(); + + //// 最后给Image控件赋值 + + //this.Img.Source = bitmap; + + //this.Img.Width = SystemParameters.PrimaryScreenWidth; + //this.Img.Height = SystemParameters.PrimaryScreenHeight; + //if (!string.IsNullOrEmpty(ScreenMatch)) + //{ + // if (ScreenMatch.Trim().Equals("拉伸")) + // { + // this.Img.Stretch = Stretch.Fill; + // } + // else if (ScreenMatch.Trim().Equals("适应")) + // { + // this.Img.Stretch = Stretch.Uniform; + // } + // else if (ScreenMatch.Trim().Equals("填充")) + // { + // this.Img.Stretch = Stretch.UniformToFill; + // } + // else if (ScreenMatch.Trim().Equals("居中")) + // { + // this.Img.Stretch = Stretch.None; + // } + //} + this.UCText.Text = text; + Uri uri = new Uri(img, UriKind.RelativeOrAbsolute); + ImageBrush ib = new ImageBrush(); + Class_Log log = new Class_Log(); + log.WriteLogFile(img, "ucimage"); + ib.ImageSource = new BitmapImage(uri); + this.Img.Source = ib.ImageSource; + this.Img.Width = app.ScreenWidth; + this.Img.Height = app.ScreenHeight; + if (!string.IsNullOrEmpty(ScreenMatch)) + { + if (ScreenMatch.Trim().Equals("拉伸")) + { + this.Img.Stretch = Stretch.Fill; + } + else if (ScreenMatch.Trim().Equals("适应")) + { + this.Img.Stretch = Stretch.Uniform; + } + else if (ScreenMatch.Trim().Equals("填充")) + { + this.Img.Stretch = Stretch.UniformToFill; + } + else if (ScreenMatch.Trim().Equals("居中")) + { + this.Img.Stretch = Stretch.None; + } + else + { + this.Img.Stretch = Stretch.Uniform; + } + } + } + catch (Exception ex) + { + Class_Log log = new Class_Log(); + log.WriteLogFile(ex.ToString(), "UCImageError"); + + } + } + + + } + + public void LoadData(double width, double height, string img, string text = "", string ScreenMatch = "") + { + try + { + this.Width = width; + this.Height = height; + Uri uri = new Uri(img, UriKind.RelativeOrAbsolute); + ImageBrush ib = new ImageBrush(); + Class_Log log = new Class_Log(); + log.WriteLogFile(img, "ucimage"); + if (File.Exists(img)) + { + + + ib.ImageSource = new BitmapImage(uri); + ib.Freeze(); + this.Img.Source = ib.ImageSource; + this.Img.Width = width; + this.Img.Height = height; + + if (!string.IsNullOrEmpty(ScreenMatch)) + { + if (ScreenMatch.Trim().Equals("拉伸")) + { + this.Img.Stretch = Stretch.Fill; + } + else if (ScreenMatch.Trim().Equals("适应")) + { + this.Img.Stretch = Stretch.Uniform; + } + else if (ScreenMatch.Trim().Equals("填充")) + { + this.Img.Stretch = Stretch.UniformToFill; + } + else if (ScreenMatch.Trim().Equals("居中")) + { + this.Img.Stretch = Stretch.None; + } + else + { + this.Img.Stretch = Stretch.Uniform; + } + } + else + { + this.Img.Stretch = Stretch.Uniform; + } + } + else + { + log.WriteLogFile(img + "不存在", "UCImageError"); + } + + } + catch (Exception ex) + { + Class_Log log = new Class_Log(); + log.WriteLogFile(ex.ToString(), "UCImageError"); + + } + } + } +} diff --git a/Container/Win/WeatherControl.xaml b/Container/Win/WeatherControl.xaml new file mode 100644 index 0000000..305a1a1 --- /dev/null +++ b/Container/Win/WeatherControl.xaml @@ -0,0 +1,178 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Container/Win/WeatherControl.xaml.cs b/Container/Win/WeatherControl.xaml.cs new file mode 100644 index 0000000..5fc2e65 --- /dev/null +++ b/Container/Win/WeatherControl.xaml.cs @@ -0,0 +1,187 @@ +using Container.Business; +using Container.Common; +using Container.Viewmodel; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Data; +using System.Windows.Documents; +using System.Windows.Input; +using System.Windows.Media; +using System.Windows.Media.Imaging; +using System.Windows.Navigation; +using System.Windows.Shapes; +using System.Windows.Threading; + +namespace Container.Win +{ + /// + /// WeatherControl.xaml 的交互逻辑 + /// + public partial class WeatherControl : UserControl + { + DispatcherTimer WeatherTimer = new DispatcherTimer();//停止播放视频的定时器 + JService jService = new JService(); + Class_Log log = new Class_Log(); + string city = string.Empty; + public WeatherControl() + { + InitializeComponent(); + WeatherTimer.Interval = TimeSpan.FromMinutes(60);//每秒刷新一次 + WeatherTimer.Tick += new EventHandler(WeatherTimer_Tick); + } + public void LoadWeather(string city,int type,double width,double height, string backgroundColor, string fontColor) { + this.Width = width; + this.Height = height; + this.city = city; + BrushConverter converter = new BrushConverter(); + if (!string.IsNullOrEmpty(backgroundColor)) + { + Brush newFill = (Brush)converter.ConvertFromString(backgroundColor); + gridMain.Background = newFill; + } + if (!string.IsNullOrEmpty(fontColor)) + { + Brush newFill = (Brush)converter.ConvertFromString(fontColor); + txtFL1.Foreground = newFill; + txtAQI1.Foreground = newFill; + txtAQI2.Foreground = newFill; + txtFL2.Foreground = newFill; + txtPM1.Foreground = newFill; + txtPM2.Foreground = newFill; + txtsd1.Foreground = newFill; + txtsd2.Foreground = newFill; + txtTemp1.Foreground = newFill; + txtTemp2.Foreground = newFill; + + txtTempZ1.Foreground = newFill; + txtsdp1.Foreground = newFill; + txtAQIA1.Foreground = newFill; + txtPMpm1.Foreground = newFill; + txtPMV1.Foreground = newFill; + + txtTempZ2.Foreground = newFill; + txtsdp2.Foreground = newFill; + txtAQIA2.Foreground = newFill; + txtPMpm2.Foreground = newFill; + txtPMV2.Foreground = newFill; + } + gridMain.Width = width; + gridMain.Height = height; + style1.Width = width; + style1.Height = height; + style2.Width = width; + style2.Height = height; + BindWeather(); + if (type == 0) + { + style1.Visibility = Visibility.Visible; + style2.Visibility = Visibility.Hidden; + } + else { + style2.Visibility = Visibility.Visible; + style1.Visibility = Visibility.Hidden; + } + + + WeatherTimer.Start(); + } + + private void WeatherTimer_Tick(object sender, EventArgs e) + { + try + { + BindWeather(); + } + catch (Exception ex) + { + log.WriteLogFile(ex.Message, "error"); + } + } + + private void BindWeather() + { + try + { + string imgUrl = ""; + WeatherViewModel weather = jService.GetEnvironmental(city); + if (weather == null || string.IsNullOrEmpty(weather.status)) + { + this.Width = 0; + this.Height = 0; + return; + } + if (weather.status.Contains("晴")) + { + imgUrl = "weather_sum.png"; + } + else if (weather.status.Contains("云")) + { + imgUrl = "weather_cloud.png"; + } + else if (weather.status.Contains("雨")) + { + imgUrl = "weather_rian.png"; + } + + else if (weather.status.Contains("雪")) + { + imgUrl = "weather_snow.png"; + } + else if (weather.status.Contains("阴") || weather.status.Contains("雾")) + { + imgUrl = "weather_cloud.png"; + } + else + { + imgUrl = "weather_sum.png"; + } + if (!string.IsNullOrEmpty(weather.temperature)) + { + txtTemp1.Text = Math.Floor(Convert.ToDouble(weather.temperature)).ToString(); + txtTemp2.Text = Math.Floor(Convert.ToDouble(weather.temperature)).ToString(); + } + if (!string.IsNullOrEmpty(weather.pm25)) + { + txtPM1.Text = Math.Floor(Convert.ToDouble(weather.pm25)).ToString(); + txtPM2.Text = Math.Floor(Convert.ToDouble(weather.pm25)).ToString(); + } + if (!string.IsNullOrEmpty(weather.humidity)) + { + txtsd1.Text = weather.humidity.Replace("%",""); + txtsd2.Text = weather.humidity.Replace("%", ""); + } + if (!string.IsNullOrEmpty(weather.windPower)) + { + txtFL1.Text = weather.windPower.Substring(0,weather.windPower.IndexOf("级")); + txtFL2.Text = weather.windPower.Substring(0,weather.windPower.IndexOf("级")); + } + if (!string.IsNullOrEmpty(weather.aqi)) + { + txtAQI1.Text = weather.aqi; + txtAQI2.Text = weather.aqi; + } + Uri uri = new Uri("pack://application:,,,/Container;component/image/weather/" + imgUrl); + ImageBrush ib = new ImageBrush(); + ib.ImageSource = new BitmapImage(uri); + this.imgWeather1.Source = ib.ImageSource; + this.imgWeather2.Source = ib.ImageSource; + } + catch (Exception e) + { + this.Width = 0; + this.Height = 0; + } + } + + public void Dispose() + { + if (WeatherTimer != null) + WeatherTimer.Stop(); + } + } +} diff --git a/Container/Win/WindowView.xaml b/Container/Win/WindowView.xaml new file mode 100644 index 0000000..ea75c32 --- /dev/null +++ b/Container/Win/WindowView.xaml @@ -0,0 +1,67 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Container/Win/WindowView.xaml.cs b/Container/Win/WindowView.xaml.cs new file mode 100644 index 0000000..82956dd --- /dev/null +++ b/Container/Win/WindowView.xaml.cs @@ -0,0 +1,1475 @@ +using Container.Business; +using Container.Common; +using Container.Model; +using Container.Services; +using Newtonsoft.Json; +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Configuration; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Net; +using System.Net.Sockets; +using System.Runtime.InteropServices; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Data; +using System.Windows.Documents; +using System.Windows.Input; +using System.Windows.Media; +using System.Windows.Media.Animation; +using System.Windows.Media.Imaging; +using System.Windows.Shapes; +using System.Windows.Threading; +using Transitionals; + + +namespace Container.Win +{ + /// + /// WindowView.xaml 的交互逻辑 优化闪屏问题还需4K视频测试 + /// + public partial class WindowView : Window + { + private Socket clentSocket; + double beginX = 0; + double endX = 0; + double beginY = 0; + double endY = 0; + bool isSysProg = true; + //创建接收客户端发送消息的线程 + Thread threadReceive; + DispatcherTimer VCDTimer = new DispatcherTimer();//停止播放视频的定时器 + DispatcherTimer NavTimer = new DispatcherTimer();//接地导航隐藏 + DispatcherTimer GCTimer = new DispatcherTimer(); + DispatcherTimer SubTitleTime = new DispatcherTimer(); + DispatcherTimer ProgramSyncTimer = new DispatcherTimer();//停止播放视频的定时器 + private Thread th1;//播放屏保的线程 + private VlcPlayer vlc_player_; + private List> ucListSys = new List>();//记录最新的屏保列表 + private List> ucNewsList = new List>(); //记录插播列表 + private List> ucList = new List>(); //记录插播列表 + PlayBackManage pbm; + private bool isStop = false;//是否关闭线程 + private bool isMedia = false;//当前播放的是否是视频 + private int duration = 0;//视频总时长; + int currentTime = 0; + int ImageShowTime = 0; + App app = ((App)Application.Current); + Class_Log log = new Class_Log(); + UserControl MyUc = new UserControl(); + bool isplay = false; + public bool isclose = false; + public bool Mainclose = false; + MouseHook mh = new MouseHook(); + // WebSocketManage web = new WebSocketManage(); + private List navDateList = new List(); + WebSocketForFaceManage webForFace = new WebSocketForFaceManage(); + WebSocketForProgram webForProgram = new WebSocketForProgram(); + JService jService = new JService(); + string outLinePath; + private double percentHeight = 1; + int isShowCountDown = 0; + bool isStartRunProg = false; + private Socket _socket; + /// + /// 鼠标位置数组 + /// + ArrayList Points = new ArrayList();// + public ObservableCollection ItemsList { get; set; } = new ObservableCollection(); + public WindowView(int type=1) + { + InitializeComponent(); + isShowCountDown = type; + this.Width = app.ScreenWidth-1; + this.Height = app.ScreenHeight-1; + + pbm = new PlayBackManage(); + //this.MouseLeftButtonUp += new MouseButtonEventHandler(this_MouseLeftButtonDown); + outLinePath = Environment.CurrentDirectory + "/OutlineFiles"; + mh.SetHook(); + mh.MouseClickEvent += this_MouseClickDown; + try + { + //Application.ExecutablePathSystem.Windows.Forms.Application.ExecutablePath.Replace("\\", "/").Substring(0, System.Windows.Forms.Application.ExecutablePath.Replace("\\", "/").LastIndexOf("/")) + string strImages = System.Environment.CurrentDirectory + "\\pic\\bg.png";//AppDomain.CurrentDomain.BaseDirectory + "pic\\common\\bg.png"; + if (File.Exists(strImages) == true) + { + Uri uri = new Uri(strImages, UriKind.Absolute); + ImageBrush ib = new ImageBrush(); + ib.ImageSource = new BitmapImage(uri); + this.waiting.Background = ib; + } + + } + catch (Exception ex) + { + log.WriteLogFile(ex.ToString(), "WindowViewErrorlog"); + } + } + private void LoadPics() + { + try + { + Storyboard _storyboard = new Storyboard(); + for (int i = 0; i < 220; i++) + { + + ObjectAnimationUsingKeyFrames oauf = new ObjectAnimationUsingKeyFrames(); + //ObjectAnimationUsingKeyFrames 可以对指定 Duration 内的一组 KeyFrames 中的 Object 属性值进行动画处理 + BitmapImage bitmap = new BitmapImage(); + bitmap.BeginInit(); + string name = i.ToString().PadLeft(5, '0'); + bitmap.UriSource = new Uri("pack://application:,,,/Container;component/image/CountDowmImage/倒计时透明度_" + name + ".png"); + bitmap.CacheOption = BitmapCacheOption.Default; + bitmap.EndInit(); + + ImageBrush imgBrush = new ImageBrush(bitmap); + //读取图片文件 + DiscreteObjectKeyFrame dokf = new DiscreteObjectKeyFrame(); + //DiscreteObjectKeyFrame 通过使用离散内插,可以在前一个关键帧的 Object 值及其自己的 Value 之间进行动画处理。 + dokf.KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromMilliseconds(i * 30)); + //KeyTime 获取或设置应到达关键帧的目标 Value 的时间 + //这里每隔40毫秒设置一张图片,也就是每秒1000/40=25帧 + dokf.Value = imgBrush; + oauf.KeyFrames.Add(dokf); + Storyboard.SetTargetProperty(oauf, new PropertyPath("(Rectangle.Fill)")); + //把动画应用到窗体的Rectangle中 + Storyboard.SetTarget(oauf, RectDisImage); + //RectDis是Rectangle的名称 + _storyboard.Children.Add(oauf); + //把ObjectAnimationUsingKeyFrames动画添加到Storyboard中 + } + _storyboard.Completed += new EventHandler(time_Completed); + //_storyboard.RepeatBehavior = RepeatBehavior.Forever; + _storyboard.Begin(); + + } + catch (Exception ex) + { + + log.WriteLogFile(ex.Message, "error"); + } + } + + void time_Completed(object sender, EventArgs e) + { + timeGrid.Visibility = Visibility.Hidden; + gridMain.Visibility = Visibility.Visible; + LoadData(); + } + + private void LoadData() { + try + { + + + this.GCTimer.Interval = TimeSpan.FromMinutes(30); //垃圾释放定时器 我定为每十分钟释放一次,大家可根据需要修改 + this.GCTimer.Start(); + + this.SubTitleTime.Interval = TimeSpan.FromSeconds(5); + GetSubtitle(); + this.SubTitleTime.Start(); + jService.SetPlayRecord(); + this.EventsRegistion(); // 注册事件 + this.ProgramSyncTimer.Start(); + NavTimer.Tick += new EventHandler(NavTimer_Tick); + NavTimer.Interval = TimeSpan.FromSeconds(1);//每秒刷新一次 + if (app.screensaver.ScreenType == 0 || (app.AppList.Count == 0 && string.IsNullOrEmpty(app.configstartexe))) + { + _canvas.Visibility = Visibility.Hidden; + } + else if (app.screensaver.ScreenType < 5) + { + _canvas.Visibility = Visibility.Visible; + RectDis.Visibility = Visibility.Visible; + gridImage.Visibility = Visibility.Hidden; + LoadPics(app.screensaver.ScreenType); + } + else if (!string.IsNullOrEmpty(app.screensaver.ScreenFile)) + { + + string fileExtension = System.IO.Path.GetExtension(app.screensaver.ScreenFile); + if (fileExtension.ToLower() == ".gif") + { + _canvas.Visibility = Visibility.Visible; + RectDis.Visibility = Visibility.Hidden; + gridImage.Visibility = Visibility.Hidden; + GifImageLib.GifImage image = new GifImageLib.GifImage(); + image.Source = app.screensaver.ScreenFile; + image.Width = 300; + image.Height = 300; + image.Background = new SolidColorBrush(Colors.Transparent); + gridmove.Children.Add(image); + } + else + { + _canvas.Visibility = Visibility.Visible; + RectDis.Visibility = Visibility.Hidden; + gridImage.Visibility = Visibility.Visible; + Uri uri = new Uri(app.screensaver.ScreenFile, UriKind.Absolute); + gridImage.Source = new BitmapImage(uri); + } + } + if (app.screensaver.ScreenEffect == 1) + { + LoadGif(); + if (app.screensaver.EffectType == 0) + { + gridmove.Margin = new Thickness(0, (_canvas.Height - gridmove.Height) / 2, 0, (_canvas.Height - gridmove.Height) / 2); + } + + } + else + { + if (app.screensaver.EffectType == 0) + { + gridmove.Margin = new Thickness((_canvas.Width - gridmove.Width), (_canvas.Height - gridmove.Height), 0, 0); + } + else + { + gridmove.Margin = new Thickness((_canvas.Width - gridmove.Width) / 2, (_canvas.Height - gridmove.Height) / 2, (_canvas.Width - gridmove.Width) / 2, (_canvas.Height - gridmove.Height) / 2); + } + } + jService.GetSyncDev(); + StartPlay(); + + WebSocketForFaceManage.WebSocketReceiveEvent += new WebSocketForFaceManage.WebSocketReceiveDelegate(WebSocketManage_WebSocketReceiveEvent); + webForFace.OpenWebSocket(); + WebSocketForKiosk.allSocketsForKiosk.ToList().ForEach(s => s.Send("首页")); + + } + catch (Exception e) + { + + log.WriteLogFile(e.ToString(), "WindowViewErrorlog"); + } + } + + private void WindowView_Load(object sender, RoutedEventArgs e) + { + + try + { + //LoadScoket(); + this.Width = SystemParameters.PrimaryScreenWidth-1; + this.Height = SystemParameters.PrimaryScreenHeight-1; + percentHeight = SystemParameters.PrimaryScreenHeight / 3840; + tbMessage.FontSize = 30 * percentHeight; + _canvas.Height = 2000 * percentHeight; + _canvas.Width = SystemParameters.PrimaryScreenWidth-1; + gridmove.Width = SystemParameters.PrimaryScreenWidth > 1920 ? 600 : 300; + gridmove.Height = SystemParameters.PrimaryScreenWidth > 1920 ? 600 : 300; + gridImage.Width = SystemParameters.PrimaryScreenWidth > 1920 ? 600 : 300; + gridImage.Height = SystemParameters.PrimaryScreenWidth > 1920 ? 600 : 300; + RectDis.Width = SystemParameters.PrimaryScreenWidth > 1920 ? 600 : 300; + RectDis.Height = SystemParameters.PrimaryScreenWidth > 1920 ? 600 : 300; + + string pluginPath = System.Environment.CurrentDirectory + "\\plugins\\"; + log.WriteLogFile(pluginPath, "plugins"); + vlc_player_ = new VlcPlayer(pluginPath, false); + VCDTimer.Interval = TimeSpan.FromSeconds(1);//每秒刷新一次 + ProgramSyncTimer.Interval = TimeSpan.FromMinutes(1); + + ShowCursor(0); + MyUc.Width = mainp.Width; + MyUc.Height = mainp.Height; + Color color = (Color)ColorConverter.ConvertFromString("Black"); + MyUc.Background = new SolidColorBrush(color); + + subtitleTop.Width = SystemParameters.PrimaryScreenWidth-1; + //subtitleTop.Margin = new Thickness(100, 10, 100, 10); + //subtitle.VerticalAlignment = VerticalAlignment.Bottom; + scrollingTextControlTop.Width = subtitleTop.Width; + scrollingTextControlTop.Height = subtitleTop.Height; + scrollingTextControlTop.Speed = 150; + scrollingTextControlTop.ShowType = SaversViewModel.MarqueeType.Left; + scrollingTextControlTop.SubTitleType = 1; + //scrollingTextControlTop.Margin = new Thickness(100, 0, 100, 0); + scrollingTextControlTop.ItemsSource = new List() { }; + + subtitleBottom.Width = SystemParameters.PrimaryScreenWidth-1; + //subtitleBottom.Margin = new Thickness(100, 10, 100, 10); + //subtitle.VerticalAlignment = VerticalAlignment.Bottom; + scrollingTextControlBottom.Width = subtitleTop.Width; + scrollingTextControlBottom.Height = subtitleTop.Height; + scrollingTextControlBottom.Speed = 150; + scrollingTextControlBottom.ShowType = SaversViewModel.MarqueeType.Left; + scrollingTextControlBottom.SubTitleType = 2; + //scrollingTextControlBottom.Margin = new Thickness(100, 0, 100, 0); + scrollingTextControlBottom.ItemsSource = new List() { }; + + + WebSocketForProgram.WebSocketReceiveEvent += new WebSocketForProgram.WebSocketReceiveDelegate(WebSocketManage_WebSocketReceiveEvent); + if (isShowCountDown == 1) + { + LoadPics(); + } + else + { + timeGrid.Visibility = Visibility.Hidden; + gridMain.Visibility = Visibility.Visible; + LoadData(); + } + + + } + catch (Exception ex) + { + log.WriteLogFile(ex.ToString(), "WindowViewErrorlog"); + } + + } + + //private void LoadScoket() + //{ + // //1、创建Socket对象 + // Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); + // _socket = socket; + // //2、连接服务器,绑定IP 与 端口 + // IPEndPoint iPEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8000); + // try + // { + // socket.Connect(iPEndPoint); + // } + // catch (Exception) + // { + // //MessageBox.Show("连接失败,请重新连接!", "提示"); + // //return; + // } + // //3、接收消息 + // ThreadPool.QueueUserWorkItem(new WaitCallback(ReceiveServerMsg), socket); + //} + + ///// + ///// 不断接收客户端信息子线程方法 + ///// + ///// 参数Socke对象 + //private void ReceiveServerMsg(object obj) + //{ + // var proxSocket = obj as Socket; + // //创建缓存内存,存储接收的信息 ,不能放到while中,这块内存可以循环利用 + // byte[] data = new byte[1020 * 1024]; + // while (true) + // { + // int len; + // try + // { + // //接收消息,返回字节长度 + // len = proxSocket.Receive(data, 0, data.Length, SocketFlags.None); + // } + // catch (Exception ex) + // { + // return;//让方法结束,终结当前客户端数据的异步线程,方法退出,即线程结束 + // } + + // if (len > 0)//判断接收的字节数 + // { + // ////将消息显示到TxtLog + // string msgStr = Encoding.Default.GetString(data, 0, len); + // Dictionary Commands = JsonConvert.DeserializeObject>(msgStr); + // var type = Commands["Type"].ToString(); + // if (type == "playprog") + // { + // isStartRunProg = true; + // if (app.isProgramServer) + // { + // app.websocketForProgramServer.CloasSocket(); + // app.isProgramServer = false; + // } + // if (app.isProgramSync) { + // app.webSocketForProgram.CloseWebSocket(); + // app.isProgramSync = false; + // } + // this.ProgramSyncTimer.Stop(); + // if (isplay) + // { + // isplay = false; + // vlc_player_.Stop(); + // VCDTimer.Stop(); + // } + // } + // else if (type == "shutdownprog") + // { + // this.ProgramSyncTimer.Start(); + // } + // } + // } + //} + + [DllImport("user32.dll", EntryPoint = "ShowCursor", CharSet = CharSet.Auto)] + public static extern void ShowCursor(int status); + + void OnGarbageCollection(object sender, EventArgs e) + { + GC.Collect(); + GC.WaitForPendingFinalizers(); + GC.Collect(); + } + + public void EventsRegistion() + { + this.GCTimer.Tick += new EventHandler(OnGarbageCollection); + this.SubTitleTime.Tick += new EventHandler(GetSubTitle); + this.VCDTimer.Tick += new EventHandler(VCDTimer_Tick); + this.ProgramSyncTimer.Tick += new EventHandler(ProgramSyncTimer_Tick); + } + + void GetSubTitle(object sender, EventArgs e) + { + GetSubtitle(); + } + + private void GetSubtitle() + { + if (app.TopSubTitle.Count == 0 && app.BottomSubTitle.Count == 0) + { + jService.GetSubTitle(); + scrollingTextControlTop.ItemsSource = app.TopSubTitle.Select(i => i.text).ToList(); + scrollingTextControlBottom.ItemsSource = app.BottomSubTitle.Select(i => i.text).ToList(); + } + if (app.TopSubTitle.Count > 0 && subtitleTop.Visibility == Visibility.Hidden) + { + subtitleTop.Visibility = Visibility.Visible; + //scrollingTextControlTop.ItemsSource = app.TopSubTitle; + } + + if (app.TopSubTitle == null || app.TopSubTitle.Count == 0 && subtitleTop.Visibility == Visibility.Visible) + { + subtitleTop.Visibility = Visibility.Hidden; + } + + if (app.BottomSubTitle.Count > 0 && subtitleBottom.Visibility == Visibility.Hidden) + { + subtitleBottom.Visibility = Visibility.Visible; + //scrollingTextControlBottom.ItemsSource = app.BottomSubTitle; + } + if (app.BottomSubTitle == null || app.BottomSubTitle.Count == 0 && subtitleBottom.Visibility == Visibility.Visible) + { + subtitleBottom.Visibility = Visibility.Hidden; + } + + } + + + private void NavTimer_Tick(object sender, EventArgs e) + { + try + { + if (navDateList.Count > 0) + { + if (navDateList[0].AddSeconds(15) <= DateTime.Now) + { + this.stackPanel1.Dispatcher.Invoke( + new Action( + delegate + { + stackPanel1.Children.RemoveAt(navDateList.Count - 1); + navDateList.RemoveAt(0); + if (navDateList.Count == 0) + { + NavTimer.Stop(); + } + } + )); + + } + } + } + catch (Exception ex) + { + log.WriteLogFile(ex.Message, "error"); + } + } + + private void VCDTimer_Tick(object sender, EventArgs e) + { + try + { + //if (currentTime >= duration - 5) + //{ + // isMedia = false; + // SetProcessWorkingSetSize(Process.GetCurrentProcess().Handle, -1, -1); + + //} + //else + // currentTime++; + log.WriteLogFile(currentTime + " " + duration, "1111"); + if (currentTime >= duration) + { + isMedia = false; + SetProcessWorkingSetSize(Process.GetCurrentProcess().Handle, -1, -1); + //if (isplay) + //{ + // isplay = false; + // vlc_player_.Stop(); + // VCDTimer.Stop(); + //} + + } + else + currentTime++; + } + catch (Exception ex) + { + log.WriteLogFile(ex.Message, "error"); + } + } + + private void ProgramSyncTimer_Tick(object sender, EventArgs e) + { + try + { + jService.GetSyncDev(); + } + catch (Exception ex) + { + log.WriteLogFile(ex.Message, "error"); + } + } + private void WindowView_Closing(object sender, System.ComponentModel.CancelEventArgs e) + { + try + { + if (VCDTimer != null) + VCDTimer.Stop(); + if (NavTimer != null) + NavTimer.Stop(); + if (SubTitleTime != null) + SubTitleTime.Stop(); + if (GCTimer != null) + GCTimer.Stop(); + if (ProgramSyncTimer != null) + ProgramSyncTimer.Stop(); + isStop = true; + //if (th1 != null) + // th1.Abort(); + if (vlc_player_ != null) + vlc_player_.Stop(); + vlc_player_ = null; + mh.UnHook(); + //webForFace.CloseWebSocket(); + } + catch (Exception ex) + { + log.WriteLogFile("--------" + ex.ToString(), "WindowViewErrorlog"); + } + try + { + + log.WriteLogFile("程序关闭 isclose" + isclose.ToString() + " Mainclose" + Mainclose.ToString(), "WindowViewErrorlog"); + //if (!isclose && !Mainclose) + //{ + // Process[] process = Process.GetProcesses(); + // foreach (Process prc in process) + // { + // if (prc.ProcessName.Equals(System.Diagnostics.Process.GetCurrentProcess().ProcessName)) + // prc.Kill(); + // } + //} + } + catch (Exception ex) + { + log.WriteLogFile(ex.ToString(), "WindowViewErrorlog"); + } + } + + public void FulshMemor() + { + try + { + SetProcessWorkingSetSize(Process.GetCurrentProcess().Handle, -1, -1); + GC.Collect(); + //Mouse.OverrideCursor = Cursors.None; + } + catch { } + } + /// + /// 根据获取到的信息生成UseControl + /// + private void GetUControl() + { + try + { + + //foreach (var item in ucList) + //{ + //} + ucListSys.Clear(); + ucNewsList.Clear(); + ucList.Clear(); + FulshMemor(); + //mainp.Visibility = Visibility.Hidden; + //waiting.Visibility = Visibility.Visible; + //List> result = pbm.GetResource(); + List> result =null; + if (result == null || result.Count == 0) + { + if (isplay) + { + isplay = false; + vlc_player_.Stop(); + VCDTimer.Stop(); + } + mainp.Visibility = Visibility.Hidden; + waiting.Visibility = Visibility.Visible; + return; + } + mainp.Visibility = Visibility.Visible; + waiting.Visibility = Visibility.Hidden; + //生成useControl,并记录相对应的效果 + foreach (var item in result) + { + + //waiting.Visibility = Visibility.Hidden; + try + { + string fileExtension = System.IO.Path.GetExtension(item.Item1.img).ToLower(); + FileTypeJudgment fvdo = new FileTypeJudgment() { TypeTarget = new TypeVideo() }; + var ext = fileExtension.Split('.').Last();//文件类型 + //if (fileExtension != ".mp4"&&fileExtension != ".mov" && fileExtension != ".avi") + if (fvdo.Judge(ext)) + { + + UserControl uc = new UserControl(); + uc.Width = mainp.Width; + uc.Height = mainp.Height; + Color color = (Color)ColorConverter.ConvertFromString("Black"); + uc.Background = new SolidColorBrush(color); + if (File.Exists(item.Item1.img)) + { + if (item.Item1.protype == "1") + { + ucListSys.Add(new Tuple(uc, item.Item2, item.Item1, true)); + } + else + { + ucNewsList.Add(new Tuple(uc, item.Item2, item.Item1, true)); + } + //ucList.Add(new Tuple(uc, item.Item2, item.Item1, true)); + //ucListbeifen.Add(new Tuple(uc, item.Item2, item.Item1, false)); + } + + } + else + { + if (File.Exists(item.Item1.img)) + { + UCImageText ucimg = new UCImageText(item.Item1.img, item.Item1.text, item.Item1.screenmatch); + ucimg.Width = mainp.Width; + ucimg.Height = mainp.Height; + Color colorimg = (Color)ColorConverter.ConvertFromString("Black"); + ucimg.Background = new SolidColorBrush(colorimg); + if (item.Item1.protype == "1") + { + ucListSys.Add(new Tuple(ucimg, item.Item2, item.Item1, false)); + } + else + { + ucNewsList.Add(new Tuple(ucimg, item.Item2, item.Item1, false)); + } + //ucListbeifen.Add(new Tuple(ucimg, item.Item2, item.Item1, false)); + + } + } + } + catch (Exception ex) { log.WriteLogFile(ex.ToString(), "AddimgError"); } + + } + ucList = ucNewsList.Where(i => Convert.ToDateTime(i.Item3.launchtime) < DateTime.Now && Convert.ToDateTime(i.Item3.expirydate) > DateTime.Now).ToList(); + isSysProg = false; + if (ucList == null || ucList.Count == 0) + { + ucList = ucListSys; + isSysProg = true; + } + else + { + ucListSys.Clear(); + } + if (ucList.Count > 0) + { + mainp.Visibility = Visibility.Visible; + waiting.Visibility = Visibility.Hidden; + app.currentIndex = 0; + } + else { + if (isplay) + { + isplay = false; + vlc_player_.Stop(); + VCDTimer.Stop(); + } + mainp.Visibility = Visibility.Hidden; + waiting.Visibility = Visibility.Visible; + } + //else if (ucListbeifen.Count > 0) + //{ + // foreach (var uc in ucListbeifen) + // { + // ucList.Add(uc); + // } + //} + if (!File.Exists(outLinePath + "/temp.xml")) + { + log.WriteLogFile("未找到temp.xml文件", "WindowViewErrorlog"); + } + } + catch (Exception ex) + { + log.WriteLogFile(ex.ToString(), "WindowViewErrorlog"); + } + } + [DllImport("kernel32.dll", EntryPoint = "SetProcessWorkingSetSize")] + public static extern int SetProcessWorkingSetSize(IntPtr process, int minSize, int maxSize); + + + + /// + /// 开始播放 + /// + private void StartPlay() + { + isStop = false; + //app.view = this; + //Thread.Sleep(1000); + GetUControl(); + stackPanelAD.Children.Clear(); + MyUc.Width = mainp.Width; + MyUc.Height = mainp.Height; + Color color = (Color)ColorConverter.ConvertFromString("Black"); + MyUc.Background = new SolidColorBrush(color); + this.Background = new SolidColorBrush(color); + this.main.Background = new SolidColorBrush(color); + try + { + + + if (th1 == null) + { + th1 = new Thread(new ThreadStart(() => + { + + while (!isStop)//停止播放 + { + try + { + if (app.isSendSync) + { + Thread.Sleep(1000); + continue; + } + if (isMedia)//正在播放视频 + { + Thread.Sleep(1000); + continue; + } + if (ImageShowTime > 1) + { + + ImageShowTime--; + Thread.Sleep(1000); + continue; + } + //播放完后重新获取最新屏保 + if (app.currentIndex >= ucList.Count || app.currentIndex < 0) + { + this.Dispatcher.Invoke(new Action(() => + { + GetUControl(); + })); + app.currentIndex = 0; + } + if (app.isProgramSync && !app.isProgramServer) + { + Thread.Sleep(1000); + continue; + } + //if (app.currentIndex == ucList.Count) + //{ + // app.currentIndex = 0; + //} + this.stackPanelAD.Dispatcher.Invoke(new Action(delegate + { + this.stackPanelAD.Children.Clear(); + })); + + if (ucList.Count > 0) + { + + if (app.isProgramServer) + { + SendPlay(); + } + else if (!app.isProgramSync) + { + Play(); + } + + } + else + { + Thread.Sleep(10000); + } + } + catch (Exception ex) + { + log.WriteLogFile(ex.ToString(), "WindowViewErrorlog"); + } + } + + + })); + //app.view.WindowState = WindowState.Maximized; + } + th1.IsBackground = true; + th1.Start(); + } + catch (Exception ex) + { + + log.WriteLogFile(ex.ToString(), "WindowViewErrorlog"); + } + } + + private void SendPlay() + { + app.isSendSync = true; + try + { + WebsocketForProgramServer.allSockets.ToList().ForEach(s => s.Send(ucList[app.currentIndex].Item3.code)); + } + catch (Exception e) + { + + log.WriteLogFile(e.ToString(), "StartPlayerror"); + } + + } + + private void Play() + { + try + { + + + this.stackPanelAD.Dispatcher.Invoke(new Action(delegate + { + this.stackPanelAD.Children.Clear(); + })); + log.WriteLogFile(app.currentIndex.ToString(), "currentIndexlog"); + log.WriteLogFile(ucList.Count.ToString()+"-----", "currentIndexlog"); + if (ucList[app.currentIndex].Item4 == false)//如果是播放的图片 + { + if (isplay) + { + isplay = false; + vlc_player_.Stop(); + VCDTimer.Stop(); + } + + this.Dispatcher.Invoke(new Action(() => + { + try + { + string fileExtension = System.IO.Path.GetExtension(ucList[app.currentIndex].Item3.img).ToLower(); + if (fileExtension == ".gif") + { + GifImageLib.GifImage gifImage = new GifImageLib.GifImage(); + gifImage.Width = mainp.Width; + gifImage.Height = mainp.Height; + gifImage.Source = ucList[app.currentIndex].Item3.img; + string ScreenMatch = ucList[app.currentIndex].Item3.screenmatch; + if (!string.IsNullOrEmpty(ScreenMatch)) + { + if (ScreenMatch.Trim().Equals("拉伸")) + { + gifImage.Stretch = Stretch.Fill; + } + else if (ScreenMatch.Trim().Equals("适应")) + { + gifImage.Stretch = Stretch.Uniform; + } + else if (ScreenMatch.Trim().Equals("填充")) + { + gifImage.Stretch = Stretch.UniformToFill; + } + else if (ScreenMatch.Trim().Equals("居中")) + { + gifImage.Stretch = Stretch.None; + } + else + { + gifImage.Stretch = Stretch.Uniform; + } + } + mainp.Transition = ucList[app.currentIndex].Item2; + mainp.Content = gifImage; + } + else + { + mainp.Transition = ucList[app.currentIndex].Item2; + mainp.Content = ucList[app.currentIndex].Item1; + } + app.isSendSync = false; + isMedia = false; + ImageShowTime = Convert.ToInt32(ucList[app.currentIndex].Item3.time); + app.currentIndex++; + if (isSysProg) + { + var ucNews = ucNewsList.Where(i => Convert.ToDateTime(i.Item3.launchtime) < DateTime.Now.AddSeconds(ImageShowTime) && Convert.ToDateTime(i.Item3.expirydate) > DateTime.Now.AddSeconds(ImageShowTime)).ToList(); + if (ucNews.Count > 0) + { + ucList = ucNews; + app.currentIndex = 0; + isSysProg = false; + } + else + { + log.WriteRecordToFile(ucList[app.currentIndex - 1].Item3.code, ucList[app.currentIndex - 1].Item3.time); + } + } + //var curIndex = app.currentIndex - 1; + //if (!string.IsNullOrEmpty(ucList[curIndex].Item3.shopName)) + //{ + // //log.WriteLogFile(Convert.ToDouble(ucList[curIndex].Item3.angle).ToString(), "socket"); + // //RichAD richAD = new RichAD(((SystemParameters.PrimaryScreenWidth > SystemParameters.PrimaryScreenHeight) ? SystemParameters.PrimaryScreenWidth / 2 : SystemParameters.PrimaryScreenWidth), 420 * percentHeight, ucList[curIndex].Item3.logoPath, ucList[curIndex].Item3.shopName, ucList[curIndex].Item3.floorName, Convert.ToDouble(ucList[curIndex].Item3.angle), percentHeight); + // RichAD richAD = new RichAD( ucList[curIndex].Item3.logoPath, ucList[curIndex].Item3.shopName, ucList[curIndex].Item3.devNum, ucList[curIndex].Item3.floorName, ucList[curIndex].Item3.floorOrder, ucList[curIndex].Item3.houseNum, ucList[curIndex].Item3.xaxis, ucList[curIndex].Item3.shopFormatName, ucList[curIndex].Item3.shopFormatIcon, ucList[curIndex].Item3.applets); + // DoubleAnimation heightAnimation = new DoubleAnimation(0, 620 , new Duration(TimeSpan.FromSeconds(1))); + // richAD.BeginAnimation(Border.HeightProperty, heightAnimation, HandoffBehavior.Compose); + // this.stackPanelAD.Children.Insert(0, richAD); + //} + + } + catch { } + })); + + //try + //{ + // SetProcessWorkingSetSize(Process.GetCurrentProcess().Handle, -1, -1); + // GC.Collect(); + //} + //catch { } + //Thread.Sleep(Convert.ToInt32(ucList[app.currentIndex - 1].Item3.time) * 1000); + } + else//如果是播放的视频 + { + this.Dispatcher.Invoke(new Action(() => + { + try + { + //mainp.Transition = ucList[app.currentIndex].Item2; + mainp.Content = MyUc; + + if (!isplay) + { + isplay = false; + var hwndSource = (System.Windows.Interop.HwndSource)PresentationSource.FromDependencyObject(main); + IntPtr render_wnd = hwndSource.Handle; + vlc_player_.SetRenderWindow((int)render_wnd); + } + if (ucList[app.currentIndex].Item3.img.StartsWith("http:")) + vlc_player_.PlayStream(ucList[app.currentIndex].Item3.img); + else + vlc_player_.PlayFile(ucList[app.currentIndex].Item3.img); + duration = (int)vlc_player_.Duration(); + app.isSendSync = false; + log.WriteLogFile(ucList[app.currentIndex].Item3.img + " " + duration.ToString(), "duration"); + currentTime = 0; + ImageShowTime = 0; + VCDTimer.Start(); + app.currentIndex++; + isMedia = true; + isplay = true; + if (isSysProg) + { + var ucNews = ucNewsList.Where(i => Convert.ToDateTime(i.Item3.launchtime) < DateTime.Now.AddSeconds(duration) && Convert.ToDateTime(i.Item3.expirydate) > DateTime.Now.AddSeconds(duration)).ToList(); + if (ucNews.Count > 0) + { + ucList = ucNews; + app.currentIndex = 0; + isSysProg = false; + } + else + { + log.WriteRecordToFile(ucList[app.currentIndex - 1].Item3.code, ucList[app.currentIndex - 1].Item3.time); + } + } + //var curIndex = app.currentIndex - 1; + //if (!string.IsNullOrEmpty(ucList[curIndex].Item3.shopName)) + //{ + // log.WriteLogFile(Convert.ToDouble(ucList[curIndex].Item3.angle).ToString(), "socket"); + // RichAD richAD = new RichAD(((SystemParameters.PrimaryScreenWidth > SystemParameters.PrimaryScreenHeight) ? SystemParameters.PrimaryScreenWidth / 2 : SystemParameters.PrimaryScreenWidth), 420 * percentHeight, ucList[curIndex].Item3.logoPath, ucList[curIndex].Item3.shopName, ucList[curIndex].Item3.floorName, Convert.ToDouble(ucList[curIndex].Item3.angle), percentHeight); + // DoubleAnimation heightAnimation = new DoubleAnimation(0, 460 * percentHeight, new Duration(TimeSpan.FromSeconds(1))); + // richAD.BeginAnimation(Border.HeightProperty, heightAnimation, HandoffBehavior.Compose); + // this.stackPanelAD.Children.Insert(0, richAD); + //} + } + catch (Exception ex) + { + log.WriteLogFile(ex.ToString(), "WindowViewErrorlog"); + } + })); + //Thread.Sleep(Convert.ToInt32(ucList[app.currentIndex-1].Item3.time) * 1000);// + } + + } + catch (Exception e) + { + + log.WriteLogFile(e.ToString(), "currentIndexlog"); + } + } + + private void this_MouseClickDown(object sender, System.Windows.Forms.MouseEventArgs e) + { + try + { + + if (e.Button == System.Windows.Forms.MouseButtons.Left) //|| e.Button == System.Windows.Forms.MouseButtons.Right + { + //点击翻页 + //Point p = new Point(e.Location.X, e.Location.Y); + //if (p.X < this.Width / 2) + //{ + // app.currentIndex -= 2; + // while (app.currentIndex < 0) + // { + // app.currentIndex = ucList.Count + app.currentIndex; + // } + //} + //if (isMedia) + //{ + // isMedia = false; + // SetProcessWorkingSetSize(Process.GetCurrentProcess().Handle, -1, -1); + //} + //else + //{ + // ImageShowTime = 0; + //} + + //------------------ + //点击关闭 + Point p = new Point(e.Location.X, e.Location.Y); + Points.Add(p); + if (Points.Count == 5) + Points.Remove(Points[0]); + if (Points.Count > 4) + Points.Clear(); + else if (Points.Count == 4 && p.X < 100 && p.Y > this.Height - 100) + { + p = (Point)Points[2]; + if (p.X < 100 && p.Y > this.Height - 100) + { + p = (Point)Points[1]; + if (p.X < 100 && p.Y > this.Height - 100) + { + p = (Point)Points[0]; + if (p.X < 100 && p.Y > this.Height - 100) + { + this.Close(); + } + } + } + } + //------------------ + } + //Mouse.OverrideCursor = Cursors.Arrow; + } + catch (Exception ex) + { + Class_Log log = new Class_Log(); + log.WriteLogFile("记录鼠标位置异常" + ex.ToString(), "MainWindowErrorLog"); + + } + } + + private void WebSocketManage_WebSocketReceiveEvent(string type, string message) + { + try + { + if (type == "relay")//开始下载 + { + this.stackPanel1.Dispatcher.Invoke( + new Action( + delegate + { + if (this.stackPanel1.Children.Count >= 3) + { + stackPanel1.Children.RemoveAt(2); + navDateList.RemoveAt(0); + if (navDateList.Count == 0) + { + NavTimer.Stop(); + } + + } + if (navDateList.Count == 0) + { + NavTimer.Start(); + } + NavGuide ucimg = new NavGuide(SystemParameters.PrimaryScreenWidth-1, 440, app.navModel.LogoPath, app.navModel.ShopName, string.IsNullOrEmpty(app.navModel.FloorName) ? "距离您还有" + app.navModel.Distance + "m" : ("店铺位于" + app.navModel.FloorName), app.navModel.Angle); + DoubleAnimation heightAnimation = new DoubleAnimation(0, 440, new Duration(TimeSpan.FromSeconds(1))); + ucimg.BeginAnimation(Border.HeightProperty, heightAnimation, HandoffBehavior.Compose); + stackPanel1.Children.Insert(0, ucimg); + navDateList.Add(DateTime.Now); + } + )); + } + if (type == "richad")//开始下载 + { + this.stackPanelAD.Dispatcher.InvokeAsync( + new Action( + delegate + { + try + { + + + log.WriteLogFile(this.stackPanelAD.Children.Count.ToString(), "socket"); + //判断发送的数据的类型 + if (this.stackPanelAD.Children.Count <= 0) + { + var curIndex = app.currentIndex > 0 ? app.currentIndex - 1 : 0; + if (!string.IsNullOrEmpty(ucList[curIndex].Item3.shopName)) + { + //log.WriteLogFile(Convert.ToDouble(ucList[curIndex].Item3.angle).ToString(), "socket"); + //RichAD richAD = new RichAD(((SystemParameters.PrimaryScreenWidth > SystemParameters.PrimaryScreenHeight) ? SystemParameters.PrimaryScreenWidth / 2 : SystemParameters.PrimaryScreenWidth), 420 * percentHeight, ucList[curIndex].Item3.logoPath, ucList[curIndex].Item3.shopName, ucList[curIndex].Item3.floorName, Convert.ToDouble(ucList[curIndex].Item3.angle), percentHeight); + //log.WriteLogFile(Convert.ToDouble(ucList[curIndex].Item3.angle).ToString(), "socket"); + RichAD richAD = new RichAD(ucList[curIndex].Item3.logoPath, ucList[curIndex].Item3.shopName, ucList[curIndex].Item3.devNum, ucList[curIndex].Item3.floorName, ucList[curIndex].Item3.floorOrder, ucList[curIndex].Item3.houseNum, ucList[curIndex].Item3.xaxis, ucList[curIndex].Item3.shopFormatName, ucList[curIndex].Item3.shopFormatIcon, ucList[curIndex].Item3.applets); + DoubleAnimation heightAnimation = new DoubleAnimation(0, 620, new Duration(TimeSpan.FromSeconds(1))); + richAD.BeginAnimation(Border.HeightProperty, heightAnimation, HandoffBehavior.Compose); + this.stackPanelAD.Children.Insert(0, richAD); + if (!isMedia) + { + ImageShowTime = Convert.ToInt32(ucList[curIndex].Item3.time); + } + } + } + } + catch (Exception ex) + { + log.WriteLogFile(ex.Message, "richaderror"); + } + + }) + + ); + } + else if (type == "syndata") + { + this.Dispatcher.Invoke(new Action(() => + { + GetUControl(); + })); + } + else if (type == "play") + { + + //this.Dispatcher.Invoke(new Action(() => + //{ + List imageList = ucList.Select(i => i.Item3.code).ToList(); + var imageIndex = imageList.IndexOf(message); + //log.WriteLogFile(message, "play"); + //log.WriteLogFile(imageIndex.ToString(), "play"); + //if (imageIndex < 0) + //{ + // imageList = ucListSys.Select(i => i.Item3.code).ToList(); + // imageIndex = imageList.IndexOf(message); + //} + if (imageIndex >= 0) + { + app.currentIndex = imageIndex; + currentTime = 0; + ImageShowTime = 0; + isMedia = false; + if (isplay) + { + isplay = false; + vlc_player_.Stop(); + VCDTimer.Stop(); + } + //app.isSendSync = false; + Play(); + } + else + { + app.currentIndex = app.currentIndex > 0 ? app.currentIndex - 1 : 0; + //app.isSendSync = false; + Play(); + + } + // })); + } + } + catch (Exception ex) + { + log.WriteLogFile(ex.ToString(), "errorsocket"); + } + + } + + public void openSocket() + { + IPAddress ip = IPAddress.Parse("127.0.0.1"); + clentSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); + clentSocket.Connect(ip, 9001); + + //开启一个新的线程不停的接收服务器发送消息的线程 + threadReceive = new Thread(new ThreadStart(Receive)); + //设置为后台线程 + threadReceive.IsBackground = true; + threadReceive.Start(); + } + + /// + /// 接口服务器发送的消息 + /// + private void Receive() + { + try + { + while (true) + { + byte[] buffer = new byte[2048]; + //实际接收到的字节数 + int r = clentSocket.Receive(buffer); + if (r == 0) + { + break; + } + else + { + this.stackPanelAD.Dispatcher.InvokeAsync( + new Action( + delegate + { + try + { + + + log.WriteLogFile(this.stackPanelAD.Children.Count.ToString(), "socket"); + //判断发送的数据的类型 + if (this.stackPanelAD.Children.Count <= 0) + { + var curIndex = app.currentIndex - 1; + if (!string.IsNullOrEmpty(ucList[curIndex].Item3.shopName)) + { + //log.WriteLogFile(Convert.ToDouble(ucList[curIndex].Item3.angle).ToString(), "socket"); + //RichAD richAD = new RichAD(((SystemParameters.PrimaryScreenWidth > SystemParameters.PrimaryScreenHeight) ? SystemParameters.PrimaryScreenWidth / 2 : SystemParameters.PrimaryScreenWidth), 420 * percentHeight, ucList[curIndex].Item3.logoPath, ucList[curIndex].Item3.shopName, ucList[curIndex].Item3.floorName, Convert.ToDouble(ucList[curIndex].Item3.angle), percentHeight); + RichAD richAD = new RichAD(ucList[curIndex].Item3.logoPath, ucList[curIndex].Item3.shopName, ucList[curIndex].Item3.devNum, ucList[curIndex].Item3.floorName, ucList[curIndex].Item3.floorOrder, ucList[curIndex].Item3.houseNum, ucList[curIndex].Item3.xaxis, ucList[curIndex].Item3.shopFormatName, ucList[curIndex].Item3.shopFormatIcon, ucList[curIndex].Item3.applets); + DoubleAnimation heightAnimation = new DoubleAnimation(0, 620, new Duration(TimeSpan.FromSeconds(1))); + richAD.BeginAnimation(Border.HeightProperty, heightAnimation, HandoffBehavior.Compose); + this.stackPanelAD.Children.Insert(0, richAD); + } + } + } + catch (Exception ex) + { + log.WriteLogFile(app.currentIndex.ToString(), "123"); + log.WriteLogFile(ex.Message, "123"); + } + + }) + + ); + } + + + } + } + catch (Exception ex) + { + log.WriteLogFile("-------" + ex.Message, "socket"); + } + } + + + private void LoadPics(int type) + { + try + { + Storyboard _storyboard = new Storyboard(); + int count = 99; + if (type < 3) + { + count = 68; + } + for (int i = 0; i < count; i++) + { + ObjectAnimationUsingKeyFrames oauf = new ObjectAnimationUsingKeyFrames(); + //ObjectAnimationUsingKeyFrames 可以对指定 Duration 内的一组 KeyFrames 中的 Object 属性值进行动画处理 + BitmapImage bitmap = new BitmapImage(); + bitmap.BeginInit(); + string name = i.ToString().PadLeft(5, '0'); + bitmap.UriSource = new Uri("pack://application:,,,/Container;component/touch/touch" + type + "/touch_" + name + ".png"); + log.WriteLogFile(bitmap.UriSource.AbsolutePath, "file"); + bitmap.CacheOption = BitmapCacheOption.Default; + bitmap.EndInit(); + + ImageBrush imgBrush = new ImageBrush(bitmap); + //读取图片文件 + DiscreteObjectKeyFrame dokf = new DiscreteObjectKeyFrame(); + //DiscreteObjectKeyFrame 通过使用离散内插,可以在前一个关键帧的 Object 值及其自己的 Value 之间进行动画处理。 + dokf.KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromMilliseconds(i * 30)); + //KeyTime 获取或设置应到达关键帧的目标 Value 的时间 + //这里每隔40毫秒设置一张图片,也就是每秒1000/40=25帧 + dokf.Value = imgBrush; + oauf.KeyFrames.Add(dokf); + Storyboard.SetTargetProperty(oauf, new PropertyPath("(Rectangle.Fill)")); + //把动画应用到窗体的Rectangle中 + Storyboard.SetTarget(oauf, RectDis); + //RectDis是Rectangle的名称 + _storyboard.Children.Add(oauf); + //把ObjectAnimationUsingKeyFrames动画添加到Storyboard中 + } + _storyboard.RepeatBehavior = RepeatBehavior.Forever; + _storyboard.Begin(); + } + catch (Exception ex) + { + + log.WriteLogFile(ex.Message, "error"); + } + } + + + private void LoadGif() + { + endX = _canvas.Width - gridmove.Width; + Random ran = new Random(); + endY = ran.Next(0, Convert.ToInt32(_canvas.Height - gridmove.Height)); ; + ss(); + //if (app.screensaver.ScreenEffect == 1 && app.screensaver.EffectType == 0) + //{ + // endX = 0; + // endX = _canvas.Width - gridmove.Width; + // beginY = (_canvas.Height - gridmove.Height) / 2; + // endY = (_canvas.Height - gridmove.Height) / 2; + //} + //else { + // endX = _canvas.Width - gridmove.Width; + // Random ran = new Random(); + // endY = ran.Next(0, Convert.ToInt32(_canvas.Height - gridmove.Height)); ; + //} + //ss(); + } + + void ss_Completed(object sender, EventArgs e) + { + Random ran = new Random(); + beginX = endX; + beginY = endY; + if (app.screensaver.EffectType == 1) + { + if (endX >= _canvas.Width - gridmove.Width) + { + if (endY >= (_canvas.Height - gridmove.Width) / 2) + { + endX = ran.Next(0, Convert.ToInt32((_canvas.Width - gridmove.Width) / 2)); + endY = _canvas.Height - gridmove.Height; + } + else + { + endX = ran.Next(0, Convert.ToInt32((_canvas.Width - gridmove.Width) / 2)); + endY = 0; + } + } + else if (endX == 0) + { + if (endY >= (_canvas.Height - gridmove.Height) / 2) + { + endX = ran.Next(Convert.ToInt32((_canvas.Width - gridmove.Width) / 2), Convert.ToInt32(_canvas.Width - gridmove.Width)); + endY = 0; + + } + else + { + endX = ran.Next(Convert.ToInt32((_canvas.Width - gridmove.Width) / 2), Convert.ToInt32(_canvas.Width - gridmove.Width)); + endY = _canvas.Height - gridmove.Height; + } + } + else + + if (endY == _canvas.Height - gridmove.Height) + { + if (endX >= (_canvas.Width - gridmove.Width) / 2) + { + endY = ran.Next(0, Convert.ToInt32((_canvas.Height - gridmove.Height) / 2)); + endX = _canvas.Width - gridmove.Width; + } + else + { + endY = ran.Next(0, Convert.ToInt32((_canvas.Height - gridmove.Height) / 2)); + endX = 0; + } + } + else if (endY == 0) + { + if (endX >= (_canvas.Width - gridmove.Width) / 2) + { + endY = ran.Next(Convert.ToInt32((_canvas.Height - gridmove.Height) / 2), Convert.ToInt32(_canvas.Height - gridmove.Height)); + + endX = _canvas.Width - gridmove.Width; + } + else + { + endY = ran.Next(Convert.ToInt32((_canvas.Height - gridmove.Height) / 2), Convert.ToInt32(_canvas.Height - gridmove.Height)); + + endX = 0; + } + } + } + else + { + if (beginX == 0) + { + endX = _canvas.Width - gridmove.Width; + } + else + { + endX = 0; + } + } + ss(); + } + + void ss() + { + var x = endX - beginX; + var y = endY - beginY; + var z = Math.Sqrt(x * x + y * y); + var time = z / 200; + DoubleAnimation DAnimation = new DoubleAnimation(); + DAnimation.From = beginX;//起点 + DAnimation.To = endX;//终点 + DAnimation.Duration = new Duration(TimeSpan.FromSeconds(time));//时间 + + Storyboard.SetTarget(DAnimation, gridmove); + Storyboard.SetTargetProperty(DAnimation, new PropertyPath(Canvas.LeftProperty)); + + Storyboard story = new Storyboard(); + story.Completed += new EventHandler(ss_Completed);//完成后要做的事 + //story.RepeatBehavior = RepeatBehavior.Forever;//无限次循环,需要的自己加上 + if (app.screensaver.EffectType == 1) + { + DoubleAnimation DAnimation1 = new DoubleAnimation(); + DAnimation1.From = beginY;//起点 + DAnimation1.To = endY;//终点 + DAnimation1.Duration = new Duration(TimeSpan.FromSeconds(time));//时间 + Storyboard.SetTarget(DAnimation1, gridmove); + Storyboard.SetTargetProperty(DAnimation1, new PropertyPath(Canvas.TopProperty)); + story.Children.Add(DAnimation1); + } + story.Children.Add(DAnimation); + + story.Begin(); + } + } +} diff --git a/Container/Win/WindowViewNew.xaml b/Container/Win/WindowViewNew.xaml new file mode 100644 index 0000000..a48ba2a --- /dev/null +++ b/Container/Win/WindowViewNew.xaml @@ -0,0 +1,55 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Container/Win/WindowViewNew.xaml.cs b/Container/Win/WindowViewNew.xaml.cs new file mode 100644 index 0000000..11e9137 --- /dev/null +++ b/Container/Win/WindowViewNew.xaml.cs @@ -0,0 +1,2090 @@ +using Container.Business; +using Container.Common; +using Container.Model; +using Container.Services; +using Newtonsoft.Json; +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Net.Sockets; +using System.Reflection; +using System.Runtime.InteropServices; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Data; +using System.Windows.Documents; +using System.Windows.Input; +using System.Windows.Interop; +using System.Windows.Media; +using System.Windows.Media.Animation; +using System.Windows.Media.Imaging; +using System.Windows.Shapes; +using System.Windows.Threading; +using Transitionals; + +namespace Container.Win +{ + /// + /// WindowViewNew.xaml 的交互逻辑 + /// + public partial class WindowViewNew : Window + { + double beginX = 0; + double endX = 0; + double beginY = 0; + double endY = 0; + //bool isSysProg = true; + //DispatcherTimer VCDTimer = new DispatcherTimer();//停止播放视频的定时器 + //DispatcherTimer GCTimer = new DispatcherTimer(); + //DispatcherTimer ProgramSyncTimer = new DispatcherTimer();//停止播放视频的定时器 + + //private List> ucListSys = new List>();//记录最新的屏保列表 + //private List> ucNewsList = new List>(); //记录插播列表 + //private List> ucList = new List>(); //记录插播列表 + private DateTime? curLoadDate; + DispatcherTimer LoadScreenTimer = new DispatcherTimer();//隔天加载节目 + DispatcherTimer LoadProgIsSync = new DispatcherTimer();//隔天加载节目 + PlayBackManage pbm; + //private int duration = 0;//视频总时长; + //int currentTime = 0; + //int ImageShowTime = 0; + App app = ((App)Application.Current); + Class_Log log = new Class_Log(); + //UserControl MyUc = new UserControl(); + //bool isplay = false; + //public bool isclose = false; + //public bool Mainclose = false; + MouseHook mh = new MouseHook(); + // WebSocketManage web = new WebSocketManage(); + //private List navDateList = new List(); + //WebSocketForFaceManage webForFace = new WebSocketForFaceManage(); + //WebSocketForProgram webForProgram = new WebSocketForProgram(); + JService jService = new JService(); + private double percentHeight = 1; + int isShowCountDown = 0; + List videoList = new List(); + /// + /// 鼠标位置数组 + /// + ArrayList Points = new ArrayList();// + IntPtr hWaitTimer = IntPtr.Zero; + //ProgControl progControl = new ProgControl(); + List sourceList = new List(); + //public ObservableCollection ItemsList { get; set; } = new ObservableCollection(); + string outLinePath; + bool IsPlayEnd = false; + DateTime? PlayEndTime = null; + DirectoryInfo vlcLibDirectory; + int curPlayIndex = 0; + UCImageText ucimg = new UCImageText(); + string ScreenMatch = "拉伸"; + //string ScreenMatch = "适应"; + Stretch stretch = Stretch.Fill; + // Stretch stretch = Stretch.Uniform; + List cancellationTokens = new List(); + public WindowViewNew(int type = 1) + { + InitializeComponent(); + isShowCountDown = type; + this.Width = app.ScreenWidth; + this.Height = app.ScreenHeight; + outLinePath = AppDomain.CurrentDomain.BaseDirectory + "/OutlineFiles"; + pbm = new PlayBackManage(); + mh.SetHook(); + mh.MouseClickEvent += this_MouseClickDown; + + try + { + //Application.ExecutablePathSystem.Windows.Forms.Application.ExecutablePath.Replace("\\", "/").Substring(0, System.Windows.Forms.Application.ExecutablePath.Replace("\\", "/").LastIndexOf("/")) + string strImages = System.Environment.CurrentDirectory + "\\pic\\bg.png";//AppDomain.CurrentDomain.BaseDirectory + "pic\\common\\bg.png"; + if (File.Exists(strImages) == true) + { + Uri uri = new Uri(strImages, UriKind.Absolute); + ImageBrush ib = new ImageBrush(); + ib.ImageSource = new BitmapImage(uri); + this.waiting.Background = ib; + } + + } + catch (Exception ex) + { + log.WriteLogFile(ex.ToString(), "WindowViewErrorlog"); + } + } + + private void MediaPlayer_EndReached(object sender, Vlc.DotNet.Core.VlcMediaPlayerEndReachedEventArgs e) + { + //Task.Factory.StartNew(() => { + // //this.sourceProvider = null; + // Application.Current.Dispatcher.BeginInvoke(new Action(() => { + // mainVideo.SourceProvider.MediaPlayer.Play(vlcVideoPath); + // })); + //}); + + + if (app.isProgramServer) + { + log.WriteLogFile("发送", "发送"); + SendPlay(curPlayIndex); + if (!app.isProgramSync) + { + PlayProg(); + } + //PlayEnd(media1, media, curIndex); + + } + else if (!app.isProgramSync) + { + PlayProg(); + } + + + //PlayProg(); + + } + //private void MediaPlayer1_EndReached(object sender, Vlc.DotNet.Core.VlcMediaPlayerEndReachedEventArgs e) + //{ + // //Task.Factory.StartNew(() => { + // // //this.sourceProvider = null; + // // Application.Current.Dispatcher.BeginInvoke(new Action(() => { + // // mainVideo.SourceProvider.MediaPlayer.Play(vlcVideoPath); + // // })); + // //}); + + + // if (app.isProgramServer) + // { + // log.WriteLogFile("发送", "发送"); + // SendPlay(curPlayIndex); + // //PlayEnd(media1, media, curIndex); + + // } + // else if (!app.isProgramSync) + // { + // PlayProg(); + // } + + + // //PlayProg(); + + //} + + ///// + ///// 修改系统分辨率 + ///// + ///// 分辨率,单位为毫秒 + ///// 返回值 + //[DllImport("winmm.dll")] + //public static extern uint timeBeginPeriod(int t); + + ///// + ///// 恢复系统分辨率 + ///// + ///// 分辨率,单位为毫秒 + ///// 返回值 + //[DllImport("winmm.dll")] + //public static extern uint timeEndPeriod(int t); + + private void LoadScreen(object sender, EventArgs e) + { + try + { + jService.GetSyncDev(); + } + catch (Exception ex) + { + log.WriteLogFile(ex.Message, "error"); + } + if (curLoadDate.HasValue && curLoadDate.Value.Date != DateTime.Now.Date) + { + foreach (var item in sourceList) + { + if (!item.Token.IsCancellationRequested) + { + item.Cancel(); + item.Dispose(); + //item.Dispose(); + } + } + curLoadDate = DateTime.Now; + sourceList.Clear(); + pbm.DownResource(); + //Action action = new Action(() => { + GetUControl(); + //}); + //action.BeginInvoke(null, null); + } + + } + + private void LoadPics() + { + try + { + Storyboard _storyboard = new Storyboard(); + for (int i = 0; i < 220; i++) + { + + ObjectAnimationUsingKeyFrames oauf = new ObjectAnimationUsingKeyFrames(); + //ObjectAnimationUsingKeyFrames 可以对指定 Duration 内的一组 KeyFrames 中的 Object 属性值进行动画处理 + BitmapImage bitmap = new BitmapImage(); + bitmap.BeginInit(); + string name = i.ToString().PadLeft(5, '0'); + bitmap.UriSource = new Uri("pack://application:,,,/Container;component/image/CountDowmImage/倒计时透明度_" + name + ".png"); + bitmap.CacheOption = BitmapCacheOption.Default; + bitmap.EndInit(); + bitmap.Freeze(); + ImageBrush imgBrush = new ImageBrush(bitmap); + //读取图片文件 + DiscreteObjectKeyFrame dokf = new DiscreteObjectKeyFrame(); + //DiscreteObjectKeyFrame 通过使用离散内插,可以在前一个关键帧的 Object 值及其自己的 Value 之间进行动画处理。 + dokf.KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromMilliseconds(i * 30)); + //KeyTime 获取或设置应到达关键帧的目标 Value 的时间 + //这里每隔40毫秒设置一张图片,也就是每秒1000/40=25帧 + dokf.Value = imgBrush; + imgBrush.Freeze(); + oauf.KeyFrames.Add(dokf); + dokf.Freeze(); + Storyboard.SetTargetProperty(oauf, new PropertyPath("(Rectangle.Fill)")); + //把动画应用到窗体的Rectangle中 + Storyboard.SetTarget(oauf, RectDisImage); + //RectDis是Rectangle的名称 + _storyboard.Children.Add(oauf); + oauf.Freeze(); + //把ObjectAnimationUsingKeyFrames动画添加到Storyboard中 + } + _storyboard.Completed += new EventHandler(time_Completed); + //_storyboard.RepeatBehavior = RepeatBehavior.Forever; + _storyboard.Begin(); + _storyboard.Freeze(); + + } + catch (Exception ex) + { + + log.WriteLogFile(ex.Message, "error"); + } + } + + void time_Completed(object sender, EventArgs e) + { + timeGrid.Visibility = Visibility.Hidden; + gridMain.Visibility = Visibility.Visible; + LoadData(); + } + + private void LoadData() + { + try + { + //timeBeginPeriod(1); + this.EventsRegistion(); // 注册事件 + this.LoadScreenTimer.Interval = TimeSpan.FromMinutes(1); //垃圾释放定时器 我定为每十分钟释放一次,大家可根据需要修改 + this.LoadProgIsSync.Interval = TimeSpan.FromSeconds(5); + this.LoadScreenTimer.Start(); + this.LoadProgIsSync.Start(); + + pbm.DownResource(); + WebSocketForProgram.WebSocketReceiveEvent += new WebSocketForProgram.WebSocketReceiveDelegate(WebSocketManage_WebSocketReceiveEvent); + JService.ScreenConfigReceiveEvent += new JService.ScreenConfigDelegate(ScreenConfig_ReceiveEvent); + //this.GCTimer.Interval = TimeSpan.FromMinutes(30); //垃圾释放定时器 我定为每十分钟释放一次,大家可根据需要修改 + //this.GCTimer.Start(); + Action action = new Action(() => + { + jService.GetSyncDev(); + jService.SetPlayRecord(); + }); + action.BeginInvoke(null, null); + + RectDis.Dispatcher.Invoke(() => + { + if (app.screensaver.ScreenType == 0 || (app.AppList.Count == 0 && string.IsNullOrEmpty(app.configstartexe))) + { + _canvas.Visibility = Visibility.Hidden; + } + else if (app.screensaver.ScreenType < 5) + { + _canvas.Visibility = Visibility.Visible; + RectDis.Visibility = Visibility.Visible; + gridImage.Visibility = Visibility.Hidden; + LoadPics(app.screensaver.ScreenType); + } + else if (!string.IsNullOrEmpty(app.screensaver.ScreenFile)) + { + + string fileExtension = System.IO.Path.GetExtension(app.screensaver.ScreenFile); + if (fileExtension.ToLower() == ".gif") + { + _canvas.Visibility = Visibility.Visible; + RectDis.Visibility = Visibility.Hidden; + gridImage.Visibility = Visibility.Hidden; + GifImageLib.GifImage image = new GifImageLib.GifImage(); + image.Source = app.screensaver.ScreenFile; + image.Width = 300; + image.Height = 300; + image.Background = new SolidColorBrush(Colors.Transparent); + gridmove.Children.Add(image); + } + else + { + _canvas.Visibility = Visibility.Visible; + RectDis.Visibility = Visibility.Hidden; + gridImage.Visibility = Visibility.Visible; + Uri uri = new Uri(app.screensaver.ScreenFile, UriKind.Absolute); + gridImage.Source = new BitmapImage(uri); + } + } + if (app.screensaver.ScreenEffect == 1) + { + LoadGif(); + if (app.screensaver.EffectType == 0) + { + gridmove.Margin = new Thickness(0, (_canvas.Height - gridmove.Height) / 2, 0, (_canvas.Height - gridmove.Height) / 2); + } + + } + else + { + if (app.screensaver.EffectType == 0) + { + gridmove.Margin = new Thickness((_canvas.Width - gridmove.Width), (_canvas.Height - gridmove.Height), 0, 0); + } + else + { + gridmove.Margin = new Thickness((_canvas.Width - gridmove.Width) / 2, (_canvas.Height - gridmove.Height) / 2, (_canvas.Width - gridmove.Width) / 2, (_canvas.Height - gridmove.Height) / 2); + } + } + }); + StartPlay(); + } + catch (Exception e) + { + log.WriteLogFile(e.ToString(), "WindowViewErrorlog"); + } + } + + private void WindowView_Load(object sender, RoutedEventArgs e) + { + //try + //{ + // var hwndSource = PresentationSource.FromVisual(this) as HwndSource; + // var hwndTarget = hwndSource.CompositionTarget; + // hwndTarget.RenderMode = RenderMode.SoftwareOnly; + //} + //catch (Exception ex) + //{ + // log.WriteLogFile(ex.ToString(), "WinView"); + //} + + try + { + //LoadScoket(); + this.Width = app.ScreenWidth; + this.Height = app.ScreenHeight; + percentHeight = app.ScreenHeight / 3840; + tbMessage.FontSize = 30 * percentHeight; + _canvas.Height = 2000 * percentHeight; + _canvas.Width = app.ScreenWidth; + gridmove.Width = app.ScreenWidth > 1920 ? 600 : 300; + gridmove.Height = app.ScreenWidth > 1920 ? 600 : 300; + gridImage.Width = app.ScreenWidth > 1920 ? 600 : 300; + gridImage.Height = app.ScreenWidth > 1920 ? 600 : 300; + RectDis.Width = app.ScreenWidth > 1920 ? 600 : 300; + RectDis.Height = app.ScreenWidth > 1920 ? 600 : 300; + mainp.Width = app.ScreenWidth; + mainp.Height = app.ScreenHeight; + //mainVideo.Width = app.ScreenWidth; + //mainVideo.Height = app.ScreenHeight; + //mainVideo1.Width = app.ScreenWidth; + //mainVideo1.Height = app.ScreenHeight; + gifPlay.Width = app.ScreenWidth; + gifPlay.Height = app.ScreenHeight; + mainVideo.Width = app.ScreenWidth; + mainVideo.Height = app.ScreenHeight; + ShowCursor(0); + + + if (isShowCountDown == 1) + { + LoadPics(); + } + else + { + timeGrid.Visibility = Visibility.Hidden; + gridMain.Visibility = Visibility.Visible; + LoadData(); + } + + + } + catch (Exception ex) + { + log.WriteLogFile(ex.ToString(), "WindowViewErrorlog"); + } + + } + + private void ScreenConfig_ReceiveEvent() + { + try + { + log.WriteLogFile("进来了", "screenconfig1"); + foreach (var item in sourceList) + { + if (!item.Token.IsCancellationRequested) + { + item.Cancel(); + item.Dispose(); + } + } + sourceList.Clear(); + GetUControl(); + + } + catch (Exception e) + { + log.WriteLogFile(e.ToString(), "error"); + } + + } + + + [DllImport("user32.dll", EntryPoint = "ShowCursor", CharSet = CharSet.Auto)] + public static extern void ShowCursor(int status); + + //void OnGarbageCollection(object sender, EventArgs e) + //{ + // GC.Collect(); + // GC.WaitForPendingFinalizers(); + // GC.Collect(); + //} + + public void EventsRegistion() + { + this.LoadScreenTimer.Tick += new EventHandler(LoadScreen); + this.LoadProgIsSync.Tick += new EventHandler(LoadProgSync); + //this.GCTimer.Tick += new EventHandler(OnGarbageCollection); + } + + public void LoadProgSync(object sender, EventArgs e) + { + //if (IsPlayEnd && PlayEndTime.HasValue && PlayEndTime.Value.AddSeconds(3) < DateTime.Now) + //{ + // media.Dispatcher.Invoke(new Action(() => + // { + // int curIndex = 0; + // int zindex = Canvas.GetZIndex(media); + // if (zindex == 1) + // { + // List hashList = videoList.Select(i => i.fileHash).ToList(); + // string curUrl = media.Source.ToString(); + // string curHash = curUrl.Substring(curUrl.LastIndexOf("/") + 1, curUrl.LastIndexOf(".") - curUrl.LastIndexOf("/") - 1); + // if (videoList.Count > 1) + // { + // curIndex = hashList.ToList().IndexOf(curHash); + // if (curIndex + 2 >= videoList.Count) + // { + // curIndex = curIndex + 2 - videoList.Count; + // } + // else + // { + // curIndex = curIndex + 2; + // } + // } + // PlayEnd(media1, media, curIndex); + // } + // else + // { + // List hashList = videoList.Select(i => i.fileHash).ToList(); + // string curUrl = media1.Source.ToString(); + // string curHash = curUrl.Substring(curUrl.LastIndexOf("/") + 1, curUrl.LastIndexOf(".") - curUrl.LastIndexOf("/") - 1); + // if (videoList.Count > 1) + // { + // curIndex = hashList.ToList().IndexOf(curHash); + // if (curIndex + 2 >= videoList.Count) + // { + // curIndex = curIndex + 2 - videoList.Count; + // } + // else + // { + // curIndex = curIndex + 2; + // } + // } + // PlayEnd(media, media1, curIndex); + // } + // })); + //} + } + + + + private void WindowView_Closing(object sender, System.ComponentModel.CancelEventArgs e) + { + try + { + + log.WriteLogFile("进入关闭屏保" + DateTime.Now.TimeOfDay.ToString(), "closewin"); + //timeEndPeriod(1); + if (hWaitTimer != IntPtr.Zero) + { + CloseHandle(hWaitTimer); + hWaitTimer = IntPtr.Zero; + } + log.WriteLogFile("进入关闭屏保1" + DateTime.Now.TimeOfDay.ToString(), "closewin"); + if (app.isProgramServer) + { + app.websocketForProgramServer.CloasSocket(); + app.websocketForProgramServer = null; + app.isProgramServer = false; + app.websocketProgramIP = ""; + } + log.WriteLogFile("进入关闭屏保2" + DateTime.Now.TimeOfDay.ToString(), "closewin"); + if (app.isProgramSync) + { + app.webSocketForProgram.CloseWebSocket(); + app.webSocketForProgram = null; + app.isProgramSync = false; + app.websocketProgramIP = ""; + } + log.WriteLogFile("进入关闭屏保3" + DateTime.Now.TimeOfDay.ToString(), "closewin"); + //progControl.Dispose(); + foreach (var item in sourceList) + { + if (!item.Token.IsCancellationRequested) + { + item.Cancel(); + item.Dispose(); + //item.Dispose(); + } + } + log.WriteLogFile("进入关闭屏保4" + DateTime.Now.TimeOfDay.ToString(), "closewin"); + sourceList.Clear(); + StopVideo(); + log.WriteLogFile("进入关闭屏保5" + DateTime.Now.TimeOfDay.ToString(), "closewin"); + foreach (var item in mainVideo.Children) + { + var mediaClear = (MediaElement)item; + mediaClear.Stop(); + mediaClear.Close(); + + } + mainVideo.Children.Clear(); + log.WriteLogFile("进入关闭屏保6" + DateTime.Now.TimeOfDay.ToString(), "closewin"); + FulshMemor(); + //if (GCTimer != null) + // GCTimer.Stop(); + if (LoadScreenTimer != null) + LoadScreenTimer.Stop(); + log.WriteLogFile("进入关闭屏保7" + DateTime.Now.TimeOfDay.ToString(), "closewin"); + mh.UnHook(); + log.WriteLogFile("关闭屏保" + DateTime.Now.TimeOfDay.ToString(), "closewin"); + //webForFace.CloseWebSocket(); + } + catch (Exception ex) + { + log.WriteLogFile("--------" + ex.ToString(), "WindowViewErrorlog"); + } + try + { + + } + catch (Exception ex) + { + log.WriteLogFile(ex.ToString(), "WindowViewErrorlog"); + } + } + + public void FulshMemor() + { + try + { + //SetProcessWorkingSetSize(Process.GetCurrentProcess().Handle, -1, -1); + //GC.Collect(); + //Mouse.OverrideCursor = Cursors.None; + } + catch { } + } + + [DllImport("kernel32.dll")] + public static extern IntPtr CreateWaitableTimer(IntPtr lpTimerAttributes, bool bManualReset, IntPtr lpTimerName); + + + [DllImport("kernel32.dll")] + public static extern bool SetWaitableTimer(IntPtr hTimer, ref long pDueTime, + long lPeriod, int pfnCompletionRoutine, // TimerCompleteDelegate + int lpArgToCompletionRoutine, bool fResume); + + + [DllImport("user32.dll")] + public static extern UInt32 MsgWaitForMultipleObjects(uint nCount, ref IntPtr pHandles, + bool bWaitAll, int dwMilliseconds, uint dwWakeMask); + + + [DllImport("Kernel32.dll")] + public static extern UInt32 WaitForSingleObject(IntPtr pHandles, int dwMilliseconds); + + [DllImport("kernel32.dll")] + public static extern bool CloseHandle(IntPtr hObject); + + + public const int NULL = 0; + public const int QS_TIMER = 0x10; + + public void UsDelay(long us) + { + long duetime = -1 * us; + if (hWaitTimer != IntPtr.Zero) + { + CloseHandle(hWaitTimer); + hWaitTimer = IntPtr.Zero; + } + if (hWaitTimer == IntPtr.Zero) + { + hWaitTimer = CreateWaitableTimer(IntPtr.Zero, true, IntPtr.Zero); + bool flag = SetWaitableTimer(hWaitTimer, ref duetime, 0, NULL, NULL, false); + UInt32 isFlag = WaitForSingleObject(hWaitTimer, Timeout.Infinite); + } + } + /// + /// 根据获取到的信息生成UseControl + /// + private void GetUControl() + { + try + { + FulshMemor(); + List result = pbm.GetResource(); + if (result == null || result.Count == 0) + { + + this.Dispatcher.Invoke(new Action(() => + { + //if (media.CanPause) + // media.Pause(); + //if (media1.CanPause) + // media1.Pause(); + //foreach (var item in mainp.Children) + //{ + // var mediaClear = (MediaElement)item; + // mediaClear.Stop(); + // mediaClear.Close(); + + //} + //mainp.Children.Clear(); + foreach (var item in sourceList) + { + if (!item.Token.IsCancellationRequested) + { + item.Cancel(); + item.Dispose(); + //item.Dispose(); + } + } + sourceList.Clear(); + foreach (var item in mainVideo.Children) + { + var mediaClear = (MediaElement)item; + mediaClear.Stop(); + mediaClear.Close(); + + } + mainVideo.Children.Clear(); + //progControl.Dispose(); + StopVideo(); + mainp.Visibility = Visibility.Hidden; + waiting.Visibility = Visibility.Visible; + })); + return; + } + else + { + this.Dispatcher.Invoke(new Action(() => + { + foreach (var item in sourceList) + { + if (!item.Token.IsCancellationRequested) + { + item.Cancel(); + item.Dispose(); + //item.Dispose(); + } + } + sourceList.Clear(); + foreach (var item in mainVideo.Children) + { + var mediaClear = (MediaElement)item; + mediaClear.Stop(); + mediaClear.Close(); + + } + mainVideo.Children.Clear(); + StopVideo(); + mainp.Visibility = Visibility.Visible; + waiting.Visibility = Visibility.Hidden; + })); + } + if (hWaitTimer != IntPtr.Zero) + { + CloseHandle(hWaitTimer); + hWaitTimer = IntPtr.Zero; + } + LoadScheduler(result); + + } + catch (Exception ex) + { + log.WriteLogFile(ex.ToString(), "WindowViewErrorlog"); + } + } + [DllImport("kernel32.dll", EntryPoint = "SetProcessWorkingSetSize")] + public static extern int SetProcessWorkingSetSize(IntPtr process, int minSize, int maxSize); + + private bool LoadScheduler(List progList) + { + bool isScheduler = false; + if (hWaitTimer != IntPtr.Zero) + { + CloseHandle(hWaitTimer); + hWaitTimer = IntPtr.Zero; + } + try + { + progList = progList.Where(i => Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd") + " " + i.endTime) > DateTime.Now).OrderBy(i => i.beginTime).ToList(); + if (progList != null && progList.Count > 0) + { + if (Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd") + " " + progList[0].beginTime) <= DateTime.Now) + { + PlayScheduler(progList[0]); + Action action = new Action(() => + { + var curDate = DateTime.Now; + var stopTime = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd") + " " + progList[0].endTime); + UsDelay((stopTime.Ticks - curDate.Ticks)); + if (hWaitTimer != IntPtr.Zero) + { + CloseHandle(hWaitTimer); + hWaitTimer = IntPtr.Zero; + } + LoadScheduler(progList); + }); + action.BeginInvoke(null, null); + } + else + { + app.currentIndex = -1; + Action action = new Action(() => + { + var curDate = DateTime.Now; + var stopTime = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd") + " " + progList[0].beginTime); + UsDelay((stopTime.Ticks - curDate.Ticks)); + if (hWaitTimer != IntPtr.Zero) + { + CloseHandle(hWaitTimer); + hWaitTimer = IntPtr.Zero; + } + PlayScheduler(progList[0]); + Action action1 = new Action(() => + { + curDate = DateTime.Now; + stopTime = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd") + " " + progList[0].endTime); + if (hWaitTimer != IntPtr.Zero) + { + CloseHandle(hWaitTimer); + hWaitTimer = IntPtr.Zero; + } + curDate = DateTime.Now; + UsDelay((stopTime.Ticks - curDate.Ticks)); + + LoadScheduler(progList); + }); + action1.BeginInvoke(null, null); + }); + action.BeginInvoke(null, null); + this.Dispatcher.Invoke(new Action(() => + { + //if(media.CanPause) + //media.Pause(); + //if (media1.CanPause) + // media1.Pause(); + //foreach (var item in mainp.Children) + //{ + // var mediaClear = (MediaElement)item; + // mediaClear.Stop(); + // mediaClear.Close(); + + //} + //mainp.Children.Clear(); + //progControl.Dispose(); + foreach (var item in sourceList) + { + if (!item.Token.IsCancellationRequested) + { + item.Cancel(); + item.Dispose(); + //item.Dispose(); + } + } + sourceList.Clear(); + foreach (var item in mainVideo.Children) + { + var mediaClear = (MediaElement)item; + mediaClear.Stop(); + mediaClear.Close(); + + } + mainVideo.Children.Clear(); + StopVideo(); + mainp.Visibility = Visibility.Hidden; + waiting.Visibility = Visibility.Visible; + })); + } + + } + else + { + this.Dispatcher.Invoke(new Action(() => + { + foreach (var item in sourceList) + { + if (!item.Token.IsCancellationRequested) + { + item.Cancel(); + item.Dispose(); + } + } + sourceList.Clear(); + //if (media.CanPause) + // media.Pause(); + //if (media1.CanPause) + // media1.Pause(); + foreach (var item in mainVideo.Children) + { + var mediaClear = (MediaElement)item; + mediaClear.Stop(); + mediaClear.Close(); + + } + mainVideo.Children.Clear(); + StopVideo(); + //progControl.Dispose(); + mainp.Visibility = Visibility.Hidden; + waiting.Visibility = Visibility.Visible; + })); + } + } + catch (Exception e) + { + + log.WriteLogFile(e.ToString()); + } + return isScheduler; + } + + //private async void PlayScheduler(ProgModel scheduler) + //{ + // try + // { + + // //Task tsk1 = factory.StartNew(() => + // //{ + // foreach (var item in sourceList) + // { + // if (!item.Token.IsCancellationRequested) + // { + // item.Cancel(); + // item.Dispose(); + // } + // } + // sourceList.Clear(); + // Transition transition = CommonMethod.GetTransition("渐入"); + // if (scheduler != null && scheduler.programs != null && scheduler.programs.Count > 0) + // { + // this.Dispatcher.Invoke(new Action(() => + // { + // mainp.Visibility = Visibility.Visible; + // waiting.Visibility = Visibility.Hidden; + // })); + // var playIndex = 0; + // CancellationTokenSource source1 = new CancellationTokenSource(); + // sourceList.Add(source1); + // while (true) + // { + // if (source1.Token.IsCancellationRequested) + // { + // //isStop = true; + // // 释放资源操作等等... + // break; + // } + // //if (!curDate.HasValue || curDate.Value.AddMilliseconds(duration) <= DateTime.Now) + // //{ + // var item = scheduler.programs[playIndex]; + // this.Dispatcher.Invoke(new Action(() => + // { + // progControl.Dispose(); + // progControl.LoadProg(this.Width, this.Height, item.backgroundMaterialInfo, item.backgroundColor, item.components); + + // mainp.Content = progControl; + // playIndex++; + // if (playIndex >= scheduler.programs.Count) + // { + // playIndex = 0; + + // } + // })); + // TimeSpan.TryParse(item.duration, out TimeSpan timeSpan); + // if (source1.Token.IsCancellationRequested) + // { + // break; + // } + // else + // { + // try + // { + // await Task.Delay(Convert.ToInt32(timeSpan.TotalMilliseconds), source1.Token); + // } + // catch (Exception) + // { + + // break; + // } + // } + + // //await Task.Delay(Convert.ToInt32(timeSpan.TotalMilliseconds), source1.Token); + // //} + // //else + // //{ + // // Task.Delay(10,token); + // //} + // } + // } + // else + // { + // this.Dispatcher.Invoke(new Action(() => + // { + // mainp.Visibility = Visibility.Hidden; + // waiting.Visibility = Visibility.Visible; + // })); + // } + + // //}); + + // } + // catch (Exception e) + // { + + // log.WriteLogFile(e.ToString()); + // } + + //} + + + private async void PlayScheduler(ProgModel scheduler) + { + try + { + + //Task tsk1 = factory.StartNew(() => + //{ + log.WriteLogFile(JsonConvert.SerializeObject(scheduler), "22222"); + try + { + foreach (var item in sourceList) + { + if (!item.Token.IsCancellationRequested) + { + item.Cancel(); + item.Dispose(); + } + } + sourceList.Clear(); + log.WriteLogFile("取消定时", "token"); + } + catch (Exception e) + { + log.WriteLogFile(e.ToString(), "PlaySchedulerError"); + } + if (scheduler != null && scheduler.programs != null && scheduler.programs.Count > 0) + { + this.Dispatcher.Invoke(new Action(() => + { + mainp.Visibility = Visibility.Visible; + waiting.Visibility = Visibility.Hidden; + })); + //var videoList= scheduler.programs.Where(i=>i.components.).Select(i=>i.components) + List videoNow = new List(); + string backCorlor = string.Empty; + foreach (var item in scheduler.programs) + { + var videoProg = item.components.Where(i => i.typeCode == "video" || i.typeCode == "image").OrderBy(i => i.zIndex).ToList(); + foreach (var itemVideo in videoProg) + { + videoNow.AddRange(itemVideo.materials.OrderBy(i => i.order).Select(i => new + PlayMaterial + { + duration = i.duration, + fileHash = i.fileHash, + fileUrl = i.fileUrl, + materialCode = i.materialCode, + name = i.name, + order = i.order, + mediaInfo = i.mediaInfo, + config = itemVideo.config, + typeCode = itemVideo.typeCode + }).ToList()); + } + if (string.IsNullOrEmpty(item.backgroundColor)) + { + backCorlor = item.backgroundColor; + } + } + if (!string.IsNullOrEmpty(backCorlor)) + { + Color color = (Color)ColorConverter.ConvertFromString(backCorlor); + mainp.Background = new SolidColorBrush(color); + } + videoList.Clear(); + videoList.AddRange(videoNow); + if (videoList.Count > 0) + { + log.WriteLogFile("进入", "222"); + this.Dispatcher.Invoke(new Action(() => + { + //if (media.CanPause) + //{ + // media.Pause(); + //} + //if (media1.CanPause) + //{ + // media1.Pause(); + //} + foreach (var item in mainVideo.Children) + { + var mediaClear = (MediaElement)item; + mediaClear.Stop(); + mediaClear.Close(); + + } + mainVideo.Children.Clear(); + StopVideo(); + curPlayIndex = 0; + + + PlayProg(); + //if (app.isProgramServer) + //{ + // log.WriteLogFile("发送", "发送"); + // SendPlay(curPlayIndex); + // //PlayEnd(media1, media, curIndex); + + //} + //else if (!app.isProgramSync) + //{ + // PlayProg(); + //} + //mainVideo.SourceProvider.MediaPlayer.Pause(); + mainp.Visibility = Visibility.Visible; + waiting.Visibility = Visibility.Hidden; + })); + } + else + { + + this.Dispatcher.Invoke(new Action(() => + { + foreach (var item in mainVideo.Children) + { + var mediaClear = (MediaElement)item; + mediaClear.Stop(); + mediaClear.Close(); + + } + mainVideo.Children.Clear(); + StopVideo(); + //mainVideo.SourceProvider.MediaPlayer.Pause(); + curPlayIndex = 0; + //PlayProg(); + mainp.Visibility = Visibility.Hidden; + waiting.Visibility = Visibility.Visible; + })); + } + } + else + { + this.Dispatcher.Invoke(new Action(() => + { + foreach (var item in mainVideo.Children) + { + var mediaClear = (MediaElement)item; + mediaClear.Stop(); + mediaClear.Close(); + + } + mainVideo.Children.Clear(); + + mainp.Visibility = Visibility.Hidden; + waiting.Visibility = Visibility.Visible; + })); + } + + //}); + + } + catch (Exception e) + { + + log.WriteLogFile(e.ToString()); + } + + } + + private void PlayProg() + { + try + { + if (videoList.Count == 0) + { + log.WriteLogFile("进来了", "token"); + return; + } + if (curPlayIndex >= videoList.Count) + { + curPlayIndex = 0; + } + Transition transition = CommonMethod.GetTransition("渐入"); + string fileExtension = string.Empty; + string url = string.Empty; + foreach (var item in sourceList) + { + if (!item.Token.IsCancellationRequested) + { + item.Cancel(); + item.Dispose(); + } + } + sourceList.Clear(); + if (videoList[curPlayIndex].fileUrl.Contains("?")) + { + fileExtension = videoList[curPlayIndex].fileUrl.Substring(videoList[curPlayIndex].fileUrl.LastIndexOf("."), videoList[curPlayIndex].fileUrl.LastIndexOf("?") - videoList[curPlayIndex].fileUrl.LastIndexOf(".")).ToLower(); + } + else + { + fileExtension = videoList[curPlayIndex].fileUrl.Substring(videoList[curPlayIndex].fileUrl.LastIndexOf(".")).ToLower(); + } + url = outLinePath + "/Main/" + videoList[curPlayIndex].fileHash + fileExtension; + log.WriteLogFile(url, "file"); + var ext = fileExtension.ToLower().Split('.').Last(); + FileTypeJudgment fvdo = new FileTypeJudgment() { TypeTarget = new TypeVideo() }; + log.WriteLogFile(fileExtension.ToLower(), "file"); + log.WriteLogFile(fvdo.Judge(ext).ToString(), "file"); + if (fvdo.Judge(ext)) + { + StartVideo(url, videoList[curPlayIndex].fileHash); + } + else + { + if (mainVideo.Visibility == Visibility.Visible) + { + + this.Dispatcher.Invoke(() => + { + mainVideo.Visibility = Visibility.Hidden; + }); + } + PlayImage(videoList[curPlayIndex], url); + + } + + + } + catch (Exception e) + { + log.WriteLogFile("---" + e.ToString(), "333"); + + if (e.ToString().Contains("指定的参数已超出有效值的范围")) + { + this.Dispatcher.Invoke(() => + { + app.main.WinView = this; + }); + } + else + { + ScreenConfig_ReceiveEvent(); + } + //await Task.Delay(new TimeSpan(0,0,0,1)); + //Thread.Sleep(1000); + //PlayProg(); + + } + } + + private async void StartVideo(string videoPath, string fileHash) + { + try + { + this.Dispatcher.Invoke(() => + { + mainImage.Visibility = Visibility.Hidden; + }); + + + + if (mainVideo.Visibility == Visibility.Hidden) + { + this.Dispatcher.Invoke(() => + { + mainVideo.Visibility = Visibility.Visible; + }); + } + + mainVideo.Dispatcher.Invoke(() => + { + mainVideo.Children.Clear(); + + MediaElement media = new MediaElement(); + //media.Dispatcher.Invoke(new Action(() => + //{ + + media.LoadedBehavior = MediaState.Manual; + media.Stretch = stretch; + media.Width = app.ScreenWidth; + media.Height = app.ScreenHeight; + media.Source = new Uri(videoPath); + media.MediaEnded += media_MediaEnded; + media.Play(); + mainVideo.Children.Add(media); + }); + + } + catch (Exception e) + { + + log.WriteLogFile(e.ToString(), "videoError"); + } + //try + //{ + + // Task.Factory.StartNew(() => { + // if (mainVideo.Visibility == Visibility.Visible) { + // mainVideo.SourceProvider.MediaPlayer.Pause(); + // mainVideo1.SourceProvider.MediaPlayer.Play(new Uri(videoPath)); + // } else { + // if (mainVideo1.Visibility == Visibility.Visible) + // { + // mainVideo1.SourceProvider.MediaPlayer.Pause(); + // } + // mainVideo.SourceProvider.MediaPlayer.Play(new Uri(videoPath)); + // } + + // }); + //} + //catch (Exception ex) + //{ + // log.WriteLogFile(videoPath + ex.ToString(), "StopVideoError"); + //} + } + + + + private void seeyou(MediaElement mep) + { + //bool isseeyou = true; + //double allTime = 0; + //int index = curPlayIndex; + //string x = ""; + //string y = ""; + //string isseeyous = mep?.Position.ToString(); + //log.WriteLogFile("开始时长" + isseeyous, "seeyou"); + //int t = 0; + //Task ta = new Task(() => + //{ + // while (isseeyou && index == curPlayIndex) + // { + // try + // { + // Thread.Sleep(1000); + + // if (string.IsNullOrEmpty(x)) + // { + // Thread.Sleep(1000); + + + // try + // { + // this.Dispatcher.Invoke(() => + // { + // if (mep.NaturalDuration.HasTimeSpan) + // { + // x = mep?.NaturalDuration.TimeSpan.ToString(); + // allTime = mep.NaturalDuration.TimeSpan.TotalSeconds; + // log.WriteLogFile("总时长秒:" + allTime, "seeyou"); + // } + // } + // ); + // log.WriteLogFile("总时长:" + x, "seeyou"); + // } + // catch (Exception ex) + // { + // log.WriteLogFile(ex.ToString(), "seeyou"); + // } + + // } + + // this.Dispatcher.Invoke(() => + // { + // try + // { + // y = mep?.Position.ToString(); + // } + // catch (Exception ex) + // { + // y = y + "0"; + // log.WriteLogFile(ex.ToString(), "seeyou"); + // } + + // }); + + + // if (isseeyous.Equals(y)) + // { + // log.WriteLogFile("没在播" + Environment.NewLine + isseeyous + Environment.NewLine + y, "seeyou"); + // t++; + // } + // else + // { + // if (t != 0) + // { + // t = 0; + // } + // log.WriteLogFile("正常播呢", "seeyous"); + // isseeyous = y; + // } + + // //C#中的TimeSpan.Compare()方法用于比较两个TimeSpan值,并返回一个整数,该整数指示第一个值是小于,等于还是大于第二个值。 + + // //如果span1小于span2,则返回值为 - 1;如果span1 = span2,则返回值为0;如果span1大于span2,则返回值为1。 + // try + // { + // log.WriteLogFile(mep.Position.TotalSeconds.ToString(), "CountTe"); + // } + // catch (Exception ex) + // { + // log.WriteLogFile(ex.ToString(), "seeyou"); + // } + // if (!string.IsNullOrEmpty(x) && !(allTime > mep.Position.TotalSeconds)) + // { + // log.WriteLogFile("播完了", "seeyous"); + // isseeyou = false; ; + // } + + + // if (t > 2 && isseeyou && curPlayIndex == index && !string.IsNullOrEmpty(x)) + // { + // isseeyou = false; + // log.WriteLogFile("异常了,准备关了重开" + Environment.NewLine + x + Environment.NewLine + y, "seeyouErr"); + // this.Dispatcher.Invoke(() => + // { + // app.main.WinView = this; + // }); + // } + // } + // catch (Exception ex) + // { + // log.WriteLogFile(ex.ToString(), "seeyou"); + // } + // } + //}); + //ta.Start(); + } + + private void StopVideo() + { + //try + //{ + // //myControl.SourceProvider.MediaPlayer.Pause(); + // //this.myControl.Dispose(); + // if (mainVideo.SourceProvider.MediaPlayer.IsPlaying()) { + // mainVideo.SourceProvider.MediaPlayer.Pause(); + // } + // if (mainVideo1.SourceProvider.MediaPlayer.IsPlaying()) + // { + // mainVideo1.SourceProvider.MediaPlayer.Pause(); + // } + + + //} + //catch (Exception e) + //{ + + // //log.WriteLogFile(videoUrl + e.ToString(), "StopVideoError"); + //} + } + + private void PlayImage(PlayMaterial material, string url) + { + try + { + log.WriteLogFile("播放111", "file"); + + CancellationTokenSource source1 = new CancellationTokenSource(); + sourceList.Add(source1); + CancellationToken token = source1.Token; + TaskFactory factory = new TaskFactory(token); + Task tsk1 = factory.StartNew(async () => + { + log.WriteLogFile("播放12222", "file"); + try + { + + + var transitionPeriod = material.config.Value("transitionPeriod"); + var transition = material.config.Value("transition"); + string fileExtension = string.Empty; + if (fileExtension.ToLower() == ".gif") + { + GC.Collect(); + mainImage.Dispatcher.Invoke(new Action(() => + { + FileStream s = new FileStream(url, FileMode.Open, FileAccess.Read); + // XamlAnimatedGif.AnimationBehavior.SetSourceUri(gifPlay, new Uri(outLinePath + "/Main/" + ucList[app.currentIndex].sourceId + fileExtension)); + + XamlAnimatedGif.AnimationBehavior.SetSourceStream(gifPlay, s); + XamlAnimatedGif.AnimationBehavior.SetRepeatBehavior(gifPlay, RepeatBehavior.Forever); + XamlAnimatedGif.AnimationBehavior.SetAutoStart(gifPlay, true); + gifPlay.Visibility = Visibility.Visible; + mainImage.Visibility = Visibility.Hidden; + mainVideo.Visibility = Visibility.Hidden; + //mainVideo1.Visibility = Visibility.Hidden; + })); + } + else + { + mainImage.Dispatcher.Invoke(new Action(() => + { + ucimg.LoadData(this.Width, this.Height, url, "", ScreenMatch); + + mainImage.Content = ucimg; + mainVideo.Visibility = Visibility.Hidden; + // mainVideo1.Visibility = Visibility.Hidden; + gifPlay.Visibility = Visibility.Hidden; + mainImage.Visibility = Visibility.Visible; + log.WriteLogFile("播放", "file"); + })); + } + await Task.Delay(transitionPeriod * 1000, token); + log.WriteLogFile(token.IsCancellationRequested.ToString(), "token"); + + if (!token.IsCancellationRequested) + { + + + if (app.isProgramServer) + { + log.WriteLogFile("发送", "发送"); + curPlayIndex++; + SendPlay(curPlayIndex); + if (!app.isProgramSync) + { + PlayProg(); + } + //PlayEnd(media1, media, curIndex); + + } + else if (!app.isProgramSync) + { + curPlayIndex++; + PlayProg(); + } + } + + } + catch (Exception e) + { + + log.WriteLogFile("---" + e.ToString(), "fileerror"); + } + }); + } + catch (Exception e) + { + + log.WriteLogFile(e.ToString(), "fileerror"); + } + } + + private void BindImage(Image image, string img, string transition) + { + Action action = new Action(() => + { + image.Dispatcher.Invoke(new Action(() => + { + if (img.ToLower().EndsWith(".gif")) + { + //FileStream stream = new FileStream(img, FileMode.Open, FileAccess.Read); + //XamlAnimatedGif.AnimationBehavior.SetSourceStream(image, stream); + //FileStream s = new FileStream(outLinePath + "/Main/" + ucList[app.currentIndex].sourceId + fileExtension, FileMode.Open, FileAccess.Read); + XamlAnimatedGif.AnimationBehavior.SetSourceUri(image, new Uri(img)); + XamlAnimatedGif.AnimationBehavior.SetRepeatBehavior(image, RepeatBehavior.Forever); + XamlAnimatedGif.AnimationBehavior.SetAutoStart(image, true); + } + else + { + image.Source = new BitmapImage(new Uri(img)); + } + })); + }); + action.BeginInvoke(null, null); + } + + + + /// + /// 开始播放 + /// + private void StartPlay() + { + curLoadDate = DateTime.Now; + GetUControl(); + + } + + + private void this_MouseClickDown(object sender, System.Windows.Forms.MouseEventArgs e) + { + try + { + + if (e.Button == System.Windows.Forms.MouseButtons.Left) //|| e.Button == System.Windows.Forms.MouseButtons.Right + { + //点击翻页 + //Point p = new Point(e.Location.X, e.Location.Y); + //if (p.X < this.Width / 2) + //{ + // app.currentIndex -= 2; + // while (app.currentIndex < 0) + // { + // app.currentIndex = ucList.Count + app.currentIndex; + // } + //} + //if (isMedia) + //{ + // isMedia = false; + // SetProcessWorkingSetSize(Process.GetCurrentProcess().Handle, -1, -1); + //} + //else + //{ + // ImageShowTime = 0; + //} + + //------------------ + //点击关闭 + Point p = new Point(e.Location.X, e.Location.Y); + Points.Add(p); + if (Points.Count == 5) + Points.Remove(Points[0]); + if (Points.Count > 4) + Points.Clear(); + else if (Points.Count == 4 && p.X < 100 && p.Y > this.Height - 100) + { + p = (Point)Points[2]; + if (p.X < 100 && p.Y > this.Height - 100) + { + p = (Point)Points[1]; + if (p.X < 100 && p.Y > this.Height - 100) + { + p = (Point)Points[0]; + if (p.X < 100 && p.Y > this.Height - 100) + { + this.Close(); + } + } + } + } + //------------------ + } + //Mouse.OverrideCursor = Cursors.Arrow; + } + catch (Exception ex) + { + Class_Log log = new Class_Log(); + log.WriteLogFile("记录鼠标位置异常" + ex.ToString(), "MainWindowErrorLog"); + + } + } + + private void LoadPics(int type) + { + try + { + Storyboard _storyboard = new Storyboard(); + int count = 99; + if (type < 3) + { + count = 68; + } + for (int i = 0; i < count; i++) + { + ObjectAnimationUsingKeyFrames oauf = new ObjectAnimationUsingKeyFrames(); + //ObjectAnimationUsingKeyFrames 可以对指定 Duration 内的一组 KeyFrames 中的 Object 属性值进行动画处理 + BitmapImage bitmap = new BitmapImage(); + bitmap.BeginInit(); + string name = i.ToString().PadLeft(5, '0'); + bitmap.UriSource = new Uri("pack://application:,,,/Container;component/touch/touch" + type + "/touch_" + name + ".png"); + log.WriteLogFile(bitmap.UriSource.AbsolutePath, "file"); + bitmap.CacheOption = BitmapCacheOption.Default; + bitmap.EndInit(); + bitmap.Freeze(); + ImageBrush imgBrush = new ImageBrush(bitmap); + //读取图片文件 + DiscreteObjectKeyFrame dokf = new DiscreteObjectKeyFrame(); + //DiscreteObjectKeyFrame 通过使用离散内插,可以在前一个关键帧的 Object 值及其自己的 Value 之间进行动画处理。 + dokf.KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromMilliseconds(i * 30)); + //KeyTime 获取或设置应到达关键帧的目标 Value 的时间 + //这里每隔40毫秒设置一张图片,也就是每秒1000/40=25帧 + dokf.Value = imgBrush; + imgBrush.Freeze(); + oauf.KeyFrames.Add(dokf); + dokf.Freeze(); + Storyboard.SetTargetProperty(oauf, new PropertyPath("(Rectangle.Fill)")); + //把动画应用到窗体的Rectangle中 + Storyboard.SetTarget(oauf, RectDis); + //RectDis是Rectangle的名称 + _storyboard.Children.Add(oauf); + oauf.Freeze(); + //把ObjectAnimationUsingKeyFrames动画添加到Storyboard中 + } + _storyboard.RepeatBehavior = RepeatBehavior.Forever; + _storyboard.Begin(); + _storyboard.Freeze(); + } + catch (Exception ex) + { + + log.WriteLogFile(ex.Message, "error"); + } + } + + + private void LoadGif() + { + endX = _canvas.Width - gridmove.Width; + Random ran = new Random(); + endY = ran.Next(0, Convert.ToInt32(_canvas.Height - gridmove.Height)); ; + ss(); + } + + void ss_Completed(object sender, EventArgs e) + { + Random ran = new Random(); + beginX = endX; + beginY = endY; + if (app.screensaver.EffectType == 1) + { + if (endX >= _canvas.Width - gridmove.Width) + { + if (endY >= (_canvas.Height - gridmove.Width) / 2) + { + endX = ran.Next(0, Convert.ToInt32((_canvas.Width - gridmove.Width) / 2)); + endY = _canvas.Height - gridmove.Height; + } + else + { + endX = ran.Next(0, Convert.ToInt32((_canvas.Width - gridmove.Width) / 2)); + endY = 0; + } + } + else if (endX == 0) + { + if (endY >= (_canvas.Height - gridmove.Height) / 2) + { + endX = ran.Next(Convert.ToInt32((_canvas.Width - gridmove.Width) / 2), Convert.ToInt32(_canvas.Width - gridmove.Width)); + endY = 0; + + } + else + { + endX = ran.Next(Convert.ToInt32((_canvas.Width - gridmove.Width) / 2), Convert.ToInt32(_canvas.Width - gridmove.Width)); + endY = _canvas.Height - gridmove.Height; + } + } + else + + if (endY == _canvas.Height - gridmove.Height) + { + if (endX >= (_canvas.Width - gridmove.Width) / 2) + { + endY = ran.Next(0, Convert.ToInt32((_canvas.Height - gridmove.Height) / 2)); + endX = _canvas.Width - gridmove.Width; + } + else + { + endY = ran.Next(0, Convert.ToInt32((_canvas.Height - gridmove.Height) / 2)); + endX = 0; + } + } + else if (endY == 0) + { + if (endX >= (_canvas.Width - gridmove.Width) / 2) + { + endY = ran.Next(Convert.ToInt32((_canvas.Height - gridmove.Height) / 2), Convert.ToInt32(_canvas.Height - gridmove.Height)); + + endX = _canvas.Width - gridmove.Width; + } + else + { + endY = ran.Next(Convert.ToInt32((_canvas.Height - gridmove.Height) / 2), Convert.ToInt32(_canvas.Height - gridmove.Height)); + + endX = 0; + } + } + } + else + { + if (beginX == 0) + { + endX = _canvas.Width - gridmove.Width; + } + else + { + endX = 0; + } + } + ss(); + } + + void ss() + { + var x = endX - beginX; + var y = endY - beginY; + var z = Math.Sqrt(x * x + y * y); + var time = z / 200; + DoubleAnimation DAnimation = new DoubleAnimation(); + DAnimation.From = beginX;//起点 + DAnimation.To = endX;//终点 + DAnimation.Duration = new Duration(TimeSpan.FromSeconds(time));//时间 + + Storyboard.SetTarget(DAnimation, gridmove); + Storyboard.SetTargetProperty(DAnimation, new PropertyPath(Canvas.LeftProperty)); + + Storyboard story = new Storyboard(); + story.Completed += new EventHandler(ss_Completed);//完成后要做的事 + //story.RepeatBehavior = RepeatBehavior.Forever;//无限次循环,需要的自己加上 + if (app.screensaver.EffectType == 1) + { + DoubleAnimation DAnimation1 = new DoubleAnimation(); + DAnimation1.From = beginY;//起点 + DAnimation1.To = endY;//终点 + DAnimation1.Duration = new Duration(TimeSpan.FromSeconds(time));//时间 + Storyboard.SetTarget(DAnimation1, gridmove); + Storyboard.SetTargetProperty(DAnimation1, new PropertyPath(Canvas.TopProperty)); + story.Children.Add(DAnimation1); + } + story.Children.Add(DAnimation); + DAnimation.Freeze(); + story.Begin(); + story.Freeze(); + } + + private void media_MediaEnded(object sender, RoutedEventArgs e) + { + //MediaElement media = (MediaElement)sender; + //int curIndex = 0; + //List hashList = videoList.Select(i => i.fileHash).ToList(); + //string curUrl = media.Source.ToString(); + //string curHash = curUrl.Substring(curUrl.LastIndexOf("/") + 1, curUrl.LastIndexOf(".") - curUrl.LastIndexOf("/") - 1); + //if (videoList.Count > 1) + //{ + // curIndex = hashList.ToList().IndexOf(curHash); + // if (curIndex + 2 >= videoList.Count) + // { + // curIndex = curIndex + 2 - videoList.Count; + // } + // else + // { + // curIndex = curIndex + 2; + // } + //} + + if (app.isProgramServer) + { + curPlayIndex++; + log.WriteLogFile("发送", "发送"); + SendPlay(curPlayIndex); + if (!app.isProgramSync) + { + PlayProg(); + } + //PlayEnd(media1, media, curIndex); + + } + else if (!app.isProgramSync) + { + curPlayIndex++; + PlayProg(); + // PlayEnd((MediaElement)mainp.Children[mainp.Children.Count-1], (MediaElement)mainp.Children[mainp.Children.Count - 2], curIndex); + } + else + { + IsPlayEnd = true; + PlayEndTime = DateTime.Now; + } + } + + //private void media1_MediaEnded(object sender, RoutedEventArgs e) + //{ + // //string fileExtensionCur = string.Empty; + // //string urlCur = string.Empty; + // //List hashList = videoList.Select(i => i.fileHash).ToList(); + // //string curUrl = media1.Source.ToString(); + // //string curHash = curUrl.Substring(curUrl.LastIndexOf("/") + 1, curUrl.LastIndexOf(".") - curUrl.LastIndexOf("/") - 1); + // //var curIndex = 0; + // //if (videoList.Count > 1) + // //{ + // // curIndex = hashList.ToList().IndexOf(curHash); + // // if (curIndex + 2 >= videoList.Count) + // // { + // // curIndex = curIndex + 2 - videoList.Count; + // // } + // // else + // // { + // // curIndex = curIndex + 2; + // // } + // //} + // ////if (curIndex >= item.materials.Count) + // ////{ + // //// curIndex = 0; + // ////} + // //if (videoList[curIndex].fileUrl.Contains("?")) + // //{ + // // fileExtensionCur = videoList[curIndex].fileUrl.Substring(videoList[curIndex].fileUrl.LastIndexOf("."), videoList[curIndex].fileUrl.LastIndexOf("?") - videoList[curIndex].fileUrl.LastIndexOf(".")).ToLower(); + // //} + // //else + // //{ + // // fileExtensionCur = videoList[curIndex].fileUrl.Substring(videoList[curIndex].fileUrl.LastIndexOf(".")).ToLower(); + // //} + // //urlCur = outLinePath + "/Main/" + videoList[curIndex].fileHash + fileExtensionCur; + // //media1.Play(); + // //media.Play(); + // //Thread.Sleep(500); + // //Canvas.SetZIndex(media, 2); + // //Canvas.SetZIndex(media1, 0); + // //Canvas.SetZIndex(media, 1); + // //media1.Source = new Uri(urlCur); + // //media1.Play(); + // //media1.Pause(); + + + // int curIndex = 0; + // List hashList = videoList.Select(i => i.fileHash).ToList(); + // string curUrl = media1.Source.ToString(); + // string curHash = curUrl.Substring(curUrl.LastIndexOf("/") + 1, curUrl.LastIndexOf(".") - curUrl.LastIndexOf("/") - 1); + // if (videoList.Count > 1) + // { + // curIndex = hashList.ToList().IndexOf(curHash); + // if (curIndex + 2 >= videoList.Count) + // { + // curIndex = curIndex + 2 - videoList.Count; + // } + // else + // { + // curIndex = curIndex + 2; + // } + // } + // if (app.isProgramServer) + // { + // log.WriteLogFile("fas", "发送"); + // //PlayEnd(media, media1, curIndex); + // SendPlay(curIndex); + // } + // else if (!app.isProgramSync) + // { + // PlayEnd(media, media1, curIndex); + // } + // else + // { + // IsPlayEnd = true; + // PlayEndTime = DateTime.Now; + // } + //} + + + + private void SendPlay(int curIndex) + { + app.isSendSync = true; + try + { + log.WriteLogFile(WebsocketForProgramServer.allSockets.ToList().ToString() + " " + curIndex, "发送"); + WebsocketForProgramServer.allSockets.ToList().ForEach(s => s.Send(curIndex.ToString())); + } + catch (Exception e) + { + + log.WriteLogFile(e.ToString(), "StartPlayerror"); + } + + } + + private void WebSocketManage_WebSocketReceiveEvent(string type, string message) + { + try + { + log.WriteLogFile(message, "WebSocketLogProg"); + if (type == "play") + { + int curIndex = Convert.ToInt32(message); + if (curIndex >= videoList.Count) + { + curIndex = 0; + } + //if (!app.isProgramServer) + //{ + curPlayIndex = curIndex; + mainp.Dispatcher.Invoke(new Action(() => + { + foreach (var item in mainVideo.Children) + { + var videoPlay = (MediaElement)item; + if (videoPlay.CanPause) + { + videoPlay.Pause(); + } + + } + PlayProg(); + })); + + + //} + } + //else if (type == "close") { + // media.Dispatcher.Invoke(new Action(() => + // { + // int curIndex = 0; + // int zindex = Canvas.GetZIndex(media); + // if (zindex == 1) + // { + // List hashList = videoList.Select(i => i.fileHash).ToList(); + // string curUrl = media.Source.ToString(); + // string curHash = curUrl.Substring(curUrl.LastIndexOf("/") + 1, curUrl.LastIndexOf(".") - curUrl.LastIndexOf("/") - 1); + // if (videoList.Count > 1) + // { + // curIndex = hashList.ToList().IndexOf(curHash); + // if (curIndex + 2 >= videoList.Count) + // { + // curIndex = curIndex + 2 - videoList.Count; + // } + // else + // { + // curIndex = curIndex + 2; + // } + // } + // PlayEnd(media1, media, curIndex); + // } + // else + // { + // List hashList = videoList.Select(i => i.fileHash).ToList(); + // string curUrl = media1.Source.ToString(); + // string curHash = curUrl.Substring(curUrl.LastIndexOf("/") + 1, curUrl.LastIndexOf(".") - curUrl.LastIndexOf("/") - 1); + // if (videoList.Count > 1) + // { + // curIndex = hashList.ToList().IndexOf(curHash); + // if (curIndex + 2 >= videoList.Count) + // { + // curIndex = curIndex + 2 - videoList.Count; + // } + // else + // { + // curIndex = curIndex + 2; + // } + // } + // PlayEnd(media, media1, curIndex); + // } + // })); + //} + } + catch (Exception ex) + { + log.WriteLogFile(ex.ToString(), "errorsocket"); + } + + } + + private void Window_MouseDown(object sender, MouseButtonEventArgs e) + { + try + { + log.WriteLogFile("点击屏保,进入关闭屏保方法" + DateTime.Now.TimeOfDay.ToString(), "closewin"); + if (!string.IsNullOrEmpty(app.configstartexe)) + { + app.isStartScreen = false; + //关闭信息发布 + //Process[] pro = Process.GetProcesses(); + //for (int i = 0; i < pro.Length; i++) + //{ + // if (pro[i].ProcessName.ToLower().Trim() == "pcscreensavers") + // { + // pro[i].Kill();//结束进程 + // } + //} + + app.AppPlayNameCH = "导视"; + app.Appversion = app.kioskVersion; + app.AppPlayName = "chrome"; + app.CurAppPlayName = app.AppPlayName; + + WebSocketForKiosk.allSocketsForKiosk.ToList().ForEach(s => s.Send("kiosk")); + //webForFace.CloseWebSocket(); + FulshMemor(); + if (hWaitTimer != IntPtr.Zero) + { + CloseHandle(hWaitTimer); + hWaitTimer = IntPtr.Zero; + } + //source1.Cancel(); + //source1.Dispose(); + this.Dispatcher.Invoke((Action)(() => + { + this.Close(); + })); + } + } + catch (Exception ex) + { + log.WriteLogFile(ex.ToString()); + } + } + + //private void media1_MediaFailed(object sender, ExceptionRoutedEventArgs e) + //{ + // log.WriteLogFile("卡了1", "mediaerror"); + // //media1.Close(); + + // media1.Dispatcher.Invoke(new Action(() => + // { + // media1.Stop(); + // media1.Position = new TimeSpan(0,0,0,0,100); + // media1.Play(); + // })); + //} + + //private void media_MediaFailed(object sender, ExceptionRoutedEventArgs e) + //{ + // log.WriteLogFile("卡了", "mediaerror"); + // media.Dispatcher.Invoke(new Action(() => + // { + // media.Stop(); + // media.Position = new TimeSpan(0, 0, 0, 0, 100); + // media.Play(); + // })); + //} + } +} diff --git a/Container/image/1.png b/Container/image/1.png new file mode 100644 index 0000000..9ac5d73 Binary files /dev/null and b/Container/image/1.png differ diff --git a/Container/image/11.jpg b/Container/image/11.jpg new file mode 100644 index 0000000..19bb168 Binary files /dev/null and b/Container/image/11.jpg differ diff --git a/Container/image/AppButton.gif b/Container/image/AppButton.gif new file mode 100644 index 0000000..8753839 Binary files /dev/null and b/Container/image/AppButton.gif differ diff --git a/Container/image/BG.gif b/Container/image/BG.gif new file mode 100644 index 0000000..745e213 Binary files /dev/null and b/Container/image/BG.gif differ diff --git a/Container/image/BGButton.png b/Container/image/BGButton.png new file mode 100644 index 0000000..fa8b950 Binary files /dev/null and b/Container/image/BGButton.png differ diff --git a/Container/image/BGButtonNew.png b/Container/image/BGButtonNew.png new file mode 100644 index 0000000..a0bee5a Binary files /dev/null and b/Container/image/BGButtonNew.png differ diff --git a/Container/image/BtnBack.png b/Container/image/BtnBack.png new file mode 100644 index 0000000..143b000 Binary files /dev/null and b/Container/image/BtnBack.png differ diff --git a/Container/image/BtnGoodinfo.png b/Container/image/BtnGoodinfo.png new file mode 100644 index 0000000..99a5613 Binary files /dev/null and b/Container/image/BtnGoodinfo.png differ diff --git a/Container/image/Btn_OK.jpg b/Container/image/Btn_OK.jpg new file mode 100644 index 0000000..d54cc1c Binary files /dev/null and b/Container/image/Btn_OK.jpg differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00000.png b/Container/image/CountDowmImage/倒计时透明度_00000.png new file mode 100644 index 0000000..419b2c0 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00000.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00001.png b/Container/image/CountDowmImage/倒计时透明度_00001.png new file mode 100644 index 0000000..1563c8f Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00001.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00002.png b/Container/image/CountDowmImage/倒计时透明度_00002.png new file mode 100644 index 0000000..180efa0 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00002.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00003.png b/Container/image/CountDowmImage/倒计时透明度_00003.png new file mode 100644 index 0000000..0729bff Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00003.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00004.png b/Container/image/CountDowmImage/倒计时透明度_00004.png new file mode 100644 index 0000000..b3e88cb Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00004.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00005.png b/Container/image/CountDowmImage/倒计时透明度_00005.png new file mode 100644 index 0000000..7e70a97 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00005.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00006.png b/Container/image/CountDowmImage/倒计时透明度_00006.png new file mode 100644 index 0000000..1d4f74f Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00006.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00007.png b/Container/image/CountDowmImage/倒计时透明度_00007.png new file mode 100644 index 0000000..b95afa2 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00007.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00008.png b/Container/image/CountDowmImage/倒计时透明度_00008.png new file mode 100644 index 0000000..8dce610 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00008.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00009.png b/Container/image/CountDowmImage/倒计时透明度_00009.png new file mode 100644 index 0000000..f7775b5 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00009.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00010.png b/Container/image/CountDowmImage/倒计时透明度_00010.png new file mode 100644 index 0000000..fc0bf81 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00010.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00011.png b/Container/image/CountDowmImage/倒计时透明度_00011.png new file mode 100644 index 0000000..83385b2 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00011.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00012.png b/Container/image/CountDowmImage/倒计时透明度_00012.png new file mode 100644 index 0000000..af73ec0 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00012.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00013.png b/Container/image/CountDowmImage/倒计时透明度_00013.png new file mode 100644 index 0000000..e5d0c67 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00013.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00014.png b/Container/image/CountDowmImage/倒计时透明度_00014.png new file mode 100644 index 0000000..417066b Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00014.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00015.png b/Container/image/CountDowmImage/倒计时透明度_00015.png new file mode 100644 index 0000000..fb6bbef Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00015.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00016.png b/Container/image/CountDowmImage/倒计时透明度_00016.png new file mode 100644 index 0000000..9945dae Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00016.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00017.png b/Container/image/CountDowmImage/倒计时透明度_00017.png new file mode 100644 index 0000000..076a2fa Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00017.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00018.png b/Container/image/CountDowmImage/倒计时透明度_00018.png new file mode 100644 index 0000000..afeb65f Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00018.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00019.png b/Container/image/CountDowmImage/倒计时透明度_00019.png new file mode 100644 index 0000000..09ae6d4 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00019.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00020.png b/Container/image/CountDowmImage/倒计时透明度_00020.png new file mode 100644 index 0000000..57d8408 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00020.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00021.png b/Container/image/CountDowmImage/倒计时透明度_00021.png new file mode 100644 index 0000000..0f6144d Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00021.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00022.png b/Container/image/CountDowmImage/倒计时透明度_00022.png new file mode 100644 index 0000000..eadfb7e Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00022.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00023.png b/Container/image/CountDowmImage/倒计时透明度_00023.png new file mode 100644 index 0000000..cfdba65 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00023.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00024.png b/Container/image/CountDowmImage/倒计时透明度_00024.png new file mode 100644 index 0000000..f797422 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00024.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00025.png b/Container/image/CountDowmImage/倒计时透明度_00025.png new file mode 100644 index 0000000..3926408 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00025.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00026.png b/Container/image/CountDowmImage/倒计时透明度_00026.png new file mode 100644 index 0000000..a45a2ff Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00026.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00027.png b/Container/image/CountDowmImage/倒计时透明度_00027.png new file mode 100644 index 0000000..d5064e7 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00027.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00028.png b/Container/image/CountDowmImage/倒计时透明度_00028.png new file mode 100644 index 0000000..c3ab8f5 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00028.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00029.png b/Container/image/CountDowmImage/倒计时透明度_00029.png new file mode 100644 index 0000000..b342b2e Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00029.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00030.png b/Container/image/CountDowmImage/倒计时透明度_00030.png new file mode 100644 index 0000000..d4895b9 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00030.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00031.png b/Container/image/CountDowmImage/倒计时透明度_00031.png new file mode 100644 index 0000000..6385bda Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00031.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00032.png b/Container/image/CountDowmImage/倒计时透明度_00032.png new file mode 100644 index 0000000..9ee0c90 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00032.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00033.png b/Container/image/CountDowmImage/倒计时透明度_00033.png new file mode 100644 index 0000000..4ac3a43 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00033.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00034.png b/Container/image/CountDowmImage/倒计时透明度_00034.png new file mode 100644 index 0000000..a506947 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00034.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00035.png b/Container/image/CountDowmImage/倒计时透明度_00035.png new file mode 100644 index 0000000..1d21a03 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00035.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00036.png b/Container/image/CountDowmImage/倒计时透明度_00036.png new file mode 100644 index 0000000..86621ac Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00036.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00037.png b/Container/image/CountDowmImage/倒计时透明度_00037.png new file mode 100644 index 0000000..515e73d Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00037.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00038.png b/Container/image/CountDowmImage/倒计时透明度_00038.png new file mode 100644 index 0000000..0b040a2 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00038.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00039.png b/Container/image/CountDowmImage/倒计时透明度_00039.png new file mode 100644 index 0000000..3255339 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00039.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00040.png b/Container/image/CountDowmImage/倒计时透明度_00040.png new file mode 100644 index 0000000..a82296d Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00040.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00041.png b/Container/image/CountDowmImage/倒计时透明度_00041.png new file mode 100644 index 0000000..aa31af2 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00041.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00042.png b/Container/image/CountDowmImage/倒计时透明度_00042.png new file mode 100644 index 0000000..f66a74c Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00042.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00043.png b/Container/image/CountDowmImage/倒计时透明度_00043.png new file mode 100644 index 0000000..dd0108b Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00043.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00044.png b/Container/image/CountDowmImage/倒计时透明度_00044.png new file mode 100644 index 0000000..87ae186 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00044.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00045.png b/Container/image/CountDowmImage/倒计时透明度_00045.png new file mode 100644 index 0000000..3373c3b Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00045.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00046.png b/Container/image/CountDowmImage/倒计时透明度_00046.png new file mode 100644 index 0000000..2317c07 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00046.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00047.png b/Container/image/CountDowmImage/倒计时透明度_00047.png new file mode 100644 index 0000000..74bf9a9 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00047.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00048.png b/Container/image/CountDowmImage/倒计时透明度_00048.png new file mode 100644 index 0000000..143e535 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00048.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00049.png b/Container/image/CountDowmImage/倒计时透明度_00049.png new file mode 100644 index 0000000..57e8e69 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00049.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00050.png b/Container/image/CountDowmImage/倒计时透明度_00050.png new file mode 100644 index 0000000..4a9e03c Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00050.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00051.png b/Container/image/CountDowmImage/倒计时透明度_00051.png new file mode 100644 index 0000000..2644ed6 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00051.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00052.png b/Container/image/CountDowmImage/倒计时透明度_00052.png new file mode 100644 index 0000000..432cf87 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00052.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00053.png b/Container/image/CountDowmImage/倒计时透明度_00053.png new file mode 100644 index 0000000..88fde63 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00053.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00054.png b/Container/image/CountDowmImage/倒计时透明度_00054.png new file mode 100644 index 0000000..0ac8a03 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00054.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00055.png b/Container/image/CountDowmImage/倒计时透明度_00055.png new file mode 100644 index 0000000..9d94574 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00055.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00056.png b/Container/image/CountDowmImage/倒计时透明度_00056.png new file mode 100644 index 0000000..399be6e Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00056.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00057.png b/Container/image/CountDowmImage/倒计时透明度_00057.png new file mode 100644 index 0000000..0a0a3bb Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00057.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00058.png b/Container/image/CountDowmImage/倒计时透明度_00058.png new file mode 100644 index 0000000..ad23892 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00058.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00059.png b/Container/image/CountDowmImage/倒计时透明度_00059.png new file mode 100644 index 0000000..9c2c0f1 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00059.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00060.png b/Container/image/CountDowmImage/倒计时透明度_00060.png new file mode 100644 index 0000000..03ebf9a Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00060.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00061.png b/Container/image/CountDowmImage/倒计时透明度_00061.png new file mode 100644 index 0000000..8791a05 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00061.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00062.png b/Container/image/CountDowmImage/倒计时透明度_00062.png new file mode 100644 index 0000000..c5bff9a Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00062.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00063.png b/Container/image/CountDowmImage/倒计时透明度_00063.png new file mode 100644 index 0000000..e8a1516 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00063.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00064.png b/Container/image/CountDowmImage/倒计时透明度_00064.png new file mode 100644 index 0000000..5ab5e17 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00064.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00065.png b/Container/image/CountDowmImage/倒计时透明度_00065.png new file mode 100644 index 0000000..fbec006 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00065.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00066.png b/Container/image/CountDowmImage/倒计时透明度_00066.png new file mode 100644 index 0000000..f2c1938 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00066.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00067.png b/Container/image/CountDowmImage/倒计时透明度_00067.png new file mode 100644 index 0000000..682c83f Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00067.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00068.png b/Container/image/CountDowmImage/倒计时透明度_00068.png new file mode 100644 index 0000000..81f50ef Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00068.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00069.png b/Container/image/CountDowmImage/倒计时透明度_00069.png new file mode 100644 index 0000000..1f1ff90 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00069.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00070.png b/Container/image/CountDowmImage/倒计时透明度_00070.png new file mode 100644 index 0000000..64d5a27 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00070.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00071.png b/Container/image/CountDowmImage/倒计时透明度_00071.png new file mode 100644 index 0000000..2c43e53 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00071.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00072.png b/Container/image/CountDowmImage/倒计时透明度_00072.png new file mode 100644 index 0000000..e0e2115 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00072.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00073.png b/Container/image/CountDowmImage/倒计时透明度_00073.png new file mode 100644 index 0000000..22ec5d4 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00073.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00074.png b/Container/image/CountDowmImage/倒计时透明度_00074.png new file mode 100644 index 0000000..5926ec0 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00074.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00075.png b/Container/image/CountDowmImage/倒计时透明度_00075.png new file mode 100644 index 0000000..6282514 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00075.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00076.png b/Container/image/CountDowmImage/倒计时透明度_00076.png new file mode 100644 index 0000000..a864bb0 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00076.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00077.png b/Container/image/CountDowmImage/倒计时透明度_00077.png new file mode 100644 index 0000000..fd361d8 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00077.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00078.png b/Container/image/CountDowmImage/倒计时透明度_00078.png new file mode 100644 index 0000000..d6e5f60 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00078.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00079.png b/Container/image/CountDowmImage/倒计时透明度_00079.png new file mode 100644 index 0000000..bbd8ee5 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00079.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00080.png b/Container/image/CountDowmImage/倒计时透明度_00080.png new file mode 100644 index 0000000..b43f679 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00080.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00081.png b/Container/image/CountDowmImage/倒计时透明度_00081.png new file mode 100644 index 0000000..caa5be4 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00081.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00082.png b/Container/image/CountDowmImage/倒计时透明度_00082.png new file mode 100644 index 0000000..f59c282 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00082.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00083.png b/Container/image/CountDowmImage/倒计时透明度_00083.png new file mode 100644 index 0000000..76421c3 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00083.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00084.png b/Container/image/CountDowmImage/倒计时透明度_00084.png new file mode 100644 index 0000000..35ef736 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00084.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00085.png b/Container/image/CountDowmImage/倒计时透明度_00085.png new file mode 100644 index 0000000..060b411 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00085.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00086.png b/Container/image/CountDowmImage/倒计时透明度_00086.png new file mode 100644 index 0000000..060b411 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00086.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00087.png b/Container/image/CountDowmImage/倒计时透明度_00087.png new file mode 100644 index 0000000..060b411 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00087.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00088.png b/Container/image/CountDowmImage/倒计时透明度_00088.png new file mode 100644 index 0000000..060b411 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00088.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00089.png b/Container/image/CountDowmImage/倒计时透明度_00089.png new file mode 100644 index 0000000..060b411 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00089.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00090.png b/Container/image/CountDowmImage/倒计时透明度_00090.png new file mode 100644 index 0000000..060b411 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00090.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00091.png b/Container/image/CountDowmImage/倒计时透明度_00091.png new file mode 100644 index 0000000..d44d722 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00091.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00092.png b/Container/image/CountDowmImage/倒计时透明度_00092.png new file mode 100644 index 0000000..849a6c3 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00092.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00093.png b/Container/image/CountDowmImage/倒计时透明度_00093.png new file mode 100644 index 0000000..ef155fe Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00093.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00094.png b/Container/image/CountDowmImage/倒计时透明度_00094.png new file mode 100644 index 0000000..524cbc8 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00094.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00095.png b/Container/image/CountDowmImage/倒计时透明度_00095.png new file mode 100644 index 0000000..0fa87be Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00095.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00096.png b/Container/image/CountDowmImage/倒计时透明度_00096.png new file mode 100644 index 0000000..02fcf81 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00096.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00097.png b/Container/image/CountDowmImage/倒计时透明度_00097.png new file mode 100644 index 0000000..cfdbbf7 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00097.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00098.png b/Container/image/CountDowmImage/倒计时透明度_00098.png new file mode 100644 index 0000000..48c3c2e Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00098.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00099.png b/Container/image/CountDowmImage/倒计时透明度_00099.png new file mode 100644 index 0000000..0df735e Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00099.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00100.png b/Container/image/CountDowmImage/倒计时透明度_00100.png new file mode 100644 index 0000000..0683c22 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00100.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00101.png b/Container/image/CountDowmImage/倒计时透明度_00101.png new file mode 100644 index 0000000..af0df49 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00101.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00102.png b/Container/image/CountDowmImage/倒计时透明度_00102.png new file mode 100644 index 0000000..612e250 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00102.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00103.png b/Container/image/CountDowmImage/倒计时透明度_00103.png new file mode 100644 index 0000000..44304f8 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00103.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00104.png b/Container/image/CountDowmImage/倒计时透明度_00104.png new file mode 100644 index 0000000..acde663 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00104.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00105.png b/Container/image/CountDowmImage/倒计时透明度_00105.png new file mode 100644 index 0000000..5505ed5 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00105.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00106.png b/Container/image/CountDowmImage/倒计时透明度_00106.png new file mode 100644 index 0000000..6256674 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00106.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00107.png b/Container/image/CountDowmImage/倒计时透明度_00107.png new file mode 100644 index 0000000..78aa5ed Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00107.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00108.png b/Container/image/CountDowmImage/倒计时透明度_00108.png new file mode 100644 index 0000000..01bfc7a Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00108.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00109.png b/Container/image/CountDowmImage/倒计时透明度_00109.png new file mode 100644 index 0000000..01bfc7a Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00109.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00110.png b/Container/image/CountDowmImage/倒计时透明度_00110.png new file mode 100644 index 0000000..01bfc7a Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00110.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00111.png b/Container/image/CountDowmImage/倒计时透明度_00111.png new file mode 100644 index 0000000..01bfc7a Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00111.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00112.png b/Container/image/CountDowmImage/倒计时透明度_00112.png new file mode 100644 index 0000000..01bfc7a Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00112.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00113.png b/Container/image/CountDowmImage/倒计时透明度_00113.png new file mode 100644 index 0000000..01bfc7a Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00113.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00114.png b/Container/image/CountDowmImage/倒计时透明度_00114.png new file mode 100644 index 0000000..01bfc7a Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00114.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00115.png b/Container/image/CountDowmImage/倒计时透明度_00115.png new file mode 100644 index 0000000..d6f0773 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00115.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00116.png b/Container/image/CountDowmImage/倒计时透明度_00116.png new file mode 100644 index 0000000..edd5528 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00116.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00117.png b/Container/image/CountDowmImage/倒计时透明度_00117.png new file mode 100644 index 0000000..a732db8 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00117.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00118.png b/Container/image/CountDowmImage/倒计时透明度_00118.png new file mode 100644 index 0000000..44304f8 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00118.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00119.png b/Container/image/CountDowmImage/倒计时透明度_00119.png new file mode 100644 index 0000000..612e250 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00119.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00120.png b/Container/image/CountDowmImage/倒计时透明度_00120.png new file mode 100644 index 0000000..07e1d7d Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00120.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00121.png b/Container/image/CountDowmImage/倒计时透明度_00121.png new file mode 100644 index 0000000..a9ce860 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00121.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00122.png b/Container/image/CountDowmImage/倒计时透明度_00122.png new file mode 100644 index 0000000..420dc29 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00122.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00123.png b/Container/image/CountDowmImage/倒计时透明度_00123.png new file mode 100644 index 0000000..677ba23 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00123.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00124.png b/Container/image/CountDowmImage/倒计时透明度_00124.png new file mode 100644 index 0000000..62b2050 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00124.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00125.png b/Container/image/CountDowmImage/倒计时透明度_00125.png new file mode 100644 index 0000000..00c85ee Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00125.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00126.png b/Container/image/CountDowmImage/倒计时透明度_00126.png new file mode 100644 index 0000000..ef84b21 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00126.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00127.png b/Container/image/CountDowmImage/倒计时透明度_00127.png new file mode 100644 index 0000000..d427ce9 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00127.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00128.png b/Container/image/CountDowmImage/倒计时透明度_00128.png new file mode 100644 index 0000000..4cfb597 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00128.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00129.png b/Container/image/CountDowmImage/倒计时透明度_00129.png new file mode 100644 index 0000000..152b1db Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00129.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00130.png b/Container/image/CountDowmImage/倒计时透明度_00130.png new file mode 100644 index 0000000..94e6da5 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00130.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00131.png b/Container/image/CountDowmImage/倒计时透明度_00131.png new file mode 100644 index 0000000..060b411 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00131.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00132.png b/Container/image/CountDowmImage/倒计时透明度_00132.png new file mode 100644 index 0000000..060b411 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00132.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00133.png b/Container/image/CountDowmImage/倒计时透明度_00133.png new file mode 100644 index 0000000..060b411 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00133.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00134.png b/Container/image/CountDowmImage/倒计时透明度_00134.png new file mode 100644 index 0000000..8363f9c Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00134.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00135.png b/Container/image/CountDowmImage/倒计时透明度_00135.png new file mode 100644 index 0000000..68e75b3 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00135.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00136.png b/Container/image/CountDowmImage/倒计时透明度_00136.png new file mode 100644 index 0000000..bfe5f74 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00136.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00137.png b/Container/image/CountDowmImage/倒计时透明度_00137.png new file mode 100644 index 0000000..51fbdef Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00137.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00138.png b/Container/image/CountDowmImage/倒计时透明度_00138.png new file mode 100644 index 0000000..d860e77 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00138.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00139.png b/Container/image/CountDowmImage/倒计时透明度_00139.png new file mode 100644 index 0000000..d512590 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00139.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00140.png b/Container/image/CountDowmImage/倒计时透明度_00140.png new file mode 100644 index 0000000..7beedea Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00140.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00141.png b/Container/image/CountDowmImage/倒计时透明度_00141.png new file mode 100644 index 0000000..0fa391a Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00141.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00142.png b/Container/image/CountDowmImage/倒计时透明度_00142.png new file mode 100644 index 0000000..674e3e8 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00142.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00143.png b/Container/image/CountDowmImage/倒计时透明度_00143.png new file mode 100644 index 0000000..2aea121 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00143.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00144.png b/Container/image/CountDowmImage/倒计时透明度_00144.png new file mode 100644 index 0000000..65c0a5f Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00144.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00145.png b/Container/image/CountDowmImage/倒计时透明度_00145.png new file mode 100644 index 0000000..db033b0 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00145.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00146.png b/Container/image/CountDowmImage/倒计时透明度_00146.png new file mode 100644 index 0000000..630e45e Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00146.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00147.png b/Container/image/CountDowmImage/倒计时透明度_00147.png new file mode 100644 index 0000000..b41bf36 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00147.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00148.png b/Container/image/CountDowmImage/倒计时透明度_00148.png new file mode 100644 index 0000000..e854e86 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00148.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00149.png b/Container/image/CountDowmImage/倒计时透明度_00149.png new file mode 100644 index 0000000..483a94c Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00149.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00150.png b/Container/image/CountDowmImage/倒计时透明度_00150.png new file mode 100644 index 0000000..483a94c Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00150.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00151.png b/Container/image/CountDowmImage/倒计时透明度_00151.png new file mode 100644 index 0000000..483a94c Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00151.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00152.png b/Container/image/CountDowmImage/倒计时透明度_00152.png new file mode 100644 index 0000000..483a94c Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00152.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00153.png b/Container/image/CountDowmImage/倒计时透明度_00153.png new file mode 100644 index 0000000..483a94c Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00153.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00154.png b/Container/image/CountDowmImage/倒计时透明度_00154.png new file mode 100644 index 0000000..483a94c Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00154.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00155.png b/Container/image/CountDowmImage/倒计时透明度_00155.png new file mode 100644 index 0000000..483a94c Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00155.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00156.png b/Container/image/CountDowmImage/倒计时透明度_00156.png new file mode 100644 index 0000000..6912b35 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00156.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00157.png b/Container/image/CountDowmImage/倒计时透明度_00157.png new file mode 100644 index 0000000..574e64b Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00157.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00158.png b/Container/image/CountDowmImage/倒计时透明度_00158.png new file mode 100644 index 0000000..77cb041 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00158.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00159.png b/Container/image/CountDowmImage/倒计时透明度_00159.png new file mode 100644 index 0000000..63417b2 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00159.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00160.png b/Container/image/CountDowmImage/倒计时透明度_00160.png new file mode 100644 index 0000000..ded65bf Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00160.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00161.png b/Container/image/CountDowmImage/倒计时透明度_00161.png new file mode 100644 index 0000000..3e177ea Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00161.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00162.png b/Container/image/CountDowmImage/倒计时透明度_00162.png new file mode 100644 index 0000000..de44fc9 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00162.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00163.png b/Container/image/CountDowmImage/倒计时透明度_00163.png new file mode 100644 index 0000000..eaebc16 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00163.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00164.png b/Container/image/CountDowmImage/倒计时透明度_00164.png new file mode 100644 index 0000000..4ba2522 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00164.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00165.png b/Container/image/CountDowmImage/倒计时透明度_00165.png new file mode 100644 index 0000000..29cee05 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00165.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00166.png b/Container/image/CountDowmImage/倒计时透明度_00166.png new file mode 100644 index 0000000..aa2b4be Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00166.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00167.png b/Container/image/CountDowmImage/倒计时透明度_00167.png new file mode 100644 index 0000000..e3c94f1 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00167.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00168.png b/Container/image/CountDowmImage/倒计时透明度_00168.png new file mode 100644 index 0000000..77f8b70 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00168.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00169.png b/Container/image/CountDowmImage/倒计时透明度_00169.png new file mode 100644 index 0000000..512cb0e Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00169.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00170.png b/Container/image/CountDowmImage/倒计时透明度_00170.png new file mode 100644 index 0000000..a7a7258 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00170.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00171.png b/Container/image/CountDowmImage/倒计时透明度_00171.png new file mode 100644 index 0000000..822ad41 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00171.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00172.png b/Container/image/CountDowmImage/倒计时透明度_00172.png new file mode 100644 index 0000000..060b411 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00172.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00173.png b/Container/image/CountDowmImage/倒计时透明度_00173.png new file mode 100644 index 0000000..060b411 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00173.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00174.png b/Container/image/CountDowmImage/倒计时透明度_00174.png new file mode 100644 index 0000000..0306e43 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00174.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00175.png b/Container/image/CountDowmImage/倒计时透明度_00175.png new file mode 100644 index 0000000..02e6850 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00175.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00176.png b/Container/image/CountDowmImage/倒计时透明度_00176.png new file mode 100644 index 0000000..7a87974 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00176.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00177.png b/Container/image/CountDowmImage/倒计时透明度_00177.png new file mode 100644 index 0000000..3c5772b Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00177.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00178.png b/Container/image/CountDowmImage/倒计时透明度_00178.png new file mode 100644 index 0000000..1f5fff1 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00178.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00179.png b/Container/image/CountDowmImage/倒计时透明度_00179.png new file mode 100644 index 0000000..b168cd2 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00179.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00180.png b/Container/image/CountDowmImage/倒计时透明度_00180.png new file mode 100644 index 0000000..c598a9f Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00180.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00181.png b/Container/image/CountDowmImage/倒计时透明度_00181.png new file mode 100644 index 0000000..0eef506 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00181.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00182.png b/Container/image/CountDowmImage/倒计时透明度_00182.png new file mode 100644 index 0000000..4c265cf Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00182.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00183.png b/Container/image/CountDowmImage/倒计时透明度_00183.png new file mode 100644 index 0000000..1fd85f8 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00183.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00184.png b/Container/image/CountDowmImage/倒计时透明度_00184.png new file mode 100644 index 0000000..2351c17 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00184.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00185.png b/Container/image/CountDowmImage/倒计时透明度_00185.png new file mode 100644 index 0000000..864e3a8 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00185.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00186.png b/Container/image/CountDowmImage/倒计时透明度_00186.png new file mode 100644 index 0000000..cc3a923 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00186.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00187.png b/Container/image/CountDowmImage/倒计时透明度_00187.png new file mode 100644 index 0000000..08ed933 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00187.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00188.png b/Container/image/CountDowmImage/倒计时透明度_00188.png new file mode 100644 index 0000000..55bef8f Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00188.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00189.png b/Container/image/CountDowmImage/倒计时透明度_00189.png new file mode 100644 index 0000000..212da77 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00189.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00190.png b/Container/image/CountDowmImage/倒计时透明度_00190.png new file mode 100644 index 0000000..9433d0f Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00190.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00191.png b/Container/image/CountDowmImage/倒计时透明度_00191.png new file mode 100644 index 0000000..4946002 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00191.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00192.png b/Container/image/CountDowmImage/倒计时透明度_00192.png new file mode 100644 index 0000000..4946002 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00192.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00193.png b/Container/image/CountDowmImage/倒计时透明度_00193.png new file mode 100644 index 0000000..4946002 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00193.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00194.png b/Container/image/CountDowmImage/倒计时透明度_00194.png new file mode 100644 index 0000000..4946002 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00194.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00195.png b/Container/image/CountDowmImage/倒计时透明度_00195.png new file mode 100644 index 0000000..4946002 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00195.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00196.png b/Container/image/CountDowmImage/倒计时透明度_00196.png new file mode 100644 index 0000000..4946002 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00196.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00197.png b/Container/image/CountDowmImage/倒计时透明度_00197.png new file mode 100644 index 0000000..4946002 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00197.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00198.png b/Container/image/CountDowmImage/倒计时透明度_00198.png new file mode 100644 index 0000000..56bbad8 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00198.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00199.png b/Container/image/CountDowmImage/倒计时透明度_00199.png new file mode 100644 index 0000000..5690986 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00199.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00200.png b/Container/image/CountDowmImage/倒计时透明度_00200.png new file mode 100644 index 0000000..e256b75 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00200.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00201.png b/Container/image/CountDowmImage/倒计时透明度_00201.png new file mode 100644 index 0000000..55bef8f Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00201.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00202.png b/Container/image/CountDowmImage/倒计时透明度_00202.png new file mode 100644 index 0000000..bc17fed Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00202.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00203.png b/Container/image/CountDowmImage/倒计时透明度_00203.png new file mode 100644 index 0000000..7cbf2da Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00203.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00204.png b/Container/image/CountDowmImage/倒计时透明度_00204.png new file mode 100644 index 0000000..98b18ad Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00204.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00205.png b/Container/image/CountDowmImage/倒计时透明度_00205.png new file mode 100644 index 0000000..e49beb4 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00205.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00206.png b/Container/image/CountDowmImage/倒计时透明度_00206.png new file mode 100644 index 0000000..408dbb0 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00206.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00207.png b/Container/image/CountDowmImage/倒计时透明度_00207.png new file mode 100644 index 0000000..7440685 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00207.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00208.png b/Container/image/CountDowmImage/倒计时透明度_00208.png new file mode 100644 index 0000000..f8df38c Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00208.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00209.png b/Container/image/CountDowmImage/倒计时透明度_00209.png new file mode 100644 index 0000000..f618f0a Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00209.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00210.png b/Container/image/CountDowmImage/倒计时透明度_00210.png new file mode 100644 index 0000000..e3615bf Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00210.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00211.png b/Container/image/CountDowmImage/倒计时透明度_00211.png new file mode 100644 index 0000000..16f1abb Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00211.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00212.png b/Container/image/CountDowmImage/倒计时透明度_00212.png new file mode 100644 index 0000000..c32075f Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00212.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00213.png b/Container/image/CountDowmImage/倒计时透明度_00213.png new file mode 100644 index 0000000..e286c31 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00213.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00214.png b/Container/image/CountDowmImage/倒计时透明度_00214.png new file mode 100644 index 0000000..f9f86d3 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00214.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00215.png b/Container/image/CountDowmImage/倒计时透明度_00215.png new file mode 100644 index 0000000..1d25b9c Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00215.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00216.png b/Container/image/CountDowmImage/倒计时透明度_00216.png new file mode 100644 index 0000000..3723a1f Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00216.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00217.png b/Container/image/CountDowmImage/倒计时透明度_00217.png new file mode 100644 index 0000000..942b6f4 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00217.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00218.png b/Container/image/CountDowmImage/倒计时透明度_00218.png new file mode 100644 index 0000000..5357948 Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00218.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00219.png b/Container/image/CountDowmImage/倒计时透明度_00219.png new file mode 100644 index 0000000..4008eab Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00219.png differ diff --git a/Container/image/CountDowmImage/倒计时透明度_00220.png b/Container/image/CountDowmImage/倒计时透明度_00220.png new file mode 100644 index 0000000..16b3e8c Binary files /dev/null and b/Container/image/CountDowmImage/倒计时透明度_00220.png differ diff --git a/Container/image/Loading.gif b/Container/image/Loading.gif new file mode 100644 index 0000000..fe2fd02 Binary files /dev/null and b/Container/image/Loading.gif differ diff --git a/Container/image/PointBlack.png b/Container/image/PointBlack.png new file mode 100644 index 0000000..9f6d7df Binary files /dev/null and b/Container/image/PointBlack.png differ diff --git a/Container/image/QR.png b/Container/image/QR.png new file mode 100644 index 0000000..096aa11 Binary files /dev/null and b/Container/image/QR.png differ diff --git a/Container/image/UCBackground.png b/Container/image/UCBackground.png new file mode 100644 index 0000000..7842fa6 Binary files /dev/null and b/Container/image/UCBackground.png differ diff --git a/Container/image/background.jpg b/Container/image/background.jpg new file mode 100644 index 0000000..a7fc0ab Binary files /dev/null and b/Container/image/background.jpg differ diff --git a/Container/image/bg.png b/Container/image/bg.png new file mode 100644 index 0000000..ddc7388 Binary files /dev/null and b/Container/image/bg.png differ diff --git a/Container/image/bg_logo.png b/Container/image/bg_logo.png new file mode 100644 index 0000000..bd4f32e Binary files /dev/null and b/Container/image/bg_logo.png differ diff --git a/Container/image/connectfailed.jpg b/Container/image/connectfailed.jpg new file mode 100644 index 0000000..bea06b7 Binary files /dev/null and b/Container/image/connectfailed.jpg differ diff --git a/Container/image/connection.jpg b/Container/image/connection.jpg new file mode 100644 index 0000000..f0e88dc Binary files /dev/null and b/Container/image/connection.jpg differ diff --git a/Container/image/coupon.png b/Container/image/coupon.png new file mode 100644 index 0000000..d5317fe Binary files /dev/null and b/Container/image/coupon.png differ diff --git a/Container/image/devicebackground.jpg b/Container/image/devicebackground.jpg new file mode 100644 index 0000000..611965b Binary files /dev/null and b/Container/image/devicebackground.jpg differ diff --git a/Container/image/deviceinfo.jpg b/Container/image/deviceinfo.jpg new file mode 100644 index 0000000..98970a7 Binary files /dev/null and b/Container/image/deviceinfo.jpg differ diff --git a/Container/image/failed.jpg b/Container/image/failed.jpg new file mode 100644 index 0000000..b617310 Binary files /dev/null and b/Container/image/failed.jpg differ diff --git a/Container/image/livebg.png b/Container/image/livebg.png new file mode 100644 index 0000000..44226e9 Binary files /dev/null and b/Container/image/livebg.png differ diff --git a/Container/image/local.png b/Container/image/local.png new file mode 100644 index 0000000..33b9f4d Binary files /dev/null and b/Container/image/local.png differ diff --git a/Container/image/point.png b/Container/image/point.png new file mode 100644 index 0000000..fa28add Binary files /dev/null and b/Container/image/point.png differ diff --git a/Container/image/success.jpg b/Container/image/success.jpg new file mode 100644 index 0000000..c667159 Binary files /dev/null and b/Container/image/success.jpg differ diff --git a/Container/image/weather/aqi.png b/Container/image/weather/aqi.png new file mode 100644 index 0000000..f7d9a97 Binary files /dev/null and b/Container/image/weather/aqi.png differ diff --git a/Container/image/weather/fl.png b/Container/image/weather/fl.png new file mode 100644 index 0000000..25e90c4 Binary files /dev/null and b/Container/image/weather/fl.png differ diff --git a/Container/image/weather/pm.png b/Container/image/weather/pm.png new file mode 100644 index 0000000..af521ca Binary files /dev/null and b/Container/image/weather/pm.png differ diff --git a/Container/image/weather/sd.png b/Container/image/weather/sd.png new file mode 100644 index 0000000..e1c5e9c Binary files /dev/null and b/Container/image/weather/sd.png differ diff --git a/Container/image/weather/weather_cloud.png b/Container/image/weather/weather_cloud.png new file mode 100644 index 0000000..bb5dd80 Binary files /dev/null and b/Container/image/weather/weather_cloud.png differ diff --git a/Container/image/weather/weather_rian.png b/Container/image/weather/weather_rian.png new file mode 100644 index 0000000..609a715 Binary files /dev/null and b/Container/image/weather/weather_rian.png differ diff --git a/Container/image/weather/weather_snow.png b/Container/image/weather/weather_snow.png new file mode 100644 index 0000000..129a5cc Binary files /dev/null and b/Container/image/weather/weather_snow.png differ diff --git a/Container/image/weather/weather_sum.png b/Container/image/weather/weather_sum.png new file mode 100644 index 0000000..557af5e Binary files /dev/null and b/Container/image/weather/weather_sum.png differ diff --git a/Container/image/千目3840.png b/Container/image/千目3840.png new file mode 100644 index 0000000..30a14ef Binary files /dev/null and b/Container/image/千目3840.png differ diff --git a/Container/image/启动页竖.jpg b/Container/image/启动页竖.jpg new file mode 100644 index 0000000..f51f505 Binary files /dev/null and b/Container/image/启动页竖.jpg differ diff --git a/Container/lib/NAudio.dll b/Container/lib/NAudio.dll new file mode 100644 index 0000000..553425e Binary files /dev/null and b/Container/lib/NAudio.dll differ diff --git a/Container/lib/msc_x64.dll b/Container/lib/msc_x64.dll new file mode 100644 index 0000000..9c9d4d3 Binary files /dev/null and b/Container/lib/msc_x64.dll differ diff --git a/Container/packages.config b/Container/packages.config new file mode 100644 index 0000000..71731ce --- /dev/null +++ b/Container/packages.config @@ -0,0 +1,29 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Container/qm.ico b/Container/qm.ico new file mode 100644 index 0000000..34a51b5 Binary files /dev/null and b/Container/qm.ico differ diff --git a/Container/touch/touch1/touch_00000.png b/Container/touch/touch1/touch_00000.png new file mode 100644 index 0000000..843801d Binary files /dev/null and b/Container/touch/touch1/touch_00000.png differ diff --git a/Container/touch/touch1/touch_00001.png b/Container/touch/touch1/touch_00001.png new file mode 100644 index 0000000..61d2a79 Binary files /dev/null and b/Container/touch/touch1/touch_00001.png differ diff --git a/Container/touch/touch1/touch_00002.png b/Container/touch/touch1/touch_00002.png new file mode 100644 index 0000000..df02285 Binary files /dev/null and b/Container/touch/touch1/touch_00002.png differ diff --git a/Container/touch/touch1/touch_00003.png b/Container/touch/touch1/touch_00003.png new file mode 100644 index 0000000..d4d23ff Binary files /dev/null and b/Container/touch/touch1/touch_00003.png differ diff --git a/Container/touch/touch1/touch_00004.png b/Container/touch/touch1/touch_00004.png new file mode 100644 index 0000000..35b410e Binary files /dev/null and b/Container/touch/touch1/touch_00004.png differ diff --git a/Container/touch/touch1/touch_00005.png b/Container/touch/touch1/touch_00005.png new file mode 100644 index 0000000..18f691a Binary files /dev/null and b/Container/touch/touch1/touch_00005.png differ diff --git a/Container/touch/touch1/touch_00006.png b/Container/touch/touch1/touch_00006.png new file mode 100644 index 0000000..90720d5 Binary files /dev/null and b/Container/touch/touch1/touch_00006.png differ diff --git a/Container/touch/touch1/touch_00007.png b/Container/touch/touch1/touch_00007.png new file mode 100644 index 0000000..9d49d4c Binary files /dev/null and b/Container/touch/touch1/touch_00007.png differ diff --git a/Container/touch/touch1/touch_00008.png b/Container/touch/touch1/touch_00008.png new file mode 100644 index 0000000..0750acd Binary files /dev/null and b/Container/touch/touch1/touch_00008.png differ diff --git a/Container/touch/touch1/touch_00009.png b/Container/touch/touch1/touch_00009.png new file mode 100644 index 0000000..f94da7c Binary files /dev/null and b/Container/touch/touch1/touch_00009.png differ diff --git a/Container/touch/touch1/touch_00010.png b/Container/touch/touch1/touch_00010.png new file mode 100644 index 0000000..a0ff0b7 Binary files /dev/null and b/Container/touch/touch1/touch_00010.png differ diff --git a/Container/touch/touch1/touch_00011.png b/Container/touch/touch1/touch_00011.png new file mode 100644 index 0000000..3b4fa7d Binary files /dev/null and b/Container/touch/touch1/touch_00011.png differ diff --git a/Container/touch/touch1/touch_00012.png b/Container/touch/touch1/touch_00012.png new file mode 100644 index 0000000..135455c Binary files /dev/null and b/Container/touch/touch1/touch_00012.png differ diff --git a/Container/touch/touch1/touch_00013.png b/Container/touch/touch1/touch_00013.png new file mode 100644 index 0000000..5e70a2b Binary files /dev/null and b/Container/touch/touch1/touch_00013.png differ diff --git a/Container/touch/touch1/touch_00014.png b/Container/touch/touch1/touch_00014.png new file mode 100644 index 0000000..3b4fac4 Binary files /dev/null and b/Container/touch/touch1/touch_00014.png differ diff --git a/Container/touch/touch1/touch_00015.png b/Container/touch/touch1/touch_00015.png new file mode 100644 index 0000000..3822087 Binary files /dev/null and b/Container/touch/touch1/touch_00015.png differ diff --git a/Container/touch/touch1/touch_00016.png b/Container/touch/touch1/touch_00016.png new file mode 100644 index 0000000..90e7040 Binary files /dev/null and b/Container/touch/touch1/touch_00016.png differ diff --git a/Container/touch/touch1/touch_00017.png b/Container/touch/touch1/touch_00017.png new file mode 100644 index 0000000..16e0323 Binary files /dev/null and b/Container/touch/touch1/touch_00017.png differ diff --git a/Container/touch/touch1/touch_00018.png b/Container/touch/touch1/touch_00018.png new file mode 100644 index 0000000..4cb4c01 Binary files /dev/null and b/Container/touch/touch1/touch_00018.png differ diff --git a/Container/touch/touch1/touch_00019.png b/Container/touch/touch1/touch_00019.png new file mode 100644 index 0000000..e84be70 Binary files /dev/null and b/Container/touch/touch1/touch_00019.png differ diff --git a/Container/touch/touch1/touch_00020.png b/Container/touch/touch1/touch_00020.png new file mode 100644 index 0000000..0717ef9 Binary files /dev/null and b/Container/touch/touch1/touch_00020.png differ diff --git a/Container/touch/touch1/touch_00021.png b/Container/touch/touch1/touch_00021.png new file mode 100644 index 0000000..3ffba7e Binary files /dev/null and b/Container/touch/touch1/touch_00021.png differ diff --git a/Container/touch/touch1/touch_00022.png b/Container/touch/touch1/touch_00022.png new file mode 100644 index 0000000..7e12fa6 Binary files /dev/null and b/Container/touch/touch1/touch_00022.png differ diff --git a/Container/touch/touch1/touch_00023.png b/Container/touch/touch1/touch_00023.png new file mode 100644 index 0000000..b53527e Binary files /dev/null and b/Container/touch/touch1/touch_00023.png differ diff --git a/Container/touch/touch1/touch_00024.png b/Container/touch/touch1/touch_00024.png new file mode 100644 index 0000000..5a01ce9 Binary files /dev/null and b/Container/touch/touch1/touch_00024.png differ diff --git a/Container/touch/touch1/touch_00025.png b/Container/touch/touch1/touch_00025.png new file mode 100644 index 0000000..18911e4 Binary files /dev/null and b/Container/touch/touch1/touch_00025.png differ diff --git a/Container/touch/touch1/touch_00026.png b/Container/touch/touch1/touch_00026.png new file mode 100644 index 0000000..ac9430b Binary files /dev/null and b/Container/touch/touch1/touch_00026.png differ diff --git a/Container/touch/touch1/touch_00027.png b/Container/touch/touch1/touch_00027.png new file mode 100644 index 0000000..6dddaef Binary files /dev/null and b/Container/touch/touch1/touch_00027.png differ diff --git a/Container/touch/touch1/touch_00028.png b/Container/touch/touch1/touch_00028.png new file mode 100644 index 0000000..fd49fd4 Binary files /dev/null and b/Container/touch/touch1/touch_00028.png differ diff --git a/Container/touch/touch1/touch_00029.png b/Container/touch/touch1/touch_00029.png new file mode 100644 index 0000000..57858ff Binary files /dev/null and b/Container/touch/touch1/touch_00029.png differ diff --git a/Container/touch/touch1/touch_00030.png b/Container/touch/touch1/touch_00030.png new file mode 100644 index 0000000..86a505d Binary files /dev/null and b/Container/touch/touch1/touch_00030.png differ diff --git a/Container/touch/touch1/touch_00031.png b/Container/touch/touch1/touch_00031.png new file mode 100644 index 0000000..2d3e223 Binary files /dev/null and b/Container/touch/touch1/touch_00031.png differ diff --git a/Container/touch/touch1/touch_00032.png b/Container/touch/touch1/touch_00032.png new file mode 100644 index 0000000..372bafb Binary files /dev/null and b/Container/touch/touch1/touch_00032.png differ diff --git a/Container/touch/touch1/touch_00033.png b/Container/touch/touch1/touch_00033.png new file mode 100644 index 0000000..28aa1a9 Binary files /dev/null and b/Container/touch/touch1/touch_00033.png differ diff --git a/Container/touch/touch1/touch_00034.png b/Container/touch/touch1/touch_00034.png new file mode 100644 index 0000000..858e769 Binary files /dev/null and b/Container/touch/touch1/touch_00034.png differ diff --git a/Container/touch/touch1/touch_00035.png b/Container/touch/touch1/touch_00035.png new file mode 100644 index 0000000..bc36e58 Binary files /dev/null and b/Container/touch/touch1/touch_00035.png differ diff --git a/Container/touch/touch1/touch_00036.png b/Container/touch/touch1/touch_00036.png new file mode 100644 index 0000000..a6a0649 Binary files /dev/null and b/Container/touch/touch1/touch_00036.png differ diff --git a/Container/touch/touch1/touch_00037.png b/Container/touch/touch1/touch_00037.png new file mode 100644 index 0000000..8a0eafc Binary files /dev/null and b/Container/touch/touch1/touch_00037.png differ diff --git a/Container/touch/touch1/touch_00038.png b/Container/touch/touch1/touch_00038.png new file mode 100644 index 0000000..b6e0c0f Binary files /dev/null and b/Container/touch/touch1/touch_00038.png differ diff --git a/Container/touch/touch1/touch_00039.png b/Container/touch/touch1/touch_00039.png new file mode 100644 index 0000000..9ca5ed5 Binary files /dev/null and b/Container/touch/touch1/touch_00039.png differ diff --git a/Container/touch/touch1/touch_00040.png b/Container/touch/touch1/touch_00040.png new file mode 100644 index 0000000..ed87378 Binary files /dev/null and b/Container/touch/touch1/touch_00040.png differ diff --git a/Container/touch/touch1/touch_00041.png b/Container/touch/touch1/touch_00041.png new file mode 100644 index 0000000..e9fa6e3 Binary files /dev/null and b/Container/touch/touch1/touch_00041.png differ diff --git a/Container/touch/touch1/touch_00042.png b/Container/touch/touch1/touch_00042.png new file mode 100644 index 0000000..3391eb9 Binary files /dev/null and b/Container/touch/touch1/touch_00042.png differ diff --git a/Container/touch/touch1/touch_00043.png b/Container/touch/touch1/touch_00043.png new file mode 100644 index 0000000..2ce1205 Binary files /dev/null and b/Container/touch/touch1/touch_00043.png differ diff --git a/Container/touch/touch1/touch_00044.png b/Container/touch/touch1/touch_00044.png new file mode 100644 index 0000000..ad0d5a6 Binary files /dev/null and b/Container/touch/touch1/touch_00044.png differ diff --git a/Container/touch/touch1/touch_00045.png b/Container/touch/touch1/touch_00045.png new file mode 100644 index 0000000..494dad2 Binary files /dev/null and b/Container/touch/touch1/touch_00045.png differ diff --git a/Container/touch/touch1/touch_00046.png b/Container/touch/touch1/touch_00046.png new file mode 100644 index 0000000..e69a99b Binary files /dev/null and b/Container/touch/touch1/touch_00046.png differ diff --git a/Container/touch/touch1/touch_00047.png b/Container/touch/touch1/touch_00047.png new file mode 100644 index 0000000..3fb3f45 Binary files /dev/null and b/Container/touch/touch1/touch_00047.png differ diff --git a/Container/touch/touch1/touch_00048.png b/Container/touch/touch1/touch_00048.png new file mode 100644 index 0000000..1cc6d0b Binary files /dev/null and b/Container/touch/touch1/touch_00048.png differ diff --git a/Container/touch/touch1/touch_00049.png b/Container/touch/touch1/touch_00049.png new file mode 100644 index 0000000..20f2331 Binary files /dev/null and b/Container/touch/touch1/touch_00049.png differ diff --git a/Container/touch/touch1/touch_00050.png b/Container/touch/touch1/touch_00050.png new file mode 100644 index 0000000..6a7ea7d Binary files /dev/null and b/Container/touch/touch1/touch_00050.png differ diff --git a/Container/touch/touch1/touch_00051.png b/Container/touch/touch1/touch_00051.png new file mode 100644 index 0000000..247c92c Binary files /dev/null and b/Container/touch/touch1/touch_00051.png differ diff --git a/Container/touch/touch1/touch_00052.png b/Container/touch/touch1/touch_00052.png new file mode 100644 index 0000000..64b2d81 Binary files /dev/null and b/Container/touch/touch1/touch_00052.png differ diff --git a/Container/touch/touch1/touch_00053.png b/Container/touch/touch1/touch_00053.png new file mode 100644 index 0000000..6506246 Binary files /dev/null and b/Container/touch/touch1/touch_00053.png differ diff --git a/Container/touch/touch1/touch_00054.png b/Container/touch/touch1/touch_00054.png new file mode 100644 index 0000000..dc830fc Binary files /dev/null and b/Container/touch/touch1/touch_00054.png differ diff --git a/Container/touch/touch1/touch_00055.png b/Container/touch/touch1/touch_00055.png new file mode 100644 index 0000000..d04a198 Binary files /dev/null and b/Container/touch/touch1/touch_00055.png differ diff --git a/Container/touch/touch1/touch_00056.png b/Container/touch/touch1/touch_00056.png new file mode 100644 index 0000000..2f4ead9 Binary files /dev/null and b/Container/touch/touch1/touch_00056.png differ diff --git a/Container/touch/touch1/touch_00057.png b/Container/touch/touch1/touch_00057.png new file mode 100644 index 0000000..16b0df4 Binary files /dev/null and b/Container/touch/touch1/touch_00057.png differ diff --git a/Container/touch/touch1/touch_00058.png b/Container/touch/touch1/touch_00058.png new file mode 100644 index 0000000..56ddaa0 Binary files /dev/null and b/Container/touch/touch1/touch_00058.png differ diff --git a/Container/touch/touch1/touch_00059.png b/Container/touch/touch1/touch_00059.png new file mode 100644 index 0000000..786b18b Binary files /dev/null and b/Container/touch/touch1/touch_00059.png differ diff --git a/Container/touch/touch1/touch_00060.png b/Container/touch/touch1/touch_00060.png new file mode 100644 index 0000000..0195801 Binary files /dev/null and b/Container/touch/touch1/touch_00060.png differ diff --git a/Container/touch/touch1/touch_00061.png b/Container/touch/touch1/touch_00061.png new file mode 100644 index 0000000..877686f Binary files /dev/null and b/Container/touch/touch1/touch_00061.png differ diff --git a/Container/touch/touch1/touch_00062.png b/Container/touch/touch1/touch_00062.png new file mode 100644 index 0000000..431e178 Binary files /dev/null and b/Container/touch/touch1/touch_00062.png differ diff --git a/Container/touch/touch1/touch_00063.png b/Container/touch/touch1/touch_00063.png new file mode 100644 index 0000000..957f1cb Binary files /dev/null and b/Container/touch/touch1/touch_00063.png differ diff --git a/Container/touch/touch1/touch_00064.png b/Container/touch/touch1/touch_00064.png new file mode 100644 index 0000000..65b9b5f Binary files /dev/null and b/Container/touch/touch1/touch_00064.png differ diff --git a/Container/touch/touch1/touch_00065.png b/Container/touch/touch1/touch_00065.png new file mode 100644 index 0000000..de39574 Binary files /dev/null and b/Container/touch/touch1/touch_00065.png differ diff --git a/Container/touch/touch1/touch_00066.png b/Container/touch/touch1/touch_00066.png new file mode 100644 index 0000000..74b2f89 Binary files /dev/null and b/Container/touch/touch1/touch_00066.png differ diff --git a/Container/touch/touch1/touch_00067.png b/Container/touch/touch1/touch_00067.png new file mode 100644 index 0000000..68302dd Binary files /dev/null and b/Container/touch/touch1/touch_00067.png differ diff --git a/Container/touch/touch1/touch_00068.png b/Container/touch/touch1/touch_00068.png new file mode 100644 index 0000000..3d4c3fa Binary files /dev/null and b/Container/touch/touch1/touch_00068.png differ diff --git a/Container/touch/touch2/touch_00000.png b/Container/touch/touch2/touch_00000.png new file mode 100644 index 0000000..4d8e1b0 Binary files /dev/null and b/Container/touch/touch2/touch_00000.png differ diff --git a/Container/touch/touch2/touch_00001.png b/Container/touch/touch2/touch_00001.png new file mode 100644 index 0000000..569bb62 Binary files /dev/null and b/Container/touch/touch2/touch_00001.png differ diff --git a/Container/touch/touch2/touch_00002.png b/Container/touch/touch2/touch_00002.png new file mode 100644 index 0000000..6794179 Binary files /dev/null and b/Container/touch/touch2/touch_00002.png differ diff --git a/Container/touch/touch2/touch_00003.png b/Container/touch/touch2/touch_00003.png new file mode 100644 index 0000000..fd5ad03 Binary files /dev/null and b/Container/touch/touch2/touch_00003.png differ diff --git a/Container/touch/touch2/touch_00004.png b/Container/touch/touch2/touch_00004.png new file mode 100644 index 0000000..5f32eb4 Binary files /dev/null and b/Container/touch/touch2/touch_00004.png differ diff --git a/Container/touch/touch2/touch_00005.png b/Container/touch/touch2/touch_00005.png new file mode 100644 index 0000000..9ac480d Binary files /dev/null and b/Container/touch/touch2/touch_00005.png differ diff --git a/Container/touch/touch2/touch_00006.png b/Container/touch/touch2/touch_00006.png new file mode 100644 index 0000000..358bcd0 Binary files /dev/null and b/Container/touch/touch2/touch_00006.png differ diff --git a/Container/touch/touch2/touch_00007.png b/Container/touch/touch2/touch_00007.png new file mode 100644 index 0000000..854c8a2 Binary files /dev/null and b/Container/touch/touch2/touch_00007.png differ diff --git a/Container/touch/touch2/touch_00008.png b/Container/touch/touch2/touch_00008.png new file mode 100644 index 0000000..a42d333 Binary files /dev/null and b/Container/touch/touch2/touch_00008.png differ diff --git a/Container/touch/touch2/touch_00009.png b/Container/touch/touch2/touch_00009.png new file mode 100644 index 0000000..df710a1 Binary files /dev/null and b/Container/touch/touch2/touch_00009.png differ diff --git a/Container/touch/touch2/touch_00010.png b/Container/touch/touch2/touch_00010.png new file mode 100644 index 0000000..f4a0faa Binary files /dev/null and b/Container/touch/touch2/touch_00010.png differ diff --git a/Container/touch/touch2/touch_00011.png b/Container/touch/touch2/touch_00011.png new file mode 100644 index 0000000..c8db7de Binary files /dev/null and b/Container/touch/touch2/touch_00011.png differ diff --git a/Container/touch/touch2/touch_00012.png b/Container/touch/touch2/touch_00012.png new file mode 100644 index 0000000..c2de725 Binary files /dev/null and b/Container/touch/touch2/touch_00012.png differ diff --git a/Container/touch/touch2/touch_00013.png b/Container/touch/touch2/touch_00013.png new file mode 100644 index 0000000..a67ed5a Binary files /dev/null and b/Container/touch/touch2/touch_00013.png differ diff --git a/Container/touch/touch2/touch_00014.png b/Container/touch/touch2/touch_00014.png new file mode 100644 index 0000000..5fea4ac Binary files /dev/null and b/Container/touch/touch2/touch_00014.png differ diff --git a/Container/touch/touch2/touch_00015.png b/Container/touch/touch2/touch_00015.png new file mode 100644 index 0000000..3df3c05 Binary files /dev/null and b/Container/touch/touch2/touch_00015.png differ diff --git a/Container/touch/touch2/touch_00016.png b/Container/touch/touch2/touch_00016.png new file mode 100644 index 0000000..983b97a Binary files /dev/null and b/Container/touch/touch2/touch_00016.png differ diff --git a/Container/touch/touch2/touch_00017.png b/Container/touch/touch2/touch_00017.png new file mode 100644 index 0000000..6aee159 Binary files /dev/null and b/Container/touch/touch2/touch_00017.png differ diff --git a/Container/touch/touch2/touch_00018.png b/Container/touch/touch2/touch_00018.png new file mode 100644 index 0000000..e6372a5 Binary files /dev/null and b/Container/touch/touch2/touch_00018.png differ diff --git a/Container/touch/touch2/touch_00019.png b/Container/touch/touch2/touch_00019.png new file mode 100644 index 0000000..3fefd9a Binary files /dev/null and b/Container/touch/touch2/touch_00019.png differ diff --git a/Container/touch/touch2/touch_00020.png b/Container/touch/touch2/touch_00020.png new file mode 100644 index 0000000..96cfa67 Binary files /dev/null and b/Container/touch/touch2/touch_00020.png differ diff --git a/Container/touch/touch2/touch_00021.png b/Container/touch/touch2/touch_00021.png new file mode 100644 index 0000000..90cbbbd Binary files /dev/null and b/Container/touch/touch2/touch_00021.png differ diff --git a/Container/touch/touch2/touch_00022.png b/Container/touch/touch2/touch_00022.png new file mode 100644 index 0000000..44e52d4 Binary files /dev/null and b/Container/touch/touch2/touch_00022.png differ diff --git a/Container/touch/touch2/touch_00023.png b/Container/touch/touch2/touch_00023.png new file mode 100644 index 0000000..2ee8458 Binary files /dev/null and b/Container/touch/touch2/touch_00023.png differ diff --git a/Container/touch/touch2/touch_00024.png b/Container/touch/touch2/touch_00024.png new file mode 100644 index 0000000..21180c9 Binary files /dev/null and b/Container/touch/touch2/touch_00024.png differ diff --git a/Container/touch/touch2/touch_00025.png b/Container/touch/touch2/touch_00025.png new file mode 100644 index 0000000..d66f2a5 Binary files /dev/null and b/Container/touch/touch2/touch_00025.png differ diff --git a/Container/touch/touch2/touch_00026.png b/Container/touch/touch2/touch_00026.png new file mode 100644 index 0000000..dec78f5 Binary files /dev/null and b/Container/touch/touch2/touch_00026.png differ diff --git a/Container/touch/touch2/touch_00027.png b/Container/touch/touch2/touch_00027.png new file mode 100644 index 0000000..6c29466 Binary files /dev/null and b/Container/touch/touch2/touch_00027.png differ diff --git a/Container/touch/touch2/touch_00028.png b/Container/touch/touch2/touch_00028.png new file mode 100644 index 0000000..fe490ad Binary files /dev/null and b/Container/touch/touch2/touch_00028.png differ diff --git a/Container/touch/touch2/touch_00029.png b/Container/touch/touch2/touch_00029.png new file mode 100644 index 0000000..2061960 Binary files /dev/null and b/Container/touch/touch2/touch_00029.png differ diff --git a/Container/touch/touch2/touch_00030.png b/Container/touch/touch2/touch_00030.png new file mode 100644 index 0000000..a738000 Binary files /dev/null and b/Container/touch/touch2/touch_00030.png differ diff --git a/Container/touch/touch2/touch_00031.png b/Container/touch/touch2/touch_00031.png new file mode 100644 index 0000000..655a7ab Binary files /dev/null and b/Container/touch/touch2/touch_00031.png differ diff --git a/Container/touch/touch2/touch_00032.png b/Container/touch/touch2/touch_00032.png new file mode 100644 index 0000000..9f633f5 Binary files /dev/null and b/Container/touch/touch2/touch_00032.png differ diff --git a/Container/touch/touch2/touch_00033.png b/Container/touch/touch2/touch_00033.png new file mode 100644 index 0000000..6baad99 Binary files /dev/null and b/Container/touch/touch2/touch_00033.png differ diff --git a/Container/touch/touch2/touch_00034.png b/Container/touch/touch2/touch_00034.png new file mode 100644 index 0000000..e89f325 Binary files /dev/null and b/Container/touch/touch2/touch_00034.png differ diff --git a/Container/touch/touch2/touch_00035.png b/Container/touch/touch2/touch_00035.png new file mode 100644 index 0000000..0276c6b Binary files /dev/null and b/Container/touch/touch2/touch_00035.png differ diff --git a/Container/touch/touch2/touch_00036.png b/Container/touch/touch2/touch_00036.png new file mode 100644 index 0000000..3cd7ba7 Binary files /dev/null and b/Container/touch/touch2/touch_00036.png differ diff --git a/Container/touch/touch2/touch_00037.png b/Container/touch/touch2/touch_00037.png new file mode 100644 index 0000000..dfaaa2a Binary files /dev/null and b/Container/touch/touch2/touch_00037.png differ diff --git a/Container/touch/touch2/touch_00038.png b/Container/touch/touch2/touch_00038.png new file mode 100644 index 0000000..faed7af Binary files /dev/null and b/Container/touch/touch2/touch_00038.png differ diff --git a/Container/touch/touch2/touch_00039.png b/Container/touch/touch2/touch_00039.png new file mode 100644 index 0000000..56d91be Binary files /dev/null and b/Container/touch/touch2/touch_00039.png differ diff --git a/Container/touch/touch2/touch_00040.png b/Container/touch/touch2/touch_00040.png new file mode 100644 index 0000000..14fa91a Binary files /dev/null and b/Container/touch/touch2/touch_00040.png differ diff --git a/Container/touch/touch2/touch_00041.png b/Container/touch/touch2/touch_00041.png new file mode 100644 index 0000000..ea5908d Binary files /dev/null and b/Container/touch/touch2/touch_00041.png differ diff --git a/Container/touch/touch2/touch_00042.png b/Container/touch/touch2/touch_00042.png new file mode 100644 index 0000000..377f8fe Binary files /dev/null and b/Container/touch/touch2/touch_00042.png differ diff --git a/Container/touch/touch2/touch_00043.png b/Container/touch/touch2/touch_00043.png new file mode 100644 index 0000000..2e8c035 Binary files /dev/null and b/Container/touch/touch2/touch_00043.png differ diff --git a/Container/touch/touch2/touch_00044.png b/Container/touch/touch2/touch_00044.png new file mode 100644 index 0000000..4274094 Binary files /dev/null and b/Container/touch/touch2/touch_00044.png differ diff --git a/Container/touch/touch2/touch_00045.png b/Container/touch/touch2/touch_00045.png new file mode 100644 index 0000000..d143096 Binary files /dev/null and b/Container/touch/touch2/touch_00045.png differ diff --git a/Container/touch/touch2/touch_00046.png b/Container/touch/touch2/touch_00046.png new file mode 100644 index 0000000..65a3165 Binary files /dev/null and b/Container/touch/touch2/touch_00046.png differ diff --git a/Container/touch/touch2/touch_00047.png b/Container/touch/touch2/touch_00047.png new file mode 100644 index 0000000..e2606f3 Binary files /dev/null and b/Container/touch/touch2/touch_00047.png differ diff --git a/Container/touch/touch2/touch_00048.png b/Container/touch/touch2/touch_00048.png new file mode 100644 index 0000000..abed970 Binary files /dev/null and b/Container/touch/touch2/touch_00048.png differ diff --git a/Container/touch/touch2/touch_00049.png b/Container/touch/touch2/touch_00049.png new file mode 100644 index 0000000..cb6c365 Binary files /dev/null and b/Container/touch/touch2/touch_00049.png differ diff --git a/Container/touch/touch2/touch_00050.png b/Container/touch/touch2/touch_00050.png new file mode 100644 index 0000000..4863919 Binary files /dev/null and b/Container/touch/touch2/touch_00050.png differ diff --git a/Container/touch/touch2/touch_00051.png b/Container/touch/touch2/touch_00051.png new file mode 100644 index 0000000..1d95630 Binary files /dev/null and b/Container/touch/touch2/touch_00051.png differ diff --git a/Container/touch/touch2/touch_00052.png b/Container/touch/touch2/touch_00052.png new file mode 100644 index 0000000..ebd2259 Binary files /dev/null and b/Container/touch/touch2/touch_00052.png differ diff --git a/Container/touch/touch2/touch_00053.png b/Container/touch/touch2/touch_00053.png new file mode 100644 index 0000000..f46df94 Binary files /dev/null and b/Container/touch/touch2/touch_00053.png differ diff --git a/Container/touch/touch2/touch_00054.png b/Container/touch/touch2/touch_00054.png new file mode 100644 index 0000000..54d6fbc Binary files /dev/null and b/Container/touch/touch2/touch_00054.png differ diff --git a/Container/touch/touch2/touch_00055.png b/Container/touch/touch2/touch_00055.png new file mode 100644 index 0000000..22b7ecc Binary files /dev/null and b/Container/touch/touch2/touch_00055.png differ diff --git a/Container/touch/touch2/touch_00056.png b/Container/touch/touch2/touch_00056.png new file mode 100644 index 0000000..4d8e1b0 Binary files /dev/null and b/Container/touch/touch2/touch_00056.png differ diff --git a/Container/touch/touch2/touch_00057.png b/Container/touch/touch2/touch_00057.png new file mode 100644 index 0000000..9e607ca Binary files /dev/null and b/Container/touch/touch2/touch_00057.png differ diff --git a/Container/touch/touch2/touch_00058.png b/Container/touch/touch2/touch_00058.png new file mode 100644 index 0000000..bea4c0e Binary files /dev/null and b/Container/touch/touch2/touch_00058.png differ diff --git a/Container/touch/touch2/touch_00059.png b/Container/touch/touch2/touch_00059.png new file mode 100644 index 0000000..235067f Binary files /dev/null and b/Container/touch/touch2/touch_00059.png differ diff --git a/Container/touch/touch2/touch_00060.png b/Container/touch/touch2/touch_00060.png new file mode 100644 index 0000000..014b69a Binary files /dev/null and b/Container/touch/touch2/touch_00060.png differ diff --git a/Container/touch/touch2/touch_00061.png b/Container/touch/touch2/touch_00061.png new file mode 100644 index 0000000..a7de008 Binary files /dev/null and b/Container/touch/touch2/touch_00061.png differ diff --git a/Container/touch/touch2/touch_00062.png b/Container/touch/touch2/touch_00062.png new file mode 100644 index 0000000..d9e1ca3 Binary files /dev/null and b/Container/touch/touch2/touch_00062.png differ diff --git a/Container/touch/touch2/touch_00063.png b/Container/touch/touch2/touch_00063.png new file mode 100644 index 0000000..7e49bbc Binary files /dev/null and b/Container/touch/touch2/touch_00063.png differ diff --git a/Container/touch/touch2/touch_00064.png b/Container/touch/touch2/touch_00064.png new file mode 100644 index 0000000..62dbde3 Binary files /dev/null and b/Container/touch/touch2/touch_00064.png differ diff --git a/Container/touch/touch2/touch_00065.png b/Container/touch/touch2/touch_00065.png new file mode 100644 index 0000000..2c45514 Binary files /dev/null and b/Container/touch/touch2/touch_00065.png differ diff --git a/Container/touch/touch2/touch_00066.png b/Container/touch/touch2/touch_00066.png new file mode 100644 index 0000000..10b2930 Binary files /dev/null and b/Container/touch/touch2/touch_00066.png differ diff --git a/Container/touch/touch2/touch_00067.png b/Container/touch/touch2/touch_00067.png new file mode 100644 index 0000000..3c95cf7 Binary files /dev/null and b/Container/touch/touch2/touch_00067.png differ diff --git a/Container/touch/touch2/touch_00068.png b/Container/touch/touch2/touch_00068.png new file mode 100644 index 0000000..2e9b424 Binary files /dev/null and b/Container/touch/touch2/touch_00068.png differ diff --git a/Container/touch/touch3/touch_00000.png b/Container/touch/touch3/touch_00000.png new file mode 100644 index 0000000..1546d72 Binary files /dev/null and b/Container/touch/touch3/touch_00000.png differ diff --git a/Container/touch/touch3/touch_00001.png b/Container/touch/touch3/touch_00001.png new file mode 100644 index 0000000..b644de9 Binary files /dev/null and b/Container/touch/touch3/touch_00001.png differ diff --git a/Container/touch/touch3/touch_00002.png b/Container/touch/touch3/touch_00002.png new file mode 100644 index 0000000..f490966 Binary files /dev/null and b/Container/touch/touch3/touch_00002.png differ diff --git a/Container/touch/touch3/touch_00003.png b/Container/touch/touch3/touch_00003.png new file mode 100644 index 0000000..c7e4b3b Binary files /dev/null and b/Container/touch/touch3/touch_00003.png differ diff --git a/Container/touch/touch3/touch_00004.png b/Container/touch/touch3/touch_00004.png new file mode 100644 index 0000000..3c8fbfa Binary files /dev/null and b/Container/touch/touch3/touch_00004.png differ diff --git a/Container/touch/touch3/touch_00005.png b/Container/touch/touch3/touch_00005.png new file mode 100644 index 0000000..d233e88 Binary files /dev/null and b/Container/touch/touch3/touch_00005.png differ diff --git a/Container/touch/touch3/touch_00006.png b/Container/touch/touch3/touch_00006.png new file mode 100644 index 0000000..2639b37 Binary files /dev/null and b/Container/touch/touch3/touch_00006.png differ diff --git a/Container/touch/touch3/touch_00007.png b/Container/touch/touch3/touch_00007.png new file mode 100644 index 0000000..1710c36 Binary files /dev/null and b/Container/touch/touch3/touch_00007.png differ diff --git a/Container/touch/touch3/touch_00008.png b/Container/touch/touch3/touch_00008.png new file mode 100644 index 0000000..df3ece2 Binary files /dev/null and b/Container/touch/touch3/touch_00008.png differ diff --git a/Container/touch/touch3/touch_00009.png b/Container/touch/touch3/touch_00009.png new file mode 100644 index 0000000..81b9fa9 Binary files /dev/null and b/Container/touch/touch3/touch_00009.png differ diff --git a/Container/touch/touch3/touch_00010.png b/Container/touch/touch3/touch_00010.png new file mode 100644 index 0000000..d5e73bc Binary files /dev/null and b/Container/touch/touch3/touch_00010.png differ diff --git a/Container/touch/touch3/touch_00011.png b/Container/touch/touch3/touch_00011.png new file mode 100644 index 0000000..0b2b559 Binary files /dev/null and b/Container/touch/touch3/touch_00011.png differ diff --git a/Container/touch/touch3/touch_00012.png b/Container/touch/touch3/touch_00012.png new file mode 100644 index 0000000..169a472 Binary files /dev/null and b/Container/touch/touch3/touch_00012.png differ diff --git a/Container/touch/touch3/touch_00013.png b/Container/touch/touch3/touch_00013.png new file mode 100644 index 0000000..b29e39b Binary files /dev/null and b/Container/touch/touch3/touch_00013.png differ diff --git a/Container/touch/touch3/touch_00014.png b/Container/touch/touch3/touch_00014.png new file mode 100644 index 0000000..8b6aab7 Binary files /dev/null and b/Container/touch/touch3/touch_00014.png differ diff --git a/Container/touch/touch3/touch_00015.png b/Container/touch/touch3/touch_00015.png new file mode 100644 index 0000000..b20f621 Binary files /dev/null and b/Container/touch/touch3/touch_00015.png differ diff --git a/Container/touch/touch3/touch_00016.png b/Container/touch/touch3/touch_00016.png new file mode 100644 index 0000000..7bf125c Binary files /dev/null and b/Container/touch/touch3/touch_00016.png differ diff --git a/Container/touch/touch3/touch_00017.png b/Container/touch/touch3/touch_00017.png new file mode 100644 index 0000000..8823cf7 Binary files /dev/null and b/Container/touch/touch3/touch_00017.png differ diff --git a/Container/touch/touch3/touch_00018.png b/Container/touch/touch3/touch_00018.png new file mode 100644 index 0000000..ef5c614 Binary files /dev/null and b/Container/touch/touch3/touch_00018.png differ diff --git a/Container/touch/touch3/touch_00019.png b/Container/touch/touch3/touch_00019.png new file mode 100644 index 0000000..66f1d4f Binary files /dev/null and b/Container/touch/touch3/touch_00019.png differ diff --git a/Container/touch/touch3/touch_00020.png b/Container/touch/touch3/touch_00020.png new file mode 100644 index 0000000..2a97d6a Binary files /dev/null and b/Container/touch/touch3/touch_00020.png differ diff --git a/Container/touch/touch3/touch_00021.png b/Container/touch/touch3/touch_00021.png new file mode 100644 index 0000000..11e44a5 Binary files /dev/null and b/Container/touch/touch3/touch_00021.png differ diff --git a/Container/touch/touch3/touch_00022.png b/Container/touch/touch3/touch_00022.png new file mode 100644 index 0000000..0b40044 Binary files /dev/null and b/Container/touch/touch3/touch_00022.png differ diff --git a/Container/touch/touch3/touch_00023.png b/Container/touch/touch3/touch_00023.png new file mode 100644 index 0000000..3a111eb Binary files /dev/null and b/Container/touch/touch3/touch_00023.png differ diff --git a/Container/touch/touch3/touch_00024.png b/Container/touch/touch3/touch_00024.png new file mode 100644 index 0000000..9a76546 Binary files /dev/null and b/Container/touch/touch3/touch_00024.png differ diff --git a/Container/touch/touch3/touch_00025.png b/Container/touch/touch3/touch_00025.png new file mode 100644 index 0000000..6e1b4c1 Binary files /dev/null and b/Container/touch/touch3/touch_00025.png differ diff --git a/Container/touch/touch3/touch_00026.png b/Container/touch/touch3/touch_00026.png new file mode 100644 index 0000000..0976649 Binary files /dev/null and b/Container/touch/touch3/touch_00026.png differ diff --git a/Container/touch/touch3/touch_00027.png b/Container/touch/touch3/touch_00027.png new file mode 100644 index 0000000..4f16cf6 Binary files /dev/null and b/Container/touch/touch3/touch_00027.png differ diff --git a/Container/touch/touch3/touch_00028.png b/Container/touch/touch3/touch_00028.png new file mode 100644 index 0000000..ca1c257 Binary files /dev/null and b/Container/touch/touch3/touch_00028.png differ diff --git a/Container/touch/touch3/touch_00029.png b/Container/touch/touch3/touch_00029.png new file mode 100644 index 0000000..3b800f2 Binary files /dev/null and b/Container/touch/touch3/touch_00029.png differ diff --git a/Container/touch/touch3/touch_00030.png b/Container/touch/touch3/touch_00030.png new file mode 100644 index 0000000..412102c Binary files /dev/null and b/Container/touch/touch3/touch_00030.png differ diff --git a/Container/touch/touch3/touch_00031.png b/Container/touch/touch3/touch_00031.png new file mode 100644 index 0000000..4320a3d Binary files /dev/null and b/Container/touch/touch3/touch_00031.png differ diff --git a/Container/touch/touch3/touch_00032.png b/Container/touch/touch3/touch_00032.png new file mode 100644 index 0000000..6728d4c Binary files /dev/null and b/Container/touch/touch3/touch_00032.png differ diff --git a/Container/touch/touch3/touch_00033.png b/Container/touch/touch3/touch_00033.png new file mode 100644 index 0000000..f2d5146 Binary files /dev/null and b/Container/touch/touch3/touch_00033.png differ diff --git a/Container/touch/touch3/touch_00034.png b/Container/touch/touch3/touch_00034.png new file mode 100644 index 0000000..6658530 Binary files /dev/null and b/Container/touch/touch3/touch_00034.png differ diff --git a/Container/touch/touch3/touch_00035.png b/Container/touch/touch3/touch_00035.png new file mode 100644 index 0000000..0e71b70 Binary files /dev/null and b/Container/touch/touch3/touch_00035.png differ diff --git a/Container/touch/touch3/touch_00036.png b/Container/touch/touch3/touch_00036.png new file mode 100644 index 0000000..b6528cb Binary files /dev/null and b/Container/touch/touch3/touch_00036.png differ diff --git a/Container/touch/touch3/touch_00037.png b/Container/touch/touch3/touch_00037.png new file mode 100644 index 0000000..5ee3027 Binary files /dev/null and b/Container/touch/touch3/touch_00037.png differ diff --git a/Container/touch/touch3/touch_00038.png b/Container/touch/touch3/touch_00038.png new file mode 100644 index 0000000..97deb51 Binary files /dev/null and b/Container/touch/touch3/touch_00038.png differ diff --git a/Container/touch/touch3/touch_00039.png b/Container/touch/touch3/touch_00039.png new file mode 100644 index 0000000..a708cb3 Binary files /dev/null and b/Container/touch/touch3/touch_00039.png differ diff --git a/Container/touch/touch3/touch_00040.png b/Container/touch/touch3/touch_00040.png new file mode 100644 index 0000000..ea08770 Binary files /dev/null and b/Container/touch/touch3/touch_00040.png differ diff --git a/Container/touch/touch3/touch_00041.png b/Container/touch/touch3/touch_00041.png new file mode 100644 index 0000000..20ec9a5 Binary files /dev/null and b/Container/touch/touch3/touch_00041.png differ diff --git a/Container/touch/touch3/touch_00042.png b/Container/touch/touch3/touch_00042.png new file mode 100644 index 0000000..9b0e9fc Binary files /dev/null and b/Container/touch/touch3/touch_00042.png differ diff --git a/Container/touch/touch3/touch_00043.png b/Container/touch/touch3/touch_00043.png new file mode 100644 index 0000000..44b38a2 Binary files /dev/null and b/Container/touch/touch3/touch_00043.png differ diff --git a/Container/touch/touch3/touch_00044.png b/Container/touch/touch3/touch_00044.png new file mode 100644 index 0000000..47d8598 Binary files /dev/null and b/Container/touch/touch3/touch_00044.png differ diff --git a/Container/touch/touch3/touch_00045.png b/Container/touch/touch3/touch_00045.png new file mode 100644 index 0000000..72c89d8 Binary files /dev/null and b/Container/touch/touch3/touch_00045.png differ diff --git a/Container/touch/touch3/touch_00046.png b/Container/touch/touch3/touch_00046.png new file mode 100644 index 0000000..dedff83 Binary files /dev/null and b/Container/touch/touch3/touch_00046.png differ diff --git a/Container/touch/touch3/touch_00047.png b/Container/touch/touch3/touch_00047.png new file mode 100644 index 0000000..b182409 Binary files /dev/null and b/Container/touch/touch3/touch_00047.png differ diff --git a/Container/touch/touch3/touch_00048.png b/Container/touch/touch3/touch_00048.png new file mode 100644 index 0000000..8413fb8 Binary files /dev/null and b/Container/touch/touch3/touch_00048.png differ diff --git a/Container/touch/touch3/touch_00049.png b/Container/touch/touch3/touch_00049.png new file mode 100644 index 0000000..1c7ef53 Binary files /dev/null and b/Container/touch/touch3/touch_00049.png differ diff --git a/Container/touch/touch3/touch_00050.png b/Container/touch/touch3/touch_00050.png new file mode 100644 index 0000000..9169dd3 Binary files /dev/null and b/Container/touch/touch3/touch_00050.png differ diff --git a/Container/touch/touch3/touch_00051.png b/Container/touch/touch3/touch_00051.png new file mode 100644 index 0000000..c2f60ac Binary files /dev/null and b/Container/touch/touch3/touch_00051.png differ diff --git a/Container/touch/touch3/touch_00052.png b/Container/touch/touch3/touch_00052.png new file mode 100644 index 0000000..1e452fc Binary files /dev/null and b/Container/touch/touch3/touch_00052.png differ diff --git a/Container/touch/touch3/touch_00053.png b/Container/touch/touch3/touch_00053.png new file mode 100644 index 0000000..fac6fb5 Binary files /dev/null and b/Container/touch/touch3/touch_00053.png differ diff --git a/Container/touch/touch3/touch_00054.png b/Container/touch/touch3/touch_00054.png new file mode 100644 index 0000000..2fd2241 Binary files /dev/null and b/Container/touch/touch3/touch_00054.png differ diff --git a/Container/touch/touch3/touch_00055.png b/Container/touch/touch3/touch_00055.png new file mode 100644 index 0000000..c7201d6 Binary files /dev/null and b/Container/touch/touch3/touch_00055.png differ diff --git a/Container/touch/touch3/touch_00056.png b/Container/touch/touch3/touch_00056.png new file mode 100644 index 0000000..c043aff Binary files /dev/null and b/Container/touch/touch3/touch_00056.png differ diff --git a/Container/touch/touch3/touch_00057.png b/Container/touch/touch3/touch_00057.png new file mode 100644 index 0000000..84a5284 Binary files /dev/null and b/Container/touch/touch3/touch_00057.png differ diff --git a/Container/touch/touch3/touch_00058.png b/Container/touch/touch3/touch_00058.png new file mode 100644 index 0000000..8290a2a Binary files /dev/null and b/Container/touch/touch3/touch_00058.png differ diff --git a/Container/touch/touch3/touch_00059.png b/Container/touch/touch3/touch_00059.png new file mode 100644 index 0000000..40706be Binary files /dev/null and b/Container/touch/touch3/touch_00059.png differ diff --git a/Container/touch/touch3/touch_00060.png b/Container/touch/touch3/touch_00060.png new file mode 100644 index 0000000..9494303 Binary files /dev/null and b/Container/touch/touch3/touch_00060.png differ diff --git a/Container/touch/touch3/touch_00061.png b/Container/touch/touch3/touch_00061.png new file mode 100644 index 0000000..0a2335a Binary files /dev/null and b/Container/touch/touch3/touch_00061.png differ diff --git a/Container/touch/touch3/touch_00062.png b/Container/touch/touch3/touch_00062.png new file mode 100644 index 0000000..be67f37 Binary files /dev/null and b/Container/touch/touch3/touch_00062.png differ diff --git a/Container/touch/touch3/touch_00063.png b/Container/touch/touch3/touch_00063.png new file mode 100644 index 0000000..09dffee Binary files /dev/null and b/Container/touch/touch3/touch_00063.png differ diff --git a/Container/touch/touch3/touch_00064.png b/Container/touch/touch3/touch_00064.png new file mode 100644 index 0000000..bc17eb0 Binary files /dev/null and b/Container/touch/touch3/touch_00064.png differ diff --git a/Container/touch/touch3/touch_00065.png b/Container/touch/touch3/touch_00065.png new file mode 100644 index 0000000..d0e5039 Binary files /dev/null and b/Container/touch/touch3/touch_00065.png differ diff --git a/Container/touch/touch3/touch_00066.png b/Container/touch/touch3/touch_00066.png new file mode 100644 index 0000000..3e7b4fc Binary files /dev/null and b/Container/touch/touch3/touch_00066.png differ diff --git a/Container/touch/touch3/touch_00067.png b/Container/touch/touch3/touch_00067.png new file mode 100644 index 0000000..99f3826 Binary files /dev/null and b/Container/touch/touch3/touch_00067.png differ diff --git a/Container/touch/touch3/touch_00068.png b/Container/touch/touch3/touch_00068.png new file mode 100644 index 0000000..e7c1755 Binary files /dev/null and b/Container/touch/touch3/touch_00068.png differ diff --git a/Container/touch/touch3/touch_00069.png b/Container/touch/touch3/touch_00069.png new file mode 100644 index 0000000..587c706 Binary files /dev/null and b/Container/touch/touch3/touch_00069.png differ diff --git a/Container/touch/touch3/touch_00070.png b/Container/touch/touch3/touch_00070.png new file mode 100644 index 0000000..a3de07f Binary files /dev/null and b/Container/touch/touch3/touch_00070.png differ diff --git a/Container/touch/touch3/touch_00071.png b/Container/touch/touch3/touch_00071.png new file mode 100644 index 0000000..bd87dac Binary files /dev/null and b/Container/touch/touch3/touch_00071.png differ diff --git a/Container/touch/touch3/touch_00072.png b/Container/touch/touch3/touch_00072.png new file mode 100644 index 0000000..b738253 Binary files /dev/null and b/Container/touch/touch3/touch_00072.png differ diff --git a/Container/touch/touch3/touch_00073.png b/Container/touch/touch3/touch_00073.png new file mode 100644 index 0000000..6221531 Binary files /dev/null and b/Container/touch/touch3/touch_00073.png differ diff --git a/Container/touch/touch3/touch_00074.png b/Container/touch/touch3/touch_00074.png new file mode 100644 index 0000000..655c64c Binary files /dev/null and b/Container/touch/touch3/touch_00074.png differ diff --git a/Container/touch/touch3/touch_00075.png b/Container/touch/touch3/touch_00075.png new file mode 100644 index 0000000..c5a277e Binary files /dev/null and b/Container/touch/touch3/touch_00075.png differ diff --git a/Container/touch/touch3/touch_00076.png b/Container/touch/touch3/touch_00076.png new file mode 100644 index 0000000..cd54f95 Binary files /dev/null and b/Container/touch/touch3/touch_00076.png differ diff --git a/Container/touch/touch3/touch_00077.png b/Container/touch/touch3/touch_00077.png new file mode 100644 index 0000000..12deb2e Binary files /dev/null and b/Container/touch/touch3/touch_00077.png differ diff --git a/Container/touch/touch3/touch_00078.png b/Container/touch/touch3/touch_00078.png new file mode 100644 index 0000000..fd088c2 Binary files /dev/null and b/Container/touch/touch3/touch_00078.png differ diff --git a/Container/touch/touch3/touch_00079.png b/Container/touch/touch3/touch_00079.png new file mode 100644 index 0000000..e5fcea7 Binary files /dev/null and b/Container/touch/touch3/touch_00079.png differ diff --git a/Container/touch/touch3/touch_00080.png b/Container/touch/touch3/touch_00080.png new file mode 100644 index 0000000..55992af Binary files /dev/null and b/Container/touch/touch3/touch_00080.png differ diff --git a/Container/touch/touch3/touch_00081.png b/Container/touch/touch3/touch_00081.png new file mode 100644 index 0000000..633e190 Binary files /dev/null and b/Container/touch/touch3/touch_00081.png differ diff --git a/Container/touch/touch3/touch_00082.png b/Container/touch/touch3/touch_00082.png new file mode 100644 index 0000000..2fe30a9 Binary files /dev/null and b/Container/touch/touch3/touch_00082.png differ diff --git a/Container/touch/touch3/touch_00083.png b/Container/touch/touch3/touch_00083.png new file mode 100644 index 0000000..ea0765b Binary files /dev/null and b/Container/touch/touch3/touch_00083.png differ diff --git a/Container/touch/touch3/touch_00084.png b/Container/touch/touch3/touch_00084.png new file mode 100644 index 0000000..6eed607 Binary files /dev/null and b/Container/touch/touch3/touch_00084.png differ diff --git a/Container/touch/touch3/touch_00085.png b/Container/touch/touch3/touch_00085.png new file mode 100644 index 0000000..0e6c037 Binary files /dev/null and b/Container/touch/touch3/touch_00085.png differ diff --git a/Container/touch/touch3/touch_00086.png b/Container/touch/touch3/touch_00086.png new file mode 100644 index 0000000..2a4242e Binary files /dev/null and b/Container/touch/touch3/touch_00086.png differ diff --git a/Container/touch/touch3/touch_00087.png b/Container/touch/touch3/touch_00087.png new file mode 100644 index 0000000..85da72a Binary files /dev/null and b/Container/touch/touch3/touch_00087.png differ diff --git a/Container/touch/touch3/touch_00088.png b/Container/touch/touch3/touch_00088.png new file mode 100644 index 0000000..802bcf4 Binary files /dev/null and b/Container/touch/touch3/touch_00088.png differ diff --git a/Container/touch/touch3/touch_00089.png b/Container/touch/touch3/touch_00089.png new file mode 100644 index 0000000..14cc182 Binary files /dev/null and b/Container/touch/touch3/touch_00089.png differ diff --git a/Container/touch/touch3/touch_00090.png b/Container/touch/touch3/touch_00090.png new file mode 100644 index 0000000..b2daa8d Binary files /dev/null and b/Container/touch/touch3/touch_00090.png differ diff --git a/Container/touch/touch3/touch_00091.png b/Container/touch/touch3/touch_00091.png new file mode 100644 index 0000000..027e0f5 Binary files /dev/null and b/Container/touch/touch3/touch_00091.png differ diff --git a/Container/touch/touch3/touch_00092.png b/Container/touch/touch3/touch_00092.png new file mode 100644 index 0000000..4aae3cb Binary files /dev/null and b/Container/touch/touch3/touch_00092.png differ diff --git a/Container/touch/touch3/touch_00093.png b/Container/touch/touch3/touch_00093.png new file mode 100644 index 0000000..9433576 Binary files /dev/null and b/Container/touch/touch3/touch_00093.png differ diff --git a/Container/touch/touch3/touch_00094.png b/Container/touch/touch3/touch_00094.png new file mode 100644 index 0000000..411deae Binary files /dev/null and b/Container/touch/touch3/touch_00094.png differ diff --git a/Container/touch/touch3/touch_00095.png b/Container/touch/touch3/touch_00095.png new file mode 100644 index 0000000..0292069 Binary files /dev/null and b/Container/touch/touch3/touch_00095.png differ diff --git a/Container/touch/touch3/touch_00096.png b/Container/touch/touch3/touch_00096.png new file mode 100644 index 0000000..c34fd8b Binary files /dev/null and b/Container/touch/touch3/touch_00096.png differ diff --git a/Container/touch/touch3/touch_00097.png b/Container/touch/touch3/touch_00097.png new file mode 100644 index 0000000..fe15545 Binary files /dev/null and b/Container/touch/touch3/touch_00097.png differ diff --git a/Container/touch/touch3/touch_00098.png b/Container/touch/touch3/touch_00098.png new file mode 100644 index 0000000..9e72889 Binary files /dev/null and b/Container/touch/touch3/touch_00098.png differ diff --git a/Container/touch/touch3/touch_00099.png b/Container/touch/touch3/touch_00099.png new file mode 100644 index 0000000..53e15c5 Binary files /dev/null and b/Container/touch/touch3/touch_00099.png differ diff --git a/Container/touch/touch4/touch_00000.png b/Container/touch/touch4/touch_00000.png new file mode 100644 index 0000000..6f9725a Binary files /dev/null and b/Container/touch/touch4/touch_00000.png differ diff --git a/Container/touch/touch4/touch_00001.png b/Container/touch/touch4/touch_00001.png new file mode 100644 index 0000000..6f9725a Binary files /dev/null and b/Container/touch/touch4/touch_00001.png differ diff --git a/Container/touch/touch4/touch_00002.png b/Container/touch/touch4/touch_00002.png new file mode 100644 index 0000000..e217ce3 Binary files /dev/null and b/Container/touch/touch4/touch_00002.png differ diff --git a/Container/touch/touch4/touch_00003.png b/Container/touch/touch4/touch_00003.png new file mode 100644 index 0000000..8c6e621 Binary files /dev/null and b/Container/touch/touch4/touch_00003.png differ diff --git a/Container/touch/touch4/touch_00004.png b/Container/touch/touch4/touch_00004.png new file mode 100644 index 0000000..c716630 Binary files /dev/null and b/Container/touch/touch4/touch_00004.png differ diff --git a/Container/touch/touch4/touch_00005.png b/Container/touch/touch4/touch_00005.png new file mode 100644 index 0000000..0d90121 Binary files /dev/null and b/Container/touch/touch4/touch_00005.png differ diff --git a/Container/touch/touch4/touch_00006.png b/Container/touch/touch4/touch_00006.png new file mode 100644 index 0000000..bceec15 Binary files /dev/null and b/Container/touch/touch4/touch_00006.png differ diff --git a/Container/touch/touch4/touch_00007.png b/Container/touch/touch4/touch_00007.png new file mode 100644 index 0000000..91aa3c7 Binary files /dev/null and b/Container/touch/touch4/touch_00007.png differ diff --git a/Container/touch/touch4/touch_00008.png b/Container/touch/touch4/touch_00008.png new file mode 100644 index 0000000..eccc155 Binary files /dev/null and b/Container/touch/touch4/touch_00008.png differ diff --git a/Container/touch/touch4/touch_00009.png b/Container/touch/touch4/touch_00009.png new file mode 100644 index 0000000..31c67a4 Binary files /dev/null and b/Container/touch/touch4/touch_00009.png differ diff --git a/Container/touch/touch4/touch_00010.png b/Container/touch/touch4/touch_00010.png new file mode 100644 index 0000000..275c4dc Binary files /dev/null and b/Container/touch/touch4/touch_00010.png differ diff --git a/Container/touch/touch4/touch_00011.png b/Container/touch/touch4/touch_00011.png new file mode 100644 index 0000000..908abbb Binary files /dev/null and b/Container/touch/touch4/touch_00011.png differ diff --git a/Container/touch/touch4/touch_00012.png b/Container/touch/touch4/touch_00012.png new file mode 100644 index 0000000..5b90ac9 Binary files /dev/null and b/Container/touch/touch4/touch_00012.png differ diff --git a/Container/touch/touch4/touch_00013.png b/Container/touch/touch4/touch_00013.png new file mode 100644 index 0000000..6812897 Binary files /dev/null and b/Container/touch/touch4/touch_00013.png differ diff --git a/Container/touch/touch4/touch_00014.png b/Container/touch/touch4/touch_00014.png new file mode 100644 index 0000000..99a8e00 Binary files /dev/null and b/Container/touch/touch4/touch_00014.png differ diff --git a/Container/touch/touch4/touch_00015.png b/Container/touch/touch4/touch_00015.png new file mode 100644 index 0000000..bc22dcb Binary files /dev/null and b/Container/touch/touch4/touch_00015.png differ diff --git a/Container/touch/touch4/touch_00016.png b/Container/touch/touch4/touch_00016.png new file mode 100644 index 0000000..11bec82 Binary files /dev/null and b/Container/touch/touch4/touch_00016.png differ diff --git a/Container/touch/touch4/touch_00017.png b/Container/touch/touch4/touch_00017.png new file mode 100644 index 0000000..d3c98d0 Binary files /dev/null and b/Container/touch/touch4/touch_00017.png differ diff --git a/Container/touch/touch4/touch_00018.png b/Container/touch/touch4/touch_00018.png new file mode 100644 index 0000000..7a295fc Binary files /dev/null and b/Container/touch/touch4/touch_00018.png differ diff --git a/Container/touch/touch4/touch_00019.png b/Container/touch/touch4/touch_00019.png new file mode 100644 index 0000000..c6f035b Binary files /dev/null and b/Container/touch/touch4/touch_00019.png differ diff --git a/Container/touch/touch4/touch_00020.png b/Container/touch/touch4/touch_00020.png new file mode 100644 index 0000000..fbfb53f Binary files /dev/null and b/Container/touch/touch4/touch_00020.png differ diff --git a/Container/touch/touch4/touch_00021.png b/Container/touch/touch4/touch_00021.png new file mode 100644 index 0000000..d2592b0 Binary files /dev/null and b/Container/touch/touch4/touch_00021.png differ diff --git a/Container/touch/touch4/touch_00022.png b/Container/touch/touch4/touch_00022.png new file mode 100644 index 0000000..bbb8302 Binary files /dev/null and b/Container/touch/touch4/touch_00022.png differ diff --git a/Container/touch/touch4/touch_00023.png b/Container/touch/touch4/touch_00023.png new file mode 100644 index 0000000..7963217 Binary files /dev/null and b/Container/touch/touch4/touch_00023.png differ diff --git a/Container/touch/touch4/touch_00024.png b/Container/touch/touch4/touch_00024.png new file mode 100644 index 0000000..0e5d391 Binary files /dev/null and b/Container/touch/touch4/touch_00024.png differ diff --git a/Container/touch/touch4/touch_00025.png b/Container/touch/touch4/touch_00025.png new file mode 100644 index 0000000..68684ba Binary files /dev/null and b/Container/touch/touch4/touch_00025.png differ diff --git a/Container/touch/touch4/touch_00026.png b/Container/touch/touch4/touch_00026.png new file mode 100644 index 0000000..c433482 Binary files /dev/null and b/Container/touch/touch4/touch_00026.png differ diff --git a/Container/touch/touch4/touch_00027.png b/Container/touch/touch4/touch_00027.png new file mode 100644 index 0000000..9dcb1cc Binary files /dev/null and b/Container/touch/touch4/touch_00027.png differ diff --git a/Container/touch/touch4/touch_00028.png b/Container/touch/touch4/touch_00028.png new file mode 100644 index 0000000..0f28492 Binary files /dev/null and b/Container/touch/touch4/touch_00028.png differ diff --git a/Container/touch/touch4/touch_00029.png b/Container/touch/touch4/touch_00029.png new file mode 100644 index 0000000..cfb9e97 Binary files /dev/null and b/Container/touch/touch4/touch_00029.png differ diff --git a/Container/touch/touch4/touch_00030.png b/Container/touch/touch4/touch_00030.png new file mode 100644 index 0000000..d197aa7 Binary files /dev/null and b/Container/touch/touch4/touch_00030.png differ diff --git a/Container/touch/touch4/touch_00031.png b/Container/touch/touch4/touch_00031.png new file mode 100644 index 0000000..475a96f Binary files /dev/null and b/Container/touch/touch4/touch_00031.png differ diff --git a/Container/touch/touch4/touch_00032.png b/Container/touch/touch4/touch_00032.png new file mode 100644 index 0000000..9483076 Binary files /dev/null and b/Container/touch/touch4/touch_00032.png differ diff --git a/Container/touch/touch4/touch_00033.png b/Container/touch/touch4/touch_00033.png new file mode 100644 index 0000000..2e4bc3e Binary files /dev/null and b/Container/touch/touch4/touch_00033.png differ diff --git a/Container/touch/touch4/touch_00034.png b/Container/touch/touch4/touch_00034.png new file mode 100644 index 0000000..8ca5775 Binary files /dev/null and b/Container/touch/touch4/touch_00034.png differ diff --git a/Container/touch/touch4/touch_00035.png b/Container/touch/touch4/touch_00035.png new file mode 100644 index 0000000..6d5f975 Binary files /dev/null and b/Container/touch/touch4/touch_00035.png differ diff --git a/Container/touch/touch4/touch_00036.png b/Container/touch/touch4/touch_00036.png new file mode 100644 index 0000000..c6709a4 Binary files /dev/null and b/Container/touch/touch4/touch_00036.png differ diff --git a/Container/touch/touch4/touch_00037.png b/Container/touch/touch4/touch_00037.png new file mode 100644 index 0000000..263a863 Binary files /dev/null and b/Container/touch/touch4/touch_00037.png differ diff --git a/Container/touch/touch4/touch_00038.png b/Container/touch/touch4/touch_00038.png new file mode 100644 index 0000000..a94bdf4 Binary files /dev/null and b/Container/touch/touch4/touch_00038.png differ diff --git a/Container/touch/touch4/touch_00039.png b/Container/touch/touch4/touch_00039.png new file mode 100644 index 0000000..1792582 Binary files /dev/null and b/Container/touch/touch4/touch_00039.png differ diff --git a/Container/touch/touch4/touch_00040.png b/Container/touch/touch4/touch_00040.png new file mode 100644 index 0000000..da39957 Binary files /dev/null and b/Container/touch/touch4/touch_00040.png differ diff --git a/Container/touch/touch4/touch_00041.png b/Container/touch/touch4/touch_00041.png new file mode 100644 index 0000000..f0fded1 Binary files /dev/null and b/Container/touch/touch4/touch_00041.png differ diff --git a/Container/touch/touch4/touch_00042.png b/Container/touch/touch4/touch_00042.png new file mode 100644 index 0000000..ecbb897 Binary files /dev/null and b/Container/touch/touch4/touch_00042.png differ diff --git a/Container/touch/touch4/touch_00043.png b/Container/touch/touch4/touch_00043.png new file mode 100644 index 0000000..6ad4e79 Binary files /dev/null and b/Container/touch/touch4/touch_00043.png differ diff --git a/Container/touch/touch4/touch_00044.png b/Container/touch/touch4/touch_00044.png new file mode 100644 index 0000000..0b208d2 Binary files /dev/null and b/Container/touch/touch4/touch_00044.png differ diff --git a/Container/touch/touch4/touch_00045.png b/Container/touch/touch4/touch_00045.png new file mode 100644 index 0000000..9e8ffc2 Binary files /dev/null and b/Container/touch/touch4/touch_00045.png differ diff --git a/Container/touch/touch4/touch_00046.png b/Container/touch/touch4/touch_00046.png new file mode 100644 index 0000000..a714f28 Binary files /dev/null and b/Container/touch/touch4/touch_00046.png differ diff --git a/Container/touch/touch4/touch_00047.png b/Container/touch/touch4/touch_00047.png new file mode 100644 index 0000000..a30b922 Binary files /dev/null and b/Container/touch/touch4/touch_00047.png differ diff --git a/Container/touch/touch4/touch_00048.png b/Container/touch/touch4/touch_00048.png new file mode 100644 index 0000000..dc9b253 Binary files /dev/null and b/Container/touch/touch4/touch_00048.png differ diff --git a/Container/touch/touch4/touch_00049.png b/Container/touch/touch4/touch_00049.png new file mode 100644 index 0000000..2dfbc5d Binary files /dev/null and b/Container/touch/touch4/touch_00049.png differ diff --git a/Container/touch/touch4/touch_00050.png b/Container/touch/touch4/touch_00050.png new file mode 100644 index 0000000..3fd5d85 Binary files /dev/null and b/Container/touch/touch4/touch_00050.png differ diff --git a/Container/touch/touch4/touch_00051.png b/Container/touch/touch4/touch_00051.png new file mode 100644 index 0000000..9aee307 Binary files /dev/null and b/Container/touch/touch4/touch_00051.png differ diff --git a/Container/touch/touch4/touch_00052.png b/Container/touch/touch4/touch_00052.png new file mode 100644 index 0000000..10e9ab3 Binary files /dev/null and b/Container/touch/touch4/touch_00052.png differ diff --git a/Container/touch/touch4/touch_00053.png b/Container/touch/touch4/touch_00053.png new file mode 100644 index 0000000..38e9ba4 Binary files /dev/null and b/Container/touch/touch4/touch_00053.png differ diff --git a/Container/touch/touch4/touch_00054.png b/Container/touch/touch4/touch_00054.png new file mode 100644 index 0000000..76066ad Binary files /dev/null and b/Container/touch/touch4/touch_00054.png differ diff --git a/Container/touch/touch4/touch_00055.png b/Container/touch/touch4/touch_00055.png new file mode 100644 index 0000000..e118694 Binary files /dev/null and b/Container/touch/touch4/touch_00055.png differ diff --git a/Container/touch/touch4/touch_00056.png b/Container/touch/touch4/touch_00056.png new file mode 100644 index 0000000..6d51842 Binary files /dev/null and b/Container/touch/touch4/touch_00056.png differ diff --git a/Container/touch/touch4/touch_00057.png b/Container/touch/touch4/touch_00057.png new file mode 100644 index 0000000..811c8a4 Binary files /dev/null and b/Container/touch/touch4/touch_00057.png differ diff --git a/Container/touch/touch4/touch_00058.png b/Container/touch/touch4/touch_00058.png new file mode 100644 index 0000000..10d1b70 Binary files /dev/null and b/Container/touch/touch4/touch_00058.png differ diff --git a/Container/touch/touch4/touch_00059.png b/Container/touch/touch4/touch_00059.png new file mode 100644 index 0000000..54ece3b Binary files /dev/null and b/Container/touch/touch4/touch_00059.png differ diff --git a/Container/touch/touch4/touch_00060.png b/Container/touch/touch4/touch_00060.png new file mode 100644 index 0000000..49be1f9 Binary files /dev/null and b/Container/touch/touch4/touch_00060.png differ diff --git a/Container/touch/touch4/touch_00061.png b/Container/touch/touch4/touch_00061.png new file mode 100644 index 0000000..0ccf36f Binary files /dev/null and b/Container/touch/touch4/touch_00061.png differ diff --git a/Container/touch/touch4/touch_00062.png b/Container/touch/touch4/touch_00062.png new file mode 100644 index 0000000..43cca93 Binary files /dev/null and b/Container/touch/touch4/touch_00062.png differ diff --git a/Container/touch/touch4/touch_00063.png b/Container/touch/touch4/touch_00063.png new file mode 100644 index 0000000..2436984 Binary files /dev/null and b/Container/touch/touch4/touch_00063.png differ diff --git a/Container/touch/touch4/touch_00064.png b/Container/touch/touch4/touch_00064.png new file mode 100644 index 0000000..531d312 Binary files /dev/null and b/Container/touch/touch4/touch_00064.png differ diff --git a/Container/touch/touch4/touch_00065.png b/Container/touch/touch4/touch_00065.png new file mode 100644 index 0000000..653ddf5 Binary files /dev/null and b/Container/touch/touch4/touch_00065.png differ diff --git a/Container/touch/touch4/touch_00066.png b/Container/touch/touch4/touch_00066.png new file mode 100644 index 0000000..756504d Binary files /dev/null and b/Container/touch/touch4/touch_00066.png differ diff --git a/Container/touch/touch4/touch_00067.png b/Container/touch/touch4/touch_00067.png new file mode 100644 index 0000000..0682282 Binary files /dev/null and b/Container/touch/touch4/touch_00067.png differ diff --git a/Container/touch/touch4/touch_00068.png b/Container/touch/touch4/touch_00068.png new file mode 100644 index 0000000..d815a5e Binary files /dev/null and b/Container/touch/touch4/touch_00068.png differ diff --git a/Container/touch/touch4/touch_00069.png b/Container/touch/touch4/touch_00069.png new file mode 100644 index 0000000..cfd5874 Binary files /dev/null and b/Container/touch/touch4/touch_00069.png differ diff --git a/Container/touch/touch4/touch_00070.png b/Container/touch/touch4/touch_00070.png new file mode 100644 index 0000000..08d4921 Binary files /dev/null and b/Container/touch/touch4/touch_00070.png differ diff --git a/Container/touch/touch4/touch_00071.png b/Container/touch/touch4/touch_00071.png new file mode 100644 index 0000000..dfe2734 Binary files /dev/null and b/Container/touch/touch4/touch_00071.png differ diff --git a/Container/touch/touch4/touch_00072.png b/Container/touch/touch4/touch_00072.png new file mode 100644 index 0000000..46c5a8d Binary files /dev/null and b/Container/touch/touch4/touch_00072.png differ diff --git a/Container/touch/touch4/touch_00073.png b/Container/touch/touch4/touch_00073.png new file mode 100644 index 0000000..2dfcd79 Binary files /dev/null and b/Container/touch/touch4/touch_00073.png differ diff --git a/Container/touch/touch4/touch_00074.png b/Container/touch/touch4/touch_00074.png new file mode 100644 index 0000000..aed2202 Binary files /dev/null and b/Container/touch/touch4/touch_00074.png differ diff --git a/Container/touch/touch4/touch_00075.png b/Container/touch/touch4/touch_00075.png new file mode 100644 index 0000000..7909bcb Binary files /dev/null and b/Container/touch/touch4/touch_00075.png differ diff --git a/Container/touch/touch4/touch_00076.png b/Container/touch/touch4/touch_00076.png new file mode 100644 index 0000000..c5fd448 Binary files /dev/null and b/Container/touch/touch4/touch_00076.png differ diff --git a/Container/touch/touch4/touch_00077.png b/Container/touch/touch4/touch_00077.png new file mode 100644 index 0000000..a337c5a Binary files /dev/null and b/Container/touch/touch4/touch_00077.png differ diff --git a/Container/touch/touch4/touch_00078.png b/Container/touch/touch4/touch_00078.png new file mode 100644 index 0000000..aa0653b Binary files /dev/null and b/Container/touch/touch4/touch_00078.png differ diff --git a/Container/touch/touch4/touch_00079.png b/Container/touch/touch4/touch_00079.png new file mode 100644 index 0000000..c0df186 Binary files /dev/null and b/Container/touch/touch4/touch_00079.png differ diff --git a/Container/touch/touch4/touch_00080.png b/Container/touch/touch4/touch_00080.png new file mode 100644 index 0000000..86c9fe6 Binary files /dev/null and b/Container/touch/touch4/touch_00080.png differ diff --git a/Container/touch/touch4/touch_00081.png b/Container/touch/touch4/touch_00081.png new file mode 100644 index 0000000..91434ad Binary files /dev/null and b/Container/touch/touch4/touch_00081.png differ diff --git a/Container/touch/touch4/touch_00082.png b/Container/touch/touch4/touch_00082.png new file mode 100644 index 0000000..22c6078 Binary files /dev/null and b/Container/touch/touch4/touch_00082.png differ diff --git a/Container/touch/touch4/touch_00083.png b/Container/touch/touch4/touch_00083.png new file mode 100644 index 0000000..9ba3b3e Binary files /dev/null and b/Container/touch/touch4/touch_00083.png differ diff --git a/Container/touch/touch4/touch_00084.png b/Container/touch/touch4/touch_00084.png new file mode 100644 index 0000000..2df2c96 Binary files /dev/null and b/Container/touch/touch4/touch_00084.png differ diff --git a/Container/touch/touch4/touch_00085.png b/Container/touch/touch4/touch_00085.png new file mode 100644 index 0000000..02542b2 Binary files /dev/null and b/Container/touch/touch4/touch_00085.png differ diff --git a/Container/touch/touch4/touch_00086.png b/Container/touch/touch4/touch_00086.png new file mode 100644 index 0000000..88dc3b3 Binary files /dev/null and b/Container/touch/touch4/touch_00086.png differ diff --git a/Container/touch/touch4/touch_00087.png b/Container/touch/touch4/touch_00087.png new file mode 100644 index 0000000..ae2f2a4 Binary files /dev/null and b/Container/touch/touch4/touch_00087.png differ diff --git a/Container/touch/touch4/touch_00088.png b/Container/touch/touch4/touch_00088.png new file mode 100644 index 0000000..02c93f4 Binary files /dev/null and b/Container/touch/touch4/touch_00088.png differ diff --git a/Container/touch/touch4/touch_00089.png b/Container/touch/touch4/touch_00089.png new file mode 100644 index 0000000..54377f1 Binary files /dev/null and b/Container/touch/touch4/touch_00089.png differ diff --git a/Container/touch/touch4/touch_00090.png b/Container/touch/touch4/touch_00090.png new file mode 100644 index 0000000..1dd103d Binary files /dev/null and b/Container/touch/touch4/touch_00090.png differ diff --git a/Container/touch/touch4/touch_00091.png b/Container/touch/touch4/touch_00091.png new file mode 100644 index 0000000..e95772f Binary files /dev/null and b/Container/touch/touch4/touch_00091.png differ diff --git a/Container/touch/touch4/touch_00092.png b/Container/touch/touch4/touch_00092.png new file mode 100644 index 0000000..4291fa2 Binary files /dev/null and b/Container/touch/touch4/touch_00092.png differ diff --git a/Container/touch/touch4/touch_00093.png b/Container/touch/touch4/touch_00093.png new file mode 100644 index 0000000..9258821 Binary files /dev/null and b/Container/touch/touch4/touch_00093.png differ diff --git a/Container/touch/touch4/touch_00094.png b/Container/touch/touch4/touch_00094.png new file mode 100644 index 0000000..394189c Binary files /dev/null and b/Container/touch/touch4/touch_00094.png differ diff --git a/Container/touch/touch4/touch_00095.png b/Container/touch/touch4/touch_00095.png new file mode 100644 index 0000000..5a7a6a3 Binary files /dev/null and b/Container/touch/touch4/touch_00095.png differ diff --git a/Container/touch/touch4/touch_00096.png b/Container/touch/touch4/touch_00096.png new file mode 100644 index 0000000..9592725 Binary files /dev/null and b/Container/touch/touch4/touch_00096.png differ diff --git a/Container/touch/touch4/touch_00097.png b/Container/touch/touch4/touch_00097.png new file mode 100644 index 0000000..dcacf98 Binary files /dev/null and b/Container/touch/touch4/touch_00097.png differ diff --git a/Container/touch/touch4/touch_00098.png b/Container/touch/touch4/touch_00098.png new file mode 100644 index 0000000..1f02ee1 Binary files /dev/null and b/Container/touch/touch4/touch_00098.png differ diff --git a/Container/touch/touch4/touch_00099.png b/Container/touch/touch4/touch_00099.png new file mode 100644 index 0000000..5719b0a Binary files /dev/null and b/Container/touch/touch4/touch_00099.png differ diff --git a/ProgControl.xaml.cs b/ProgControl.xaml.cs new file mode 100644 index 0000000..1e196d0 --- /dev/null +++ b/ProgControl.xaml.cs @@ -0,0 +1,771 @@ +using CefSharp.Wpf; +using Container.Business; +using Container.ChildWindows; +using Container.Common; +using Container.Model; +using Newtonsoft.Json.Linq; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Data; +using System.Windows.Documents; +using System.Windows.Input; +using System.Windows.Media; +using System.Windows.Media.Animation; +using System.Windows.Media.Imaging; +using System.Windows.Navigation; +using System.Windows.Shapes; +using Vlc.DotNet.Wpf; + +namespace Container.Win +{ + /// + /// ProgControl.xaml 的交互逻辑 + /// + public partial class ProgControl : UserControl + { + string outLinePath; + App app = ((App)System.Windows.Application.Current); + DirectoryInfo vlcLibDirectory; + backgroundMaterialInfo backgroundMaterial; + string backgroundColor; + List components; + private Thread th1;//播放屏保的线程 + bool isStop = false; + BrushConverter converter = new BrushConverter(); + List tasks = new List(); + List marqueeControlNews = new List(); + List clockControls = new List(); + List weatherControls = new List(); + List imageControls = new List(); + List mediaControls = new List(); + List chromiumWebBrowsers = new List(); + List canvasWebBrowsers = new List(); + VlcControl vlcControl1 = new VlcControl(); + VlcControl vlcControl2 = new VlcControl(); + string vlcVideoPath = string.Empty; + string vlcVideo2Path = string.Empty; + List cancellationTokens = new List(); + string[] options; + public ProgControl() + { + InitializeComponent(); + var currentAssembly = Assembly.GetEntryAssembly(); + var currentDirectory = new FileInfo(currentAssembly.Location).DirectoryName; + // Default installation path of VideoLAN.LibVLC.Windows + vlcLibDirectory = new DirectoryInfo(currentDirectory); + //初始化配置,指定引用库 + vlcControl1.SourceProvider.CreatePlayer(vlcLibDirectory); + //初始化配置,指定引用库 + vlcControl2.SourceProvider.CreatePlayer(vlcLibDirectory); + // options = new string[]{ + // "-I", + //"dummy", + //"--ignore-config", + //"--extraintf=logger", + //"--verbose=2", + //"--fullscreen", + //"--network-caching=300", + //"--live-caching=300", + //"--sout-mux-caching=300", + //"--file-caching=300", + //"--codec=mediacodec,iomx,all", + //"--quiet-synchro", + //" --clock-synchro=300", + //"--network-synchronisation", + //"--cr-average=10000" + // }; + options = new string[] { "-I", "dummy", "--network-caching=<300", ":sout=#transcode{vcodec=h264,acodec=mpga,ab=128,channels=2,samplerate=44100" }; + + canvas.Children.Add(vlcControl1); + canvas.Children.Add(vlcControl2); + } + + private void MediaPlayer_EndReached(object sender, Vlc.DotNet.Core.VlcMediaPlayerEndReachedEventArgs e) + { + Task.Factory.StartNew(() => { + //this.sourceProvider = null; + Application.Current.Dispatcher.BeginInvoke(new Action(() => { + vlcControl1.SourceProvider.MediaPlayer.Play(vlcVideoPath); + })); + }); + + } + + private void MediaPlayer2_EndReached(object sender, Vlc.DotNet.Core.VlcMediaPlayerEndReachedEventArgs e) + { + Task.Factory.StartNew(() => { + //this.sourceProvider = null; + Application.Current.Dispatcher.BeginInvoke(new Action(() => { + vlcControl2.SourceProvider.MediaPlayer.Play(vlcVideo2Path); + })); + }); + + } + + public void LoadProg(double width, double height, backgroundMaterialInfo backgroundmaterial, string backgroundcolor, List componentList) + { + backgroundMaterial = backgroundmaterial; + backgroundColor = backgroundcolor; + components = componentList; + this.Width = width; + this.Height = height; + canvas.Width = width; + canvas.Height = height; + try + { + outLinePath = AppDomain.CurrentDomain.BaseDirectory + "/OutlineFiles"; + if (backgroundMaterial != null) + { + string fileExtension = string.Empty; + if (backgroundMaterial.filePath.Contains("?")) + { + fileExtension = backgroundMaterial.filePath.Substring(backgroundMaterial.filePath.LastIndexOf("."), backgroundMaterial.filePath.LastIndexOf("?") - backgroundMaterial.filePath.LastIndexOf(".")).ToLower(); + } + else + { + fileExtension = backgroundMaterial.filePath.Substring(backgroundMaterial.filePath.LastIndexOf(".")).ToLower(); + } + string url = outLinePath + "/Main/" + backgroundMaterial.fileHash + fileExtension; + if (File.Exists(url)) + { + Image image = new Image();//新建图片对象 + image.Source = new BitmapImage(new Uri(url));//读取图片 + ImageBrush ib = new ImageBrush();//新建图片对象 + ib.ImageSource = image.Source;//赋值为背景图片 + canvas.Background = ib;//将图片对象赋值给Canvas的Background + } + + } + else if (!string.IsNullOrEmpty(backgroundColor)) + { + Color color = (Color)ColorConverter.ConvertFromString(backgroundColor); + canvas.Background = new SolidColorBrush(color); + } + + int vlcCount = 0; + + isStop = false; + foreach (var item in components) + { + if ((item.materials == null || item.materials.Count == 0) && (item.typeCode == "text" || item.typeCode == "image" || item.typeCode == "video"||item.typeCode== "audio" || item.typeCode == "html" || item.typeCode == "url")) + { + continue; + } + if (item.typeCode == "image") + { + Image image = new Image(); + image.Width = item.width; + image.Height = item.height; + imageControls.Add(image); + canvas.Children.Add(image); + Canvas.SetLeft(image, item.offsetX); + Canvas.SetZIndex(image, item.zIndex); + Canvas.SetTop(image, item.offsetY); + image.Stretch = Stretch.Fill; + PlayImage(image, item.materials, item.config); + } + if (item.typeCode == "video") + { + vlcCount++; + if (vlcCount == 1) + { + vlcControl1.Width = item.width; + vlcControl1.Height = item.height; + Canvas.SetLeft(vlcControl1, item.offsetX); + Canvas.SetZIndex(vlcControl1, item.zIndex); + Canvas.SetTop(vlcControl1, item.offsetY); + PlayVideo(vlcControl1, item.materials, item.config, 1); + } + else + { + vlcControl2.Width = item.width; + vlcControl2.Height = item.height; + Canvas.SetLeft(vlcControl2, item.offsetX); + Canvas.SetZIndex(vlcControl2, item.zIndex); + Canvas.SetTop(vlcControl2, item.offsetY); + PlayVideo(vlcControl2, item.materials, item.config, 2); + } + + } + if (item.typeCode == "text" && item.materials != null && item.materials.Count > 0) + { + var textBackgroundColor = item.config.Value("backgroundColor"); + var textBackgroundOpacity = item.config.Value("backgroundOpacity"); + var textFontColor = item.config.Value("fontColor"); + var textFontSize = item.config.Value("fontSize"); + var textFontStyle = item.config.Value("fontStyle"); + var textAnimationSpeed = item.config.Value("animationSpeed"); + + string fileExtension = string.Empty; + string url = string.Empty; + if (item.materials[0].fileUrl.Contains("?")) + { + fileExtension = item.materials[0].fileUrl.Substring(item.materials[0].fileUrl.LastIndexOf("."), item.materials[0].fileUrl.LastIndexOf("?") - item.materials[0].fileUrl.LastIndexOf(".")).ToLower(); + } + else + { + fileExtension = item.materials[0].fileUrl.Substring(item.materials[0].fileUrl.LastIndexOf(".")).ToLower(); + } + url = outLinePath + "/Main/" + item.materials[0].fileHash + fileExtension; + string textContent = DownLoadMethod.ReadContext(url); + textContent = textContent.Replace("\r\n", " "); + MarqueeControlNew marqueeControlNew = new MarqueeControlNew(); + marqueeControlNew.Load(textContent, item.width, item.height, textFontSize, textBackgroundColor, textBackgroundOpacity, textFontColor, textFontStyle, textAnimationSpeed); + canvas.Children.Add(marqueeControlNew); + marqueeControlNews.Add(marqueeControlNew); + Canvas.SetLeft(marqueeControlNew, item.offsetX); + Canvas.SetZIndex(marqueeControlNew, item.zIndex); + Canvas.SetTop(marqueeControlNew, item.offsetY); + } + if (item.typeCode == "clock") + { + var backgroundColor = item.config.Value("backgroundColor"); + var fontColor = item.config.Value("fontColor"); + var style = item.config.Value("style"); + ClockControl clock = new ClockControl(); + clock.BindClock(style.Value, item.width, item.height, backgroundColor, fontColor); + canvas.Children.Add(clock); + clockControls.Add(clock); + Canvas.SetLeft(clock, item.offsetX); + Canvas.SetZIndex(clock, item.zIndex); + Canvas.SetTop(clock, item.offsetY); + } + if (item.typeCode == "weather") + { + var backgroundColor = item.config.Value("backgroundColor"); + var fontColor = item.config.Value("fontColor"); + var style = item.config.Value("style"); + var city = item.config.Value("cityName"); + if (string.IsNullOrEmpty(city)) + { + city = app.defaultCity; + } + if (!string.IsNullOrEmpty(city)) + { + WeatherControl weather = new WeatherControl(); + weather.LoadWeather(city, style.Value, item.width, item.height, backgroundColor, fontColor); + canvas.Children.Add(weather); + weatherControls.Add(weather); + Canvas.SetLeft(weather, item.offsetX); + Canvas.SetZIndex(weather, item.zIndex); + Canvas.SetTop(weather, item.offsetY); + } + } + if (item.typeCode == "audio" && item.materials != null && item.materials.Count > 0) + { + MediaPlayer media = new MediaPlayer(); + string fileExtension = string.Empty; + string url = string.Empty; + if (item.materials[0].fileUrl.Contains("?")) + { + fileExtension = item.materials[0].fileUrl.Substring(item.materials[0].fileUrl.LastIndexOf("."), item.materials[0].fileUrl.LastIndexOf("?") - item.materials[0].fileUrl.LastIndexOf(".")).ToLower(); + } + else + { + fileExtension = item.materials[0].fileUrl.Substring(item.materials[0].fileUrl.LastIndexOf(".")).ToLower(); + } + url = outLinePath + "/Main/" + item.materials[0].fileHash + fileExtension; + media.Open(new Uri(url, UriKind.Relative)); + media.MediaEnded += (sender, e) => + {//播放结束后 又重新播放 + media.Position = new TimeSpan(0); + }; + media.Play(); + mediaControls.Add(media); + } + if (item.typeCode == "html" && item.materials != null && item.materials.Count > 0) + { + string fileExtension = string.Empty; + string url = string.Empty; + if (item.materials[0].fileUrl.Contains("?")) + { + fileExtension = item.materials[0].fileUrl.Substring(item.materials[0].fileUrl.LastIndexOf("."), item.materials[0].fileUrl.LastIndexOf("?") - item.materials[0].fileUrl.LastIndexOf(".")).ToLower(); + } + else + { + fileExtension = item.materials[0].fileUrl.Substring(item.materials[0].fileUrl.LastIndexOf(".")).ToLower(); + } + url = outLinePath + "/Main/" + item.materials[0].fileHash + fileExtension; + ChromiumWebBrowser webBrowser = new ChromiumWebBrowser(); + webBrowser.Width = item.width; + webBrowser.Height = item.height; + webBrowser.Address = url.Replace(@"/", @"\").Replace(@"\\",@"\") ; + //webBrowser.Address = "file:///D:/360MoveData/Users/jiaxl/Desktop/Websocket.html"; + webBrowser.Background = Brushes.Black; + Canvas canvas1 = new Canvas(); + canvas1.Width = item.width; + canvas1.Height = item.height; + canvas1.Background = Brushes.White; + canvas1.Children.Add(webBrowser); + //webBrowser.Load(url); + canvas.Children.Add(canvas1); + canvasWebBrowsers.Add(canvas1); + chromiumWebBrowsers.Add(webBrowser); + Canvas.SetLeft(canvas1, item.offsetX); + Canvas.SetZIndex(canvas1, item.zIndex); + Canvas.SetTop(canvas1, item.offsetY); + } + if (item.typeCode == "url" && item.materials != null && item.materials.Count > 0 && item.materials[0].mediaInfo != null && !string.IsNullOrEmpty(item.materials[0].mediaInfo.url)) + { + ChromiumWebBrowser webBrowser = new ChromiumWebBrowser(); + webBrowser.Width = item.width; + webBrowser.Height = item.height; + webBrowser.Address = item.materials[0].mediaInfo.url; + webBrowser.Background = Brushes.Black; + Canvas canvas1 = new Canvas(); + canvas1.Width = item.width; + canvas1.Height = item.height; + canvas1.Background = Brushes.White; + canvas1.Children.Add(webBrowser); + //webBrowser.Load(url); + canvas.Children.Add(canvas1); + canvasWebBrowsers.Add(canvas1); + chromiumWebBrowsers.Add(webBrowser); + Canvas.SetLeft(canvas1, item.offsetX); + Canvas.SetZIndex(canvas1, item.zIndex); + Canvas.SetTop(canvas1, item.offsetY); + } + } + + } + catch (Exception ex) + { + + Class_Log _Log = new Class_Log(); + _Log.WriteLogFile(ex.ToString()); + } + } + + //private void PlayImage(Image image, List materials, JObject config) + //{ + // CancellationTokenSource source1 = new CancellationTokenSource(); + // cancellationTokens.Add(source1); + // CancellationToken token = source1.Token; + // TaskFactory factory = new TaskFactory(token); + // Task tsk1 = factory.StartNew(() => + // { + // var curPlayIndex = 0; + // var transitionPeriod = config.Value("transitionPeriod"); + // var transition = config.Value("transition"); + // string fileExtension = string.Empty; + // string url = string.Empty; + // DateTime? curDate = null; + // while (!isStop) + // { + // if (token.IsCancellationRequested) + // { + // //isStop = true; + // // 释放资源操作等等... + // break; + // } + // if (!curDate.HasValue||curDate.Value.AddMilliseconds(transitionPeriod * 1000) <= DateTime.Now) + // { + // if (materials[curPlayIndex].fileUrl.Contains("?")) + // { + // fileExtension = materials[curPlayIndex].fileUrl.Substring(materials[curPlayIndex].fileUrl.LastIndexOf("."), materials[curPlayIndex].fileUrl.LastIndexOf("?") - materials[curPlayIndex].fileUrl.LastIndexOf(".")).ToLower(); + // } + // else + // { + // fileExtension = materials[curPlayIndex].fileUrl.Substring(materials[curPlayIndex].fileUrl.LastIndexOf(".")).ToLower(); + // } + // curDate = DateTime.Now; + // url = outLinePath + "/Main/" + materials[curPlayIndex].fileHash + fileExtension; + // BindImage(image, url, transition); + // curPlayIndex++; + // if (curPlayIndex >= materials.Count) + // { + // curPlayIndex = 0; + // } + // } + // else + // { + // Thread.Sleep(1); + // } + // } + // }); + // //var thImage = new Thread(new ThreadStart(async () => + // //{ + // // var curPlayIndex = 0; + // // var transitionPeriod = config.Value("transitionPeriod"); + // // var transition = config.Value("transition"); + // // string fileExtension = string.Empty; + // // string url = string.Empty; + // // while (!isStop) + // // { + + // // if (materials[curPlayIndex].fileUrl.Contains("?")) + // // { + // // fileExtension = materials[curPlayIndex].fileUrl.Substring(materials[curPlayIndex].fileUrl.LastIndexOf("."), materials[curPlayIndex].fileUrl.LastIndexOf("?") - materials[curPlayIndex].fileUrl.LastIndexOf(".")).ToLower(); + // // } + // // else + // // { + // // fileExtension = materials[curPlayIndex].fileUrl.Substring(materials[curPlayIndex].fileUrl.LastIndexOf(".")).ToLower(); + // // } + // // url = outLinePath + "/Main/" + materials[curPlayIndex].fileHash + fileExtension; + // // BindImage(image, url, transition); + // // curPlayIndex++; + // // if (curPlayIndex >= materials.Count) + // // { + // // curPlayIndex = 0; + // // } + // // var taskProg = Task.Delay(transitionPeriod * 1000); + // // tasks.Add(taskProg); + // // await taskProg; + // // if (taskProg != null && taskProg.Status != TaskStatus.Canceled) + // // { + // // taskProg.Dispose(); + // // tasks.Remove(taskProg); + // // } + // // } + // //})); + // //thImage.IsBackground = true; + // //thImage.Start(); + + //} + + private void PlayImage(Image image, List materials, JObject config) + { + CancellationTokenSource source1 = new CancellationTokenSource(); + cancellationTokens.Add(source1); + CancellationToken token = source1.Token; + TaskFactory factory = new TaskFactory(token); + Task tsk1 = factory.StartNew(async () => + { + var curPlayIndex = 0; + var transitionPeriod = config.Value("transitionPeriod"); + var transition = config.Value("transition"); + string fileExtension = string.Empty; + string url = string.Empty; + DateTime? curDate = null; + while (!isStop) + { + if (token.IsCancellationRequested) + { + //isStop = true; + // 释放资源操作等等... + break; + } + //if (!curDate.HasValue || curDate.Value.AddMilliseconds(transitionPeriod * 1000) <= DateTime.Now) + //{ + if (materials[curPlayIndex].fileUrl.Contains("?")) + { + fileExtension = materials[curPlayIndex].fileUrl.Substring(materials[curPlayIndex].fileUrl.LastIndexOf("."), materials[curPlayIndex].fileUrl.LastIndexOf("?") - materials[curPlayIndex].fileUrl.LastIndexOf(".")).ToLower(); + } + else + { + fileExtension = materials[curPlayIndex].fileUrl.Substring(materials[curPlayIndex].fileUrl.LastIndexOf(".")).ToLower(); + } + curDate = DateTime.Now; + url = outLinePath + "/Main/" + materials[curPlayIndex].fileHash + fileExtension; + BindImage(image, url, transition); + curPlayIndex++; + if (curPlayIndex >= materials.Count) + { + curPlayIndex = 0; + } + if (token.IsCancellationRequested) + { + //isStop = true; + // 释放资源操作等等... + break; + } + else + { + await Task.Delay(transitionPeriod * 1000, token); + } + + //} + //else + //{ + // Thread.Sleep(1); + //} + } + }); + + } + + private void BindImage(Image image, string img, string transition) + { + Action action = new Action(()=> { + image.Dispatcher.Invoke(new Action(() => + { + if (img.ToLower().EndsWith(".gif")) + { + //FileStream stream = new FileStream(img, FileMode.Open, FileAccess.Read); + //XamlAnimatedGif.AnimationBehavior.SetSourceStream(image, stream); + //FileStream s = new FileStream(outLinePath + "/Main/" + ucList[app.currentIndex].sourceId + fileExtension, FileMode.Open, FileAccess.Read); + XamlAnimatedGif.AnimationBehavior.SetSourceUri(image, new Uri(img)); + XamlAnimatedGif.AnimationBehavior.SetRepeatBehavior(image, RepeatBehavior.Forever); + XamlAnimatedGif.AnimationBehavior.SetAutoStart(image, true); + } + else + { + image.Source = new BitmapImage(new Uri(img)); + } + })); + }); + action.BeginInvoke(null,null); + } + + private void PlayVideo(VlcControl vlcControl, List materials, JObject config,int type) + { + Action action = new Action(async delegate + { + + try + { + Class_Log log = new Class_Log(); + + //if (th1 == null) + //{ + CancellationTokenSource source1 = new CancellationTokenSource(); + cancellationTokens.Add(source1); + CancellationToken token = source1.Token; + TaskFactory factory = new TaskFactory(token); + Task tsk1 = factory.StartNew(async () => + { + var curPlayIndex = 0; + string fileExtension = string.Empty; + string url = string.Empty; + var curDate = DateTime.Now; + var duration = 0; + while (!isStop) + { + if (token.IsCancellationRequested) + { + //isStop = true; + // 释放资源操作等等... + break; + } + //log.WriteLogFile("-----curDate" + curDate.ToString("yyyy-MM-dd HH:mm:ss") + " url=" + url + " duration=" + duration); + //if (curDate.AddMilliseconds(duration) <= DateTime.Now) + //{ + if (materials[curPlayIndex].fileUrl.Contains("?")) + { + fileExtension = materials[curPlayIndex].fileUrl.Substring(materials[curPlayIndex].fileUrl.LastIndexOf("."), materials[curPlayIndex].fileUrl.LastIndexOf("?") - materials[curPlayIndex].fileUrl.LastIndexOf(".")).ToLower(); + } + else + { + fileExtension = materials[curPlayIndex].fileUrl.Substring(materials[curPlayIndex].fileUrl.LastIndexOf(".")).ToLower(); + } + url = outLinePath + "/Main/" + materials[curPlayIndex].fileHash + fileExtension; + duration = materials[curPlayIndex].duration; + //log.WriteLogFile("curDate" + curDate.ToString("yyyy-MM-dd HH:mm:ss") + " url=" + url + " duration=" + duration); + curDate = DateTime.Now; + if (type == 1) + { + vlcVideoPath = url; + } + else + { + vlcVideo2Path = url; + } + StopVideo(vlcControl); + StartVideo(vlcControl, url); + curPlayIndex++; + if (curPlayIndex >= materials.Count) + { + curPlayIndex = 0; + } + //var taskProg = Task.Delay(duration); + //tasks.Add(taskProg); + //await taskProg; + //if (taskProg != null && taskProg.Status != TaskStatus.Canceled) + //{ + // taskProg.Dispose(); + // tasks.Remove(taskProg); + //} + + if (token.IsCancellationRequested) + { + //isStop = true; + // 释放资源操作等等... + break; + } + else + { + await Task.Delay(duration, token); + } + //} + //else + //{ + // Thread.Sleep(1); + //} + + //Thread.Sleep(duration); + } + }); + //var thVideo = new Thread(new ThreadStart(async () => + // { + // var curPlayIndex = 0; + // string fileExtension = string.Empty; + // string url = string.Empty; + // while (!isStop) + // { + + // if (materials[curPlayIndex].fileUrl.Contains("?")) + // { + // fileExtension = materials[curPlayIndex].fileUrl.Substring(materials[curPlayIndex].fileUrl.LastIndexOf("."), materials[curPlayIndex].fileUrl.LastIndexOf("?") - materials[curPlayIndex].fileUrl.LastIndexOf(".")).ToLower(); + // } + // else + // { + // fileExtension = materials[curPlayIndex].fileUrl.Substring(materials[curPlayIndex].fileUrl.LastIndexOf(".")).ToLower(); + // } + // url = outLinePath + "/Main/" + materials[curPlayIndex].fileHash + fileExtension; + // int duration = materials[curPlayIndex].duration; + // StartVideo(vlcControl, url); + // curPlayIndex++; + // if (curPlayIndex >= materials.Count) + // { + // curPlayIndex = 0; + // } + + // var taskProg = Task.Delay(duration); + // tasks.Add(taskProg); + // await taskProg; + // if (taskProg != null && taskProg.Status != TaskStatus.Canceled) + // { + // taskProg.Dispose(); + // tasks.Remove(taskProg); + // } + // //Thread.Sleep(duration); + // } + // })); + //thVideo.IsBackground = true; + //thVideo.Start(); + //} + + } + catch (Exception ex) + { + Class_Log log = new Class_Log(); + log.WriteLogFile(ex.ToString(), "WindowViewErrorlog"); + } + }); + action.BeginInvoke(null, null); + + } + + private void StartVideo(VlcControl vlcControl, string videoPath) + { + try + { + + vlcControl.SourceProvider.MediaPlayer.Play(new Uri(videoPath)); + } + catch (Exception ex) + { + + MessageBox.Show(ex.Message); + } + } + + private void StopVideo(VlcControl vlcControl) + { + try + { + if (vlcControl.SourceProvider.MediaPlayer.IsPlaying()) + { + vlcControl.SourceProvider.MediaPlayer.Pause(); + } + + } + catch (Exception e) + { + + MessageBox.Show(e.Message); + } + } + + + private async void UserControl_Loaded(object sender, RoutedEventArgs e) + { + + } + + public void Dispose() + { + try + { + vlcControl1.Width = 0; + vlcControl1.Height = 0; + vlcControl2.Width = 0; + vlcControl2.Height = 0; + isStop = true; + foreach (var item in tasks) + { + if (item != null && (item.IsCanceled || item.IsCompleted || item.IsFaulted)) + { + item.Dispose(); + } + } + tasks.Clear(); + foreach (var item in marqueeControlNews) + { + item.Dispose(); + canvas.Children.Remove(item); + } + marqueeControlNews.Clear(); + foreach (var item in clockControls) + { + item.Dispose(); + canvas.Children.Remove(item); + + } + clockControls.Clear(); + foreach (var item in weatherControls) + { + item.Dispose(); + canvas.Children.Remove(item); + + } + weatherControls.Clear(); + foreach (var item in cancellationTokens) + { + item.Cancel(); + } + cancellationTokens.Clear(); + + foreach (var item in imageControls) + { + canvas.Children.Remove(item); + } + imageControls.Clear(); + foreach (var item in mediaControls) + { + item.Stop(); + item.Close(); + } + mediaControls.Clear(); + + foreach (var item in chromiumWebBrowsers) + { + item.Dispose(); + canvas.Children.Remove(item); + } + chromiumWebBrowsers.Clear(); + foreach (var item in canvasWebBrowsers) + { + canvas.Children.Remove(item); + } + canvasWebBrowsers.Clear(); + StopVideo(vlcControl1); + StopVideo(vlcControl2); + + } + catch (Exception e) + { + Class_Log _Log = new Class_Log(); + _Log.WriteLogFile(e.ToString(), "prog"); + } + } + } +} diff --git a/ProgControl1.xaml.cs b/ProgControl1.xaml.cs new file mode 100644 index 0000000..450c944 --- /dev/null +++ b/ProgControl1.xaml.cs @@ -0,0 +1,866 @@ +using CefSharp.Wpf; +using Container.Business; +using Container.ChildWindows; +using Container.Common; +using Container.Model; +using Newtonsoft.Json.Linq; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Data; +using System.Windows.Documents; +using System.Windows.Input; +using System.Windows.Media; +using System.Windows.Media.Animation; +using System.Windows.Media.Imaging; +using System.Windows.Navigation; +using System.Windows.Shapes; +using Vlc.DotNet.Wpf; + +namespace Container.Win +{ + /// + /// ProgControl.xaml 的交互逻辑 + /// + public partial class ProgControl : UserControl + { + string outLinePath; + App app = ((App)System.Windows.Application.Current); + DirectoryInfo vlcLibDirectory; + backgroundMaterialInfo backgroundMaterial; + string backgroundColor; + List components; + private Thread th1;//播放屏保的线程 + bool isStop = false; + BrushConverter converter = new BrushConverter(); + List tasks = new List(); + List marqueeControlNews = new List(); + List clockControls = new List(); + List weatherControls = new List(); + List imageControls = new List(); + List mediaControls = new List(); + List chromiumWebBrowsers = new List(); + List mediaElements = new List(); + List canvasWebBrowsers = new List(); + //VlcControl vlcControl1 = new VlcControl(); + //VlcControl vlcControl2 = new VlcControl(); + + List cancellationTokens = new List(); + string[] options; + public ProgControl() + { + InitializeComponent(); + var currentAssembly = Assembly.GetEntryAssembly(); + var currentDirectory = new FileInfo(currentAssembly.Location).DirectoryName; + // Default installation path of VideoLAN.LibVLC.Windows + //vlcLibDirectory = new DirectoryInfo(currentDirectory); + ////初始化配置,指定引用库 + //vlcControl1.SourceProvider.CreatePlayer(vlcLibDirectory); + ////初始化配置,指定引用库 + //vlcControl2.SourceProvider.CreatePlayer(vlcLibDirectory); + + + // options = new string[]{ + // "-I", + //"dummy", + //"--ignore-config", + //"--extraintf=logger", + //"--verbose=2", + //"--fullscreen", + //"--network-caching=300", + //"--live-caching=300", + //"--sout-mux-caching=300", + //"--file-caching=300", + //"--codec=mediacodec,iomx,all", + //"--quiet-synchro", + //" --clock-synchro=300", + //"--network-synchronisation", + //"--cr-average=10000" + // }; + //options = new string[] { "-I", "dummy", "--network-caching=<300", ":sout=#transcode{vcodec=h264,acodec=mpga,ab=128,channels=2,samplerate=44100" }; + + //canvas.Children.Add(vlcControl1); + //canvas.Children.Add(vlcControl2); + + } + + + + public void LoadProg(double width, double height, backgroundMaterialInfo backgroundmaterial, string backgroundcolor, List componentList) + { + backgroundMaterial = backgroundmaterial; + backgroundColor = backgroundcolor; + components = componentList; + this.Width = width; + this.Height = height; + canvas.Width = width; + canvas.Height = height; + try + { + outLinePath = AppDomain.CurrentDomain.BaseDirectory + "/OutlineFiles"; + if (backgroundMaterial != null) + { + string fileExtension = string.Empty; + if (backgroundMaterial.filePath.Contains("?")) + { + fileExtension = backgroundMaterial.filePath.Substring(backgroundMaterial.filePath.LastIndexOf("."), backgroundMaterial.filePath.LastIndexOf("?") - backgroundMaterial.filePath.LastIndexOf(".")).ToLower(); + } + else + { + fileExtension = backgroundMaterial.filePath.Substring(backgroundMaterial.filePath.LastIndexOf(".")).ToLower(); + } + string url = outLinePath + "/Main/" + backgroundMaterial.fileHash + fileExtension; + if (File.Exists(url)) + { + Image image = new Image();//新建图片对象 + image.Source = new BitmapImage(new Uri(url));//读取图片 + ImageBrush ib = new ImageBrush();//新建图片对象 + ib.ImageSource = image.Source;//赋值为背景图片 + canvas.Background = ib;//将图片对象赋值给Canvas的Background + } + + } + else if (!string.IsNullOrEmpty(backgroundColor)) + { + Color color = (Color)ColorConverter.ConvertFromString(backgroundColor); + canvas.Background = new SolidColorBrush(color); + } + + int vlcCount = 0; + + isStop = false; + foreach (var item in components) + { + if ((item.materials == null || item.materials.Count == 0) && (item.typeCode == "text" || item.typeCode == "image" || item.typeCode == "video"||item.typeCode== "audio" || item.typeCode == "html" || item.typeCode == "url")) + { + continue; + } + if (item.typeCode == "image") + { + Image image = new Image(); + image.Width = item.width; + image.Height = item.height; + imageControls.Add(image); + canvas.Children.Add(image); + Canvas.SetLeft(image, item.offsetX); + Canvas.SetZIndex(image, item.zIndex); + Canvas.SetTop(image, item.offsetY); + image.Stretch = Stretch.Fill; + PlayImage(image, item.materials, item.config); + } + if (item.typeCode == "video"&& item.materials.Count>0) + { + if (item.materials.Count > 1) + { + MediaElement media = new MediaElement(); + + media.LoadedBehavior = MediaState.Manual; + Canvas canvasM = new Canvas(); + canvasM.Width = item.width; + canvasM.Height = item.height; + canvasM.Background = Brushes.Black; + media.Width = item.width; + media.Height = item.height; + media.Stretch = Stretch.Fill; + canvasM.Children.Add(media); + Canvas.SetLeft(canvasM, item.offsetX); + Canvas.SetZIndex(canvasM, item.zIndex); + Canvas.SetTop(canvasM, item.offsetY); + canvas.Children.Add(canvasM); + canvasWebBrowsers.Add(canvasM); + mediaElements.Add(media); + PlayVideo(media, item.materials, item.config, 1); + media.Volume = 1; + } + else if (item.materials.Count == 1) + { + + string fileExtension = string.Empty; + string url = string.Empty; + if (item.materials[0].fileUrl.Contains("?")) + { + fileExtension = item.materials[0].fileUrl.Substring(item.materials[0].fileUrl.LastIndexOf("."), item.materials[0].fileUrl.LastIndexOf("?") - item.materials[0].fileUrl.LastIndexOf(".")).ToLower(); + } + else + { + fileExtension = item.materials[0].fileUrl.Substring(item.materials[0].fileUrl.LastIndexOf(".")).ToLower(); + } + url = outLinePath + "/Main/" + item.materials[0].fileHash + fileExtension; + MediaElement media = new MediaElement(); + media.MediaEnded += new RoutedEventHandler((send, e) => + { + media.Position = new TimeSpan(0,0,0,0,100); + }); + media.LoadedBehavior = MediaState.Manual; + media.Stretch = Stretch.Fill; + media.Source = new Uri(url); + Canvas canvasM = new Canvas(); + canvasM.Width = item.width; + canvasM.Height = item.height; + canvasM.Background = Brushes.Transparent; + media.Width = item.width; + media.Height = item.height; + canvasM.Children.Add(media); + Canvas.SetLeft(canvasM, item.offsetX); + Canvas.SetZIndex(canvasM, item.zIndex); + Canvas.SetTop(canvasM, item.offsetY); + canvas.Children.Add(canvasM); + canvasWebBrowsers.Add(canvasM); + mediaElements.Add(media); + media.Play(); + //PlayVideo(media, item.materials, item.config, 1); + media.Volume = 1; + } + //else if (item.materials.Count == 1) + //{ + + // string fileExtension = string.Empty; + // string url = string.Empty; + // if (item.materials[0].fileUrl.Contains("?")) + // { + // fileExtension = item.materials[0].fileUrl.Substring(item.materials[0].fileUrl.LastIndexOf("."), item.materials[0].fileUrl.LastIndexOf("?") - item.materials[0].fileUrl.LastIndexOf(".")).ToLower(); + // } + // else + // { + // fileExtension = item.materials[0].fileUrl.Substring(item.materials[0].fileUrl.LastIndexOf(".")).ToLower(); + // } + // url = outLinePath + "/Main/" + item.materials[0].fileHash + fileExtension; + // MediaElement media = new MediaElement(); + // media.LoadedBehavior = MediaState.Manual; + // media.Volume = 1; + // EventTrigger eventTrigger = new EventTrigger(); + // eventTrigger.RoutedEvent = MediaElement.LoadedEvent; + // eventTrigger.SourceName = media.Name; + // BeginStoryboard begin = new BeginStoryboard(); + // Storyboard storyboard = new Storyboard(); + // MediaTimeline timeline = new MediaTimeline(); + // //timeline.FillBehavior = FillBehavior.Stop; + // timeline.Source = new Uri(url); + // timeline.RepeatBehavior = RepeatBehavior.Forever; + + // Storyboard.SetTarget(timeline, media); + // storyboard.Children.Add(timeline); + // begin.Storyboard = storyboard; + // eventTrigger.Actions.Add(begin); + // media.Triggers.Add(eventTrigger); + + // Canvas canvasM = new Canvas(); + // canvasM.Width = item.width; + // canvasM.Height = item.height; + // canvasM.Background = Brushes.Transparent; + // media.Width = item.width; + // media.Height = item.height; + // canvasM.Children.Add(media); + // Canvas.SetLeft(canvasM, item.offsetX); + // Canvas.SetZIndex(canvasM, item.zIndex); + // Canvas.SetTop(canvasM, item.offsetY); + // canvas.Children.Add(canvasM); + // canvasWebBrowsers.Add(canvasM); + // mediaElements.Add(media); + //} + + //vlcCount++; + //if (vlcCount == 1) + //{ + // canvasM1.Width= item.width; + // canvasM1.Height = item.height; + // media1.Width = item.width; + // media1.Height = item.height; + // Canvas.SetLeft(canvasM1, item.offsetX); + // Canvas.SetZIndex(canvasM1, item.zIndex); + // Canvas.SetTop(canvasM1, item.offsetY); + // PlayVideo(media1, item.materials, item.config, 1); + //} + //else + //{ + // canvasM2.Width = item.width; + // canvasM2.Height = item.height; + // media2.Width = item.width; + // media2.Height = item.height; + // Canvas.SetLeft(canvasM2, item.offsetX); + // Canvas.SetZIndex(canvasM2, item.zIndex); + // Canvas.SetTop(canvasM2, item.offsetY); + // PlayVideo(media2, item.materials, item.config, 2); + //} + + } + if (item.typeCode == "text" && item.materials != null && item.materials.Count > 0) + { + var textBackgroundColor = item.config.Value("backgroundColor"); + var textBackgroundOpacity = item.config.Value("backgroundOpacity"); + var textFontColor = item.config.Value("fontColor"); + var textFontSize = item.config.Value("fontSize"); + var textFontStyle = item.config.Value("fontStyle"); + var textAnimationSpeed = item.config.Value("animationSpeed"); + + string fileExtension = string.Empty; + string url = string.Empty; + if (item.materials[0].fileUrl.Contains("?")) + { + fileExtension = item.materials[0].fileUrl.Substring(item.materials[0].fileUrl.LastIndexOf("."), item.materials[0].fileUrl.LastIndexOf("?") - item.materials[0].fileUrl.LastIndexOf(".")).ToLower(); + } + else + { + fileExtension = item.materials[0].fileUrl.Substring(item.materials[0].fileUrl.LastIndexOf(".")).ToLower(); + } + url = outLinePath + "/Main/" + item.materials[0].fileHash + fileExtension; + string textContent = DownLoadMethod.ReadContext(url); + textContent = textContent.Replace("\r\n", " "); + MarqueeControlNew marqueeControlNew = new MarqueeControlNew(); + marqueeControlNew.Load(textContent, item.width, item.height, textFontSize, textBackgroundColor, textBackgroundOpacity, textFontColor, textFontStyle, textAnimationSpeed); + canvas.Children.Add(marqueeControlNew); + marqueeControlNews.Add(marqueeControlNew); + Canvas.SetLeft(marqueeControlNew, item.offsetX); + Canvas.SetZIndex(marqueeControlNew, item.zIndex); + Canvas.SetTop(marqueeControlNew, item.offsetY); + } + if (item.typeCode == "clock") + { + var backgroundColor = item.config.Value("backgroundColor"); + var fontColor = item.config.Value("fontColor"); + var style = item.config.Value("style"); + ClockControl clock = new ClockControl(); + clock.BindClock(style.Value, item.width, item.height, backgroundColor, fontColor); + canvas.Children.Add(clock); + clockControls.Add(clock); + Canvas.SetLeft(clock, item.offsetX); + Canvas.SetZIndex(clock, item.zIndex); + Canvas.SetTop(clock, item.offsetY); + } + if (item.typeCode == "weather") + { + var backgroundColor = item.config.Value("backgroundColor"); + var fontColor = item.config.Value("fontColor"); + var style = item.config.Value("style"); + var city = item.config.Value("cityName"); + if (string.IsNullOrEmpty(city)) + { + city = app.defaultCity; + } + if (!string.IsNullOrEmpty(city)) + { + WeatherControl weather = new WeatherControl(); + weather.LoadWeather(city, style.Value, item.width, item.height, backgroundColor, fontColor); + canvas.Children.Add(weather); + weatherControls.Add(weather); + Canvas.SetLeft(weather, item.offsetX); + Canvas.SetZIndex(weather, item.zIndex); + Canvas.SetTop(weather, item.offsetY); + } + } + if (item.typeCode == "audio" && item.materials != null && item.materials.Count > 0) + { + MediaPlayer media = new MediaPlayer(); + string fileExtension = string.Empty; + string url = string.Empty; + if (item.materials[0].fileUrl.Contains("?")) + { + fileExtension = item.materials[0].fileUrl.Substring(item.materials[0].fileUrl.LastIndexOf("."), item.materials[0].fileUrl.LastIndexOf("?") - item.materials[0].fileUrl.LastIndexOf(".")).ToLower(); + } + else + { + fileExtension = item.materials[0].fileUrl.Substring(item.materials[0].fileUrl.LastIndexOf(".")).ToLower(); + } + url = outLinePath + "/Main/" + item.materials[0].fileHash + fileExtension; + media.Open(new Uri(url, UriKind.Relative)); + media.MediaEnded += (sender, e) => + {//播放结束后 又重新播放 + media.Position = new TimeSpan(0); + }; + media.Play(); + mediaControls.Add(media); + } + if (item.typeCode == "html" && item.materials != null && item.materials.Count > 0) + { + string fileExtension = string.Empty; + string url = string.Empty; + if (item.materials[0].fileUrl.Contains("?")) + { + fileExtension = item.materials[0].fileUrl.Substring(item.materials[0].fileUrl.LastIndexOf("."), item.materials[0].fileUrl.LastIndexOf("?") - item.materials[0].fileUrl.LastIndexOf(".")).ToLower(); + } + else + { + fileExtension = item.materials[0].fileUrl.Substring(item.materials[0].fileUrl.LastIndexOf(".")).ToLower(); + } + url = outLinePath + "/Main/" + item.materials[0].fileHash + fileExtension; + ChromiumWebBrowser webBrowser = new ChromiumWebBrowser(); + webBrowser.Width = item.width; + webBrowser.Height = item.height; + webBrowser.Address = url.Replace(@"/", @"\").Replace(@"\\",@"\") ; + //webBrowser.GetBrowser().Reload(); + //webBrowser.Address = "file:///D:/360MoveData/Users/jiaxl/Desktop/Websocket.html"; + webBrowser.Background = Brushes.Black; + Canvas canvas1 = new Canvas(); + canvas1.Width = item.width; + canvas1.Height = item.height; + canvas1.Background = Brushes.White; + canvas1.Children.Add(webBrowser); + //webBrowser.Load(url); + canvas.Children.Add(canvas1); + canvasWebBrowsers.Add(canvas1); + chromiumWebBrowsers.Add(webBrowser); + Canvas.SetLeft(canvas1, item.offsetX); + Canvas.SetZIndex(canvas1, item.zIndex); + Canvas.SetTop(canvas1, item.offsetY); + } + if (item.typeCode == "url" && item.materials != null && item.materials.Count > 0 && item.materials[0].mediaInfo != null && !string.IsNullOrEmpty(item.materials[0].mediaInfo.url)) + { + ChromiumWebBrowser webBrowser = new ChromiumWebBrowser(); + webBrowser.Width = item.width; + webBrowser.Height = item.height; + webBrowser.Address = item.materials[0].mediaInfo.url; + webBrowser.Background = Brushes.Black; + Canvas canvas1 = new Canvas(); + canvas1.Width = item.width; + canvas1.Height = item.height; + canvas1.Background = Brushes.White; + canvas1.Children.Add(webBrowser); + //webBrowser.Load(url); + canvas.Children.Add(canvas1); + canvasWebBrowsers.Add(canvas1); + chromiumWebBrowsers.Add(webBrowser); + Canvas.SetLeft(canvas1, item.offsetX); + Canvas.SetZIndex(canvas1, item.zIndex); + Canvas.SetTop(canvas1, item.offsetY); + } + } + + } + catch (Exception ex) + { + + Class_Log _Log = new Class_Log(); + _Log.WriteLogFile(ex.ToString()); + } + } + + //private void PlayImage(Image image, List materials, JObject config) + //{ + // CancellationTokenSource source1 = new CancellationTokenSource(); + // cancellationTokens.Add(source1); + // CancellationToken token = source1.Token; + // TaskFactory factory = new TaskFactory(token); + // Task tsk1 = factory.StartNew(() => + // { + // var curPlayIndex = 0; + // var transitionPeriod = config.Value("transitionPeriod"); + // var transition = config.Value("transition"); + // string fileExtension = string.Empty; + // string url = string.Empty; + // DateTime? curDate = null; + // while (!isStop) + // { + // if (token.IsCancellationRequested) + // { + // //isStop = true; + // // 释放资源操作等等... + // break; + // } + // if (!curDate.HasValue||curDate.Value.AddMilliseconds(transitionPeriod * 1000) <= DateTime.Now) + // { + // if (materials[curPlayIndex].fileUrl.Contains("?")) + // { + // fileExtension = materials[curPlayIndex].fileUrl.Substring(materials[curPlayIndex].fileUrl.LastIndexOf("."), materials[curPlayIndex].fileUrl.LastIndexOf("?") - materials[curPlayIndex].fileUrl.LastIndexOf(".")).ToLower(); + // } + // else + // { + // fileExtension = materials[curPlayIndex].fileUrl.Substring(materials[curPlayIndex].fileUrl.LastIndexOf(".")).ToLower(); + // } + // curDate = DateTime.Now; + // url = outLinePath + "/Main/" + materials[curPlayIndex].fileHash + fileExtension; + // BindImage(image, url, transition); + // curPlayIndex++; + // if (curPlayIndex >= materials.Count) + // { + // curPlayIndex = 0; + // } + // } + // else + // { + // Thread.Sleep(1); + // } + // } + // }); + // //var thImage = new Thread(new ThreadStart(async () => + // //{ + // // var curPlayIndex = 0; + // // var transitionPeriod = config.Value("transitionPeriod"); + // // var transition = config.Value("transition"); + // // string fileExtension = string.Empty; + // // string url = string.Empty; + // // while (!isStop) + // // { + + // // if (materials[curPlayIndex].fileUrl.Contains("?")) + // // { + // // fileExtension = materials[curPlayIndex].fileUrl.Substring(materials[curPlayIndex].fileUrl.LastIndexOf("."), materials[curPlayIndex].fileUrl.LastIndexOf("?") - materials[curPlayIndex].fileUrl.LastIndexOf(".")).ToLower(); + // // } + // // else + // // { + // // fileExtension = materials[curPlayIndex].fileUrl.Substring(materials[curPlayIndex].fileUrl.LastIndexOf(".")).ToLower(); + // // } + // // url = outLinePath + "/Main/" + materials[curPlayIndex].fileHash + fileExtension; + // // BindImage(image, url, transition); + // // curPlayIndex++; + // // if (curPlayIndex >= materials.Count) + // // { + // // curPlayIndex = 0; + // // } + // // var taskProg = Task.Delay(transitionPeriod * 1000); + // // tasks.Add(taskProg); + // // await taskProg; + // // if (taskProg != null && taskProg.Status != TaskStatus.Canceled) + // // { + // // taskProg.Dispose(); + // // tasks.Remove(taskProg); + // // } + // // } + // //})); + // //thImage.IsBackground = true; + // //thImage.Start(); + + //} + + private void PlayImage(Image image, List materials, JObject config) + { + CancellationTokenSource source1 = new CancellationTokenSource(); + cancellationTokens.Add(source1); + CancellationToken token = source1.Token; + TaskFactory factory = new TaskFactory(token); + Task tsk1 = factory.StartNew(async () => + { + var curPlayIndex = 0; + var transitionPeriod = config.Value("transitionPeriod"); + var transition = config.Value("transition"); + string fileExtension = string.Empty; + string url = string.Empty; + DateTime? curDate = null; + while (!isStop) + { + if (token.IsCancellationRequested) + { + //isStop = true; + // 释放资源操作等等... + break; + } + //if (!curDate.HasValue || curDate.Value.AddMilliseconds(transitionPeriod * 1000) <= DateTime.Now) + //{ + if (materials[curPlayIndex].fileUrl.Contains("?")) + { + fileExtension = materials[curPlayIndex].fileUrl.Substring(materials[curPlayIndex].fileUrl.LastIndexOf("."), materials[curPlayIndex].fileUrl.LastIndexOf("?") - materials[curPlayIndex].fileUrl.LastIndexOf(".")).ToLower(); + } + else + { + fileExtension = materials[curPlayIndex].fileUrl.Substring(materials[curPlayIndex].fileUrl.LastIndexOf(".")).ToLower(); + } + curDate = DateTime.Now; + url = outLinePath + "/Main/" + materials[curPlayIndex].fileHash + fileExtension; + BindImage(image, url, transition); + curPlayIndex++; + if (curPlayIndex >= materials.Count) + { + curPlayIndex = 0; + } + if (token.IsCancellationRequested) + { + //isStop = true; + // 释放资源操作等等... + break; + } + else + { + await Task.Delay(transitionPeriod * 1000, token); + } + + //} + //else + //{ + // Thread.Sleep(1); + //} + } + }); + + } + + private void BindImage(Image image, string img, string transition) + { + Action action = new Action(()=> { + image.Dispatcher.Invoke(new Action(() => + { + if (img.ToLower().EndsWith(".gif")) + { + //FileStream stream = new FileStream(img, FileMode.Open, FileAccess.Read); + //XamlAnimatedGif.AnimationBehavior.SetSourceStream(image, stream); + //FileStream s = new FileStream(outLinePath + "/Main/" + ucList[app.currentIndex].sourceId + fileExtension, FileMode.Open, FileAccess.Read); + XamlAnimatedGif.AnimationBehavior.SetSourceUri(image, new Uri(img)); + XamlAnimatedGif.AnimationBehavior.SetRepeatBehavior(image, RepeatBehavior.Forever); + XamlAnimatedGif.AnimationBehavior.SetAutoStart(image, true); + } + else + { + image.Source = new BitmapImage(new Uri(img)); + } + })); + }); + action.BeginInvoke(null,null); + } + + private void PlayVideo(MediaElement media, List materials, JObject config,int type) + { + Action action = new Action(async delegate + { + + try + { + Class_Log log = new Class_Log(); + + //if (th1 == null) + //{ + CancellationTokenSource source1 = new CancellationTokenSource(); + cancellationTokens.Add(source1); + CancellationToken token = source1.Token; + TaskFactory factory = new TaskFactory(token); + Task tsk1 = factory.StartNew(async () => + { + var curPlayIndex = 0; + string fileExtension = string.Empty; + string url = string.Empty; + var curDate = DateTime.Now; + var duration = 0; + while (!isStop) + { + if (token.IsCancellationRequested) + { + //isStop = true; + // 释放资源操作等等... + break; + } + //log.WriteLogFile("-----curDate" + curDate.ToString("yyyy-MM-dd HH:mm:ss") + " url=" + url + " duration=" + duration); + //if (curDate.AddMilliseconds(duration) <= DateTime.Now) + //{ + if (materials[curPlayIndex].fileUrl.Contains("?")) + { + fileExtension = materials[curPlayIndex].fileUrl.Substring(materials[curPlayIndex].fileUrl.LastIndexOf("."), materials[curPlayIndex].fileUrl.LastIndexOf("?") - materials[curPlayIndex].fileUrl.LastIndexOf(".")).ToLower(); + } + else + { + fileExtension = materials[curPlayIndex].fileUrl.Substring(materials[curPlayIndex].fileUrl.LastIndexOf(".")).ToLower(); + } + url = outLinePath + "/Main/" + materials[curPlayIndex].fileHash + fileExtension; + duration = materials[curPlayIndex].duration; + //log.WriteLogFile("curDate" + curDate.ToString("yyyy-MM-dd HH:mm:ss") + " url=" + url + " duration=" + duration); + curDate = DateTime.Now; + StopVideo(media); + StartVideo(media, url); + curPlayIndex++; + if (curPlayIndex >= materials.Count) + { + curPlayIndex = 0; + } + //var taskProg = Task.Delay(duration); + //tasks.Add(taskProg); + //await taskProg; + //if (taskProg != null && taskProg.Status != TaskStatus.Canceled) + //{ + // taskProg.Dispose(); + // tasks.Remove(taskProg); + //} + + //if (token.IsCancellationRequested) + //{ + // //isStop = true; + // // 释放资源操作等等... + // break; + //} + //else + //{ + await Task.Delay(duration, token); + // } + //} + //else + //{ + // Thread.Sleep(1); + //} + + //Thread.Sleep(duration); + } + }); + //var thVideo = new Thread(new ThreadStart(async () => + // { + // var curPlayIndex = 0; + // string fileExtension = string.Empty; + // string url = string.Empty; + // while (!isStop) + // { + + // if (materials[curPlayIndex].fileUrl.Contains("?")) + // { + // fileExtension = materials[curPlayIndex].fileUrl.Substring(materials[curPlayIndex].fileUrl.LastIndexOf("."), materials[curPlayIndex].fileUrl.LastIndexOf("?") - materials[curPlayIndex].fileUrl.LastIndexOf(".")).ToLower(); + // } + // else + // { + // fileExtension = materials[curPlayIndex].fileUrl.Substring(materials[curPlayIndex].fileUrl.LastIndexOf(".")).ToLower(); + // } + // url = outLinePath + "/Main/" + materials[curPlayIndex].fileHash + fileExtension; + // int duration = materials[curPlayIndex].duration; + // StartVideo(vlcControl, url); + // curPlayIndex++; + // if (curPlayIndex >= materials.Count) + // { + // curPlayIndex = 0; + // } + + // var taskProg = Task.Delay(duration); + // tasks.Add(taskProg); + // await taskProg; + // if (taskProg != null && taskProg.Status != TaskStatus.Canceled) + // { + // taskProg.Dispose(); + // tasks.Remove(taskProg); + // } + // //Thread.Sleep(duration); + // } + // })); + //thVideo.IsBackground = true; + //thVideo.Start(); + //} + + } + catch (Exception ex) + { + Class_Log log = new Class_Log(); + log.WriteLogFile(ex.ToString(), "WindowViewErrorlog"); + } + }); + action.BeginInvoke(null, null); + + } + + private void StartVideo(MediaElement media, string videoPath) + { + try + { + media.Dispatcher.Invoke(new Action(() => + { + media.Source = new Uri(videoPath); + media.Play(); + })); + //vlcControl.SourceProvider.MediaPlayer.Play(new Uri(videoPath)); + } + catch (Exception ex) + { + + MessageBox.Show(ex.Message); + } + } + + private void StopVideo(MediaElement media) + { + try + { + media.Dispatcher.Invoke(new Action(() => + { + media.Stop(); + })); + //if (vlcControl.SourceProvider.MediaPlayer.IsPlaying()) + //{ + // vlcControl.SourceProvider.MediaPlayer.Pause(); + //} + + } + catch (Exception e) + { + + MessageBox.Show(e.Message); + } + } + + + private async void UserControl_Loaded(object sender, RoutedEventArgs e) + { + + } + + public void Dispose() + { + try + { + isStop = true; + foreach (var item in tasks) + { + if (item != null && (item.IsCanceled || item.IsCompleted || item.IsFaulted)) + { + item.Dispose(); + } + } + tasks.Clear(); + foreach (var item in marqueeControlNews) + { + item.Dispose(); + canvas.Children.Remove(item); + } + marqueeControlNews.Clear(); + foreach (var item in clockControls) + { + item.Dispose(); + canvas.Children.Remove(item); + + } + clockControls.Clear(); + foreach (var item in weatherControls) + { + item.Dispose(); + canvas.Children.Remove(item); + + } + weatherControls.Clear(); + foreach (var item in cancellationTokens) + { + item.Cancel(); + } + cancellationTokens.Clear(); + foreach (var item in mediaElements) + { + item.Stop(); + } + mediaElements.Clear(); + foreach (var item in imageControls) + { + canvas.Children.Remove(item); + } + imageControls.Clear(); + foreach (var item in mediaControls) + { + item.Stop(); + item.Close(); + } + mediaControls.Clear(); + + foreach (var item in chromiumWebBrowsers) + { + item.Dispose(); + canvas.Children.Remove(item); + } + chromiumWebBrowsers.Clear(); + foreach (var item in canvasWebBrowsers) + { + canvas.Children.Remove(item); + } + canvasWebBrowsers.Clear(); + + } + catch (Exception e) + { + Class_Log _Log = new Class_Log(); + _Log.WriteLogFile(e.ToString(), "prog"); + } + } + } +}