Пример #1
0
        //
        private WebFileCache GetWebFileCache(string file)
        {
            WebFileCache fileItem = new WebFileCache(), cachedItem = null;

            try { cachedItem = webFileCache.Find(wfc => wfc.FilePath == file); }
            catch (Exception ex)
            {
                //TODO: sometimes the Find method fires an "object reference not set" error (who knows why???)
                Console.WriteLine("\nMIGService ERROR: " + ex.Message + "\n" + ex.StackTrace + "\n");
                // clear possibly corrupted cache items
                ClearWebCache();
            }
            //
            if (cachedItem != null && (DateTime.Now - cachedItem.Timestamp).TotalSeconds < 600)
            {
                fileItem = cachedItem;
            }
            else
            {
                Encoding fileEncoding = DetectWebFileEncoding(file);  //TextFileEncodingDetector.DetectTextFileEncoding(file);
                if (fileEncoding == null)
                {
                    fileEncoding = defaultWebFileEncoding;
                }
                fileItem.Content  = System.IO.File.ReadAllText(file, fileEncoding); //Encoding.UTF8.GetString(buffer, 0, buffer.Length);
                fileItem.Encoding = fileEncoding;
                if (cachedItem != null)
                {
                    webFileCache.Remove(cachedItem);
                }
            }
            return(fileItem);
        }
Пример #2
0
        private void PutWebFileCache(string file, string content, Encoding encoding)
        {
            var cachedItem = webFileCache.Find(wfc => wfc.FilePath == file);

            if (cachedItem == null)
            {
                cachedItem = new WebFileCache();
                webFileCache.Add(cachedItem);
            }
            cachedItem.FilePath = file;
            cachedItem.Content  = content;
            cachedItem.Encoding = encoding;
        }
