Example #1
0
        public static void Main(string[] args)
        {
            updateBaseDir();
            Debug.WriteLine("baseDir = " + baseDir);
            Debug.WriteLine("extentionsDir = " + extentionsDir);
            Debug.WriteLine("imagesDir = " + imagesDir);
            Debug.WriteLine("soundDir = " + soundDir);
            isDebugF();
            PluginLoadAll();
            if (IsDebug == false)
            {
                Dictionary <string, object> plug = Server.Program.PluginGet("TrayIcon");
                if (plug == null)
                {
                    return;
                }
                try
                {
                    Assembly asem     = (Assembly)plug["assembly"];
                    Type     t        = (Type)plug["type"];
                    object   instance = (object)plug["instance"];

                    MethodInfo m = t.GetMethod("HideConsole");
                    Debug.WriteLine("m.Invoke(instance, new object[] {});");
                    m.Invoke(instance, new object[] { });
                }
                catch (Exception error) { }
            }

            AppDomain.CurrentDomain.ProcessExit += CurrentDomain_ProcessExit;
            listSocket = new List <JObject>();
            exe        = new Execute();
            LoadRemoteParams();

            watcher = new FileSystemWatcher(baseDir);
            watcher.NotifyFilter = NotifyFilters.LastAccess
                                   | NotifyFilters.LastWrite
                                   | NotifyFilters.FileName
                                   | NotifyFilters.DirectoryName;
            watcher.Filter   = "*.json";
            watcher.Changed += OnLoadRemoteParamsChanged;
            watcher.Created += OnLoadRemoteParamsChanged;
            //watcher.Deleted += OnLoadRemoteParamsChanged;
            watcher.Renamed            += OnLoadRemoteParamsChanged;
            watcher.EnableRaisingEvents = true;


            try
            {
                Thread objThread = new Thread(TimerLoop);
                objThread.IsBackground = true;
                objThread.Priority     = ThreadPriority.AboveNormal;
                objThread.Start();
            }
            catch (ThreadStartException objException) { }
            catch (ThreadAbortException objException) { }
            catch (Exception objException) { }


            byte[] data = new byte[51200];
            listhendPort = 25000;
            //listhendPort = FreeTcpPort();
            IPEndPoint ipep = new IPEndPoint(IPAddress.Any, listhendPort);

            newsock = new UdpClient(ipep);

            Console.WriteLine("Waiting for a client...");

            IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);

            while (unload == false)
            {
                try {
                    data = newsock.Receive(ref sender);
                    Console.WriteLine("Message received from {0}:", sender.ToString());
                    string text = Encoding.UTF8.GetString(data, 0, data.Length);
                    try { Console.WriteLine(text); } catch (Exception error) { Console.WriteLine(Encoding.ASCII.GetString(data, 0, data.Length)); }
                    try {
                        JObject ob       = JObject.Parse(text);
                        string  function = "";
                        try { function = ob.GetValue("function").Value <string>(); } catch (Exception error) { }
                        string macro = null;
                        try { macro = ob.GetValue("macro").Value <string>(); } catch (Exception error) { }

                        if (function != "")
                        {
                            if (function == "Pong")
                            {
                                for (int i = 0; i < listSocket.Count; i++)
                                {
                                    if (listSocket[i]["addr"].Value <string>() == sender.Address.ToString() && listSocket[i]["port"].Value <int>() == sender.Port)
                                    {
                                        listSocket[i]["last"] = (Int32)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
                                    }
                                }
                                continue;
                            }
                            if (function == "GetInfo")
                            {
                                JObject sock = new JObject();
                                sock["addr"] = sender.Address.ToString();
                                sock["port"] = sender.Port;
                                sock["last"] = (Int32)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
                                listSocket.Add(sock);
                                data = Encoding.UTF8.GetBytes(GetInfo());
                                newsock.Send(data, data.Length, sender);
                            }

                            if (function == "GetGrids" || function == "ForceReload")
                            {
                                if (function == "ForceReload")
                                {
                                    LoadRemoteParams();
                                }
                                string gri = JsonConvert.SerializeObject(GridsList.GetValue("grids"));
                                data = Encoding.UTF8.GetBytes("{\"function\":\"SendGrids\", \"grids\":" + gri + "}");
                            }

                            if (function == "GetImage")
                            {
                                string filePath = imagesDir + ob["reference"].Value <string>();
                                if (File.Exists(filePath) == true)
                                {
                                    using (Image image = Image.FromFile(filePath))
                                    {
                                        using (MemoryStream m = new MemoryStream())
                                        {
                                            image.Save(m, image.RawFormat);
                                            byte[] imageBytes   = m.ToArray();
                                            string base64String = Convert.ToBase64String(imageBytes);
                                            data = Encoding.UTF8.GetBytes("{\"function\":\"RetGetImage\", \"reference\":\"" + ob["reference"].Value <string>() + "\", \"result\":\"data:" + MimeTypesMap.GetMimeType(filePath) + ";base64," + base64String + "\"}");
                                        }
                                    }
                                }
                                else
                                {
                                    data = Encoding.UTF8.GetBytes("{\"function\":\"RetGetImage\", \"reference\":\"" + ob["reference"].Value <string>() + "\", \"result\":\"ERROR\"}");
                                }
                            }

                            if (function == "GetSoundInfo" || function == "MuteSound" || function == "VolUp" || function == "VolDown")
                            {
                                JToken tok = ob.Value <JToken>();
                                ParseSoundInfo(function, ref newsock, sender, tok);
                            }

                            newsock.Send(data, data.Length, sender);
                        }
                        if (macro != null)
                        {
                            string sound = null;
                            try { sound = ob.GetValue("sound").Value <string>(); } catch (Exception error) { }
                            MacrosProcessing.Run(exe, MacroList, macro, sound, newsock, sender);
                        }
                    } catch (Exception error) { Debug.WriteLine(JsonConvert.SerializeObject(error)); Debug.WriteLine(Encoding.UTF8.GetString(data, 0, data.Length)); }
                }
                catch (Exception error) { Debug.WriteLine(error.StackTrace); }
            }
        }
 public static void Run(Execute exe, JObject MacroList, string CalledMacro, string CalledSound, UdpClient newsock, IPEndPoint sender)
 {
     Debug.WriteLine("MacrosProcessing.Run: " + CalledMacro + " " + CalledSound);
     if (CalledMacro != "")
     {
         Debug.WriteLine("IN MACRO");
         string[] tabGivenMacro = CalledMacro.Split('/');
         foreach (JToken section in MacroList["sections"].ToList <JToken>())
         {
             //Debug.WriteLine("section Compare: " + tabGivenMacro[0] + " " + section["name"].Value<string>());
             if (section["name"].Value <string>() == tabGivenMacro[0])
             {
                 //Debug.WriteLine("section data = " + JsonConvert.SerializeObject(section));
                 if (section["macros"].Value <JObject>().ContainsKey(tabGivenMacro[1]) == true)
                 {
                     JObject ob2 = section["macros"][tabGivenMacro[1]].Value <JObject>();
                     if (CalledSound != "")
                     {
                         if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) == true)
                         {
                             CalledSound = CalledSound.Replace("/", "\\");
                         }
                         ob2["sound"] = Program.soundDir + CalledSound;
                     }
                     string st = JsonConvert.SerializeObject(ob2);
                     //Debug.WriteLine("macro data = " + st);
                     Dictionary <string, object> options = new Dictionary <string, object>()
                     {
                         { "exe", exe },
                         { "macro", ob2 },
                         { "newsock", newsock },
                         { "sender", sender }
                     };
                     if (st.Contains("Sleep") == true && st.Contains("delay") == true)
                     {
                         Thread objThread = new Thread(new ParameterizedThreadStart(RunPart2));
                         //Make the thread as background thread.
                         objThread.IsBackground = true;
                         //Set the Priority of the thread.
                         objThread.Priority = ThreadPriority.AboveNormal;
                         //Start the thread.
                         objThread.Start(options);
                     }
                     else
                     {
                         RunPart2(options);
                     }
                 }
             }
         }
     }
     else
     {
         if (CalledSound != "")
         {
             JObject options = new JObject();
             if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) == true)
             {
                 CalledSound = CalledSound.Replace("/", "\\");
             }
             options["url"] = Program.soundDir + CalledSound;
             PlaySound(options);
         }
     }
 }