Пример #3
0
        private void webGateway_ProcessRequest(object gwRequest)
        {
            var    request      = (WebServiceGatewayRequest)gwRequest;
            var    context      = request.Context;
            string requestedUrl = request.UrlRequest;

            var migRequest = new MIGClientRequest()
            {
                Context        = context,
                RequestOrigin  = context.Request.RemoteEndPoint.Address.ToString(),
                RequestMessage = requestedUrl,
                SubjectName    = "HTTP",
                SubjectValue   = context.Request.HttpMethod,
                InputStream    = context.Request.InputStream,
                OutputStream   = context.Response.OutputStream
            };

            // we are expecting url in the forms http://<hgserver>/<hgservicekey>/<servicedomain>/<servicegroup>/<command>/<opt1>/.../<optn>
            // arguments up to <command> are mandatory.
            string migCommand = requestedUrl.Substring(requestedUrl.IndexOf('/', 1) + 1);
            //string section = requestedurl.Substring (0, requestedurl.IndexOf ('/', 1) - 1); TODO: "api" section keyword, ignored for now
            //TODO: implement "api" keyword in MIGInterfaceCommand?
            var command = new MIGInterfaceCommand(migCommand);


            // MIGService namespace Web API
            if (command.Domain == "MIGService.Interfaces")
            {
                context.Response.ContentType = "application/json";
                switch (command.Command)
                {
                case "IsEnabled.Set":
                    if (command.GetOption(0) == "1")
                    {
                        configuration.GetInterface(command.NodeId).IsEnabled = true;
                        EnableInterface(command.NodeId);
                    }
                    else
                    {
                        configuration.GetInterface(command.NodeId).IsEnabled = false;
                        DisableInterface(command.NodeId);
                    }
                    WebServiceUtility.WriteStringToContext(context, "[{ \"ResponseValue\" : \"OK\" }]");
                    //
                    if (InterfacePropertyChanged != null)
                    {
                        InterfacePropertyChanged(new InterfacePropertyChangedAction()
                        {
                            Domain     = "MIGService.Interfaces",
                            SourceId   = command.NodeId,
                            SourceType = "MIG Interface",
                            Path       = "Status.IsEnabled",
                            Value      = command.GetOption(0)
                        });
                    }
                    break;

                case "IsEnabled.Get":
                    WebServiceUtility.WriteStringToContext(context, "[{ \"ResponseValue\" : \"" + (configuration.GetInterface(command.NodeId).IsEnabled ? "1" : "0") + "\" }]");
                    break;

                case "Options.Set":
                    Interfaces[command.NodeId].SetOption(command.GetOption(0), command.GetOption(1));
                    WebServiceUtility.WriteStringToContext(context, "[{ \"ResponseValue\" : \"OK\" }]");
                    //
                    if (InterfacePropertyChanged != null)
                    {
                        InterfacePropertyChanged(new InterfacePropertyChangedAction()
                        {
                            Domain     = "MIGService.Interfaces",
                            SourceId   = command.NodeId,
                            SourceType = "MIG Interface",
                            Path       = "Options." + command.GetOption(0),
                            Value      = command.GetOption(1)
                        });
                    }
                    break;

                case "Options.Get":
                    string optionValue = Interfaces[command.NodeId].GetOption(command.GetOption(0)).Value;
                    WebServiceUtility.WriteStringToContext(context, "[{ \"ResponseValue\" : \"" + Uri.EscapeDataString(optionValue) + "\" }]");
                    break;

                default:
                    break;
                }
                return;
            }


            //PREPROCESS request: if domain != html, execute command
            if (ServiceRequestPreProcess != null)
            {
                ServiceRequestPreProcess(migRequest, command);
                // request was handled by preprocess listener
                if (!string.IsNullOrEmpty(command.Response))
                {
                    // simple automatic json response type detection
                    if (command.Response.StartsWith("[") && command.Response.EndsWith("]") || (command.Response.StartsWith("{") && command.Response.EndsWith("}")))
                    {
                        // TODO: check the reason why this cause ajax/json error on some browser
                        context.Response.ContentType     = "application/json";
                        context.Response.ContentEncoding = defaultWebFileEncoding;
                    }
                    WebServiceUtility.WriteStringToContext(context, command.Response);
                    return;
                }
            }

            // TODO: move dupe code to WebServiceUtility

            //if request begins /hg/html, process
            if (requestedUrl.StartsWith(webServiceConfig.BaseUrl))
            {
                string requestedFile = GetWebFilePath(requestedUrl);
                if (!System.IO.File.Exists(requestedFile))
                {
                    context.Response.StatusCode = 404;
                    //context.Response.OutputStream.WriteByte();
                }
                else
                {
                    bool isText = false;
                    if (requestedUrl.EndsWith(".js")) // || requestedurl.EndsWith(".json"))
                    {
                        context.Response.ContentType = "text/javascript";
                        isText = true;
                    }
                    else if (requestedUrl.EndsWith(".css"))
                    {
                        context.Response.ContentType = "text/css";
                        isText = true;
                    }
                    else if (requestedUrl.EndsWith(".zip"))
                    {
                        context.Response.ContentType = "application/zip";
                    }
                    else if (requestedUrl.EndsWith(".png"))
                    {
                        context.Response.ContentType = "image/png";
                    }
                    else if (requestedUrl.EndsWith(".jpg"))
                    {
                        context.Response.ContentType = "image/jpeg";
                    }
                    else if (requestedUrl.EndsWith(".gif"))
                    {
                        context.Response.ContentType = "image/gif";
                    }
                    else if (requestedUrl.EndsWith(".mp3"))
                    {
                        context.Response.ContentType = "audio/mp3";
                    }
                    else
                    {
                        context.Response.ContentType = "text/html";
                        isText = true;
                    }

                    var file = new System.IO.FileInfo(requestedFile);
                    context.Response.AddHeader("Last-Modified", file.LastWriteTimeUtc.ToString("r"));
                    context.Response.Headers.Set(HttpResponseHeader.LastModified, file.LastWriteTimeUtc.ToString("r"));
                    // PRE PROCESS text output
                    //TODO: add callback for handling caching (eg. function that returns true or false with requestdfile as input and that will return false for widget path)
                    if (isText)
                    {
                        try
                        {
                            WebFileCache cachedItem = GetWebFileCache(requestedFile);
                            context.Response.ContentEncoding = cachedItem.Encoding;
                            context.Response.ContentType    += "; charset=" + cachedItem.Encoding.BodyName;
                            string body = cachedItem.Content;
                            //
                            bool tagFound;
                            do
                            {
                                tagFound = false;
                                int ts = body.IndexOf("{include ");
                                if (ts > 0)
                                {
                                    int te = body.IndexOf("}", ts);
                                    if (te > ts)
                                    {
                                        string rs = body.Substring(ts + (te - ts) + 1);
                                        string cs = body.Substring(ts, te - ts + 1);
                                        string ls = body.Substring(0, ts);
                                        //
                                        try
                                        {
                                            if (cs.StartsWith("{include "))
                                            {
                                                string fileName = cs.Substring(9).TrimEnd('}').Trim();
                                                fileName = GetWebFilePath(fileName);
                                                //
                                                Encoding fileEncoding = DetectWebFileEncoding(fileName);
                                                if (fileEncoding == null)
                                                {
                                                    fileEncoding = defaultWebFileEncoding;
                                                }
                                                body = ls + System.IO.File.ReadAllText(fileName, fileEncoding) + rs;
                                            }
                                        }
                                        catch
                                        {
                                            body = ls + "<h5 style=\"color:red\">Error processing '" + cs.Replace("{", "[").Replace("}", "]") + "'</h5>" + rs;
                                        }
                                        tagFound = true;
                                    }
                                }
                            } while (tagFound); // pre processor tag found
                            //
                            if (webServiceConfig.CacheEnable)
                            {
                                PutWebFileCache(requestedFile, body, context.Response.ContentEncoding);
                            }
                            //
                            WebServiceUtility.WriteStringToContext(context, body);
                        }
                        catch (Exception ex)
                        {
                            // TODO: report internal mig interface  error
                            context.Response.StatusCode = 500;
                            WebServiceUtility.WriteStringToContext(context, ex.Message + "\n" + ex.StackTrace);
                            Console.WriteLine("\nMIGService ERROR: " + ex.Message + "\n" + ex.StackTrace + "\n");
                        }
                    }
                    else
                    {
                        WebServiceUtility.WriteBytesToContext(context, System.IO.File.ReadAllBytes(requestedFile));
                    }
                }
            }

            object responseObject = null;
            bool   wroteBytes     = false;
            //domain == HomeAutomation._Interface_ call InterfaceControl
            var result = (from miginterface in Interfaces.Values
                          let ns = miginterface.GetType().Namespace
                                   let domain = ns.Substring(ns.LastIndexOf(".") + 1) + "." + miginterface.GetType().Name
                                                where (command.Domain != null && command.Domain.StartsWith(domain))
                                                select miginterface).FirstOrDefault();

            if (result != null)
            {
                try
                {
                    responseObject = result.InterfaceControl(command);
                }
                catch (Exception ex)
                {
                    // TODO: report internal mig interface  error
                    context.Response.StatusCode = 500;
                    responseObject = ex.Message + "\n" + ex.StackTrace;
                }
            }
            //
            if (responseObject == null || responseObject.Equals(String.Empty))
            {
                responseObject = WebServiceDynamicApiCall(command);
            }
            //
            if (responseObject != null && responseObject.GetType().Equals(typeof(string)))
            {
                command.Response = (string)responseObject;
                //
                // simple automatic json response type detection
                if (command.Response.StartsWith("[") && command.Response.EndsWith("]") || (command.Response.StartsWith("{") && command.Response.EndsWith("}")))
                {
                    context.Response.ContentType     = "application/json";
                    context.Response.ContentEncoding = defaultWebFileEncoding;
                }
            }
            else
            {
                WebServiceUtility.WriteBytesToContext(context, (Byte[])responseObject);
                wroteBytes = true;
            }
            //
            //POSTPROCESS
            if (ServiceRequestPostProcess != null)
            {
                ServiceRequestPostProcess(migRequest, command);
                if (!string.IsNullOrEmpty(command.Response) && !wroteBytes)
                {
                    // request was handled by postprocess listener
                    WebServiceUtility.WriteStringToContext(context, command.Response);
                    return;
                }
            }
        }
Пример #4
0
 private void PutWebFileCache(string file, string content, Encoding encoding)
 {
     var cachedItem = webFileCache.Find(wfc => wfc.FilePath == file);
     if (cachedItem == null)
     {
         cachedItem = new WebFileCache();
         webFileCache.Add(cachedItem);
     }
     cachedItem.FilePath = file;
     cachedItem.Content = content;
     cachedItem.Encoding = encoding;
 }
Пример #5
0
 //
 private WebFileCache GetWebFileCache(string file)
 {
     WebFileCache fileItem = new WebFileCache(), cachedItem = null;
     try { cachedItem = webFileCache.Find(wfc => wfc.FilePath == file); }
     catch (Exception ex)
     {
         //TODO: sometimes the Find method fires an "object reference not set" error (who knows why???)
         Console.WriteLine("\nMIGService ERROR: " + ex.Message + "\n" + ex.StackTrace + "\n");
         // clear possibly corrupted cache items
         ClearWebCache();
     }
     //
     if (cachedItem != null && (DateTime.Now - cachedItem.Timestamp).TotalSeconds < 600)
     {
         fileItem = cachedItem;
     }
     else
     {
         Encoding fileEncoding = DetectWebFileEncoding(file);  //TextFileEncodingDetector.DetectTextFileEncoding(file);
         if (fileEncoding == null) fileEncoding = defaultWebFileEncoding;
         fileItem.Content = System.IO.File.ReadAllText(file, fileEncoding);  //Encoding.UTF8.GetString(buffer, 0, buffer.Length);
         fileItem.Encoding = fileEncoding;
         if (cachedItem != null)
         {
             webFileCache.Remove(cachedItem);
         }
     }
     return fileItem;
 }
Пример #6
0
 private WebFileCache GetWebFileCache(string file)
 {
     WebFileCache fileItem = new WebFileCache();
     var cachedItem = webFileCache.Find(wfc => wfc.FilePath == file);
     if (cachedItem != null && (DateTime.Now - cachedItem.Timestamp).TotalSeconds < 600)
     {
         fileItem = cachedItem;
     }
     else
     {
         Encoding fileEncoding = DetectWebFileEncoding(file);  //TextFileEncodingDetector.DetectTextFileEncoding(file);
         if (fileEncoding == null) fileEncoding = defaultWebFileEncoding;
         fileItem.Content = System.IO.File.ReadAllText(file, fileEncoding);  //Encoding.UTF8.GetString(buffer, 0, buffer.Length);
         fileItem.Encoding = fileEncoding;
         if (cachedItem != null)
         {
             webFileCache.Remove(cachedItem);
         }
     }
     return fileItem;
 }