Exemplo n.º 1
0
        public static void HandleRequest(string pageName, SimpleHttp.HttpProcessor p, Session s)
        {
            string pageKey = pageName.ToLower();

            if (s.permission < 100)
            {
                pageKey = "login";
            }

            Type type;

            if (!pageKeyToType.TryGetValue(pageKey, out type))
            {
                p.writeFailure();
                return;
            }
            ConstructorInfo ctor     = type.GetConstructor(new Type[0]);
            object          instance = ctor.Invoke(null);
            AdminBase       page     = (AdminBase)instance;
            string          str      = page.GetHtml(p, s, pageKey);

            if (str == null)
            {
                p.writeFailure("500 Internal Server Error");
                return;
            }
            p.writeSuccess();
            p.outputStream.Write(str);
        }
Exemplo n.º 2
0
        protected override string GetPageHtml(SimpleHttp.HttpProcessor p, Session s)
        {
            ItemTable <PTZProfile> tbl = new ItemTable <PTZProfile>("PTZ Profiles", "ptzprofile", "name", PTZProfile.GetPtzProfiles(), PTZProfile.lockObj, ItemTableMode.Add, new ItemTableColumnDefinition <PTZProfile>[]
            {
                new ItemTableColumnDefinition <PTZProfile>("Name", c => { return("<a href=\"javascript:EditItem('" + HttpUtility.JavaScriptStringEncode(c.spec.name) + "')\">" + HttpUtility.HtmlEncode(c.spec.name) + "</a>"); })
            });

            return(tbl.GetSectionHtml());
        }
Exemplo n.º 3
0
        protected virtual string GetMenuHtml(SimpleHttp.HttpProcessor p, Session s, string pageKey)
        {
            StringBuilder sb = new StringBuilder();

            foreach (string key in AdminPage.pageKeys)
            {
                AddLink(sb, pageKey, 1, AdminPage.pageKeyToName[key], key);
            }
            return(sb.ToString());
        }
Exemplo n.º 4
0
        protected override string GetPageHtml(SimpleHttp.HttpProcessor p, Session s)
        {
            ItemTable <Configuration.User> tbl = new ItemTable <Configuration.User>("Users", "user", "name", MJpegWrapper.cfg.users, MJpegWrapper.cfg, ItemTableMode.Add, new ItemTableColumnDefinition <Configuration.User>[]
            {
                new ItemTableColumnDefinition <Configuration.User>("Name", u => { return("<a href=\"javascript:EditItem('" + u.name + "')\">" + HttpUtility.HtmlEncode(u.name) + "</a>"); }),
                new ItemTableColumnDefinition <Configuration.User>("Permission", u => { return(u.permission.ToString()); }),
                new ItemTableColumnDefinition <Configuration.User>("Session Length (Minutes)", u => { return(u.sessionLengthMinutes.ToString()); })
            });

            return(tbl.GetSectionHtml());
        }
Exemplo n.º 5
0
        protected override string GetPageHtml(SimpleHttp.HttpProcessor p, Session s)
        {
            SortedList <string, int> wwwFileSortedList = new SortedList <string, int>();

            // Add configured files to list
            lock (MJpegWrapper.cfg)
            {
                foreach (var item in MJpegWrapper.cfg.GetWwwFilesList())
                {
                    wwwFileSortedList.Add(item.Key, item.Value);
                }
            }
            // Add filesystem files to list
            HashSet <string> existingFiles = new HashSet <string>();
            DirectoryInfo    diWWW         = new DirectoryInfo(Globals.WWWDirectoryBase);
            string           directoryBase = Globals.WWWDirectoryBase.ToLower().Replace('\\', '/');

            foreach (FileInfo fi in diWWW.GetFiles("*", SearchOption.AllDirectories))
            {
                string fileName = fi.FullName.ToLower().Replace('\\', '/');
                if (!fileName.StartsWith(directoryBase))
                {
                    continue;
                }
                fileName = fileName.Substring(directoryBase.Length);
                existingFiles.Add(fileName);
                if (!wwwFileSortedList.ContainsKey(fileName))
                {
                    wwwFileSortedList.Add(fileName, 100);
                }
            }
            // Create list of WwwFile so we can easily list them in a table.
            List <WwwFile>       wwwFileList       = new List <WwwFile>();
            List <SimpleWwwFile> simpleWwwFileList = new List <SimpleWwwFile>();

            foreach (var item in wwwFileSortedList)
            {
                wwwFileList.Add(new WwwFile(item.Key, item.Value, existingFiles.Contains(item.Key)));
                simpleWwwFileList.Add(new SimpleWwwFile(item.Key, item.Value));
            }

            // Save the current files list
            MJpegWrapper.cfg.SetWwwFilesList(simpleWwwFileList);
            MJpegWrapper.cfg.Save(Globals.ConfigFilePath);

            ItemTable <WwwFile> tbl = new ItemTable <WwwFile>("Web Server Files", "wwwfile", "fileName", wwwFileList, wwwFileList, ItemTableMode.Save, new ItemTableColumnDefinition <WwwFile>[]
            {
                new ItemTableColumnDefinition <WwwFile>("File", c => { return((!c.verifiedExisting ? "<span style=\"color:Red\" title=\"Files in red no longer exist, but they are configured with a stored permission\" >" : "") + HttpUtility.HtmlEncode(c.fileName) + (!c.verifiedExisting ? "</span>" : "")); }),
                new ItemTableColumnDefinition <WwwFile>("Permission Required", c => { return("<input saveitemfield=\"permission\" saveitemkey=\"" + HttpUtility.JavaScriptStringEncode(c.fileName) + "\" type=\"number\" min=\"0\" max=\"100\" value=\"" + (c.permission > 100 ? 100 : (c.permission < 0 ? 0 : c.permission)) + "\" />"); })
            });

            return(tbl.GetSectionHtml() + "<div>* Note: Only files with a red name can be deleted from this list.  Files have a red name when they no longer exist in the www directory.</div>");
        }
Exemplo n.º 6
0
        public string ReorderCam(SimpleHttp.HttpProcessor p)
        {
            lock (this)
            {
                string id = p.GetPostParam("id").ToLower();
                if (string.IsNullOrEmpty(id))
                {
                    return("0Missing id parameter");
                }
                string dir = p.GetPostParam("dir");
                if (string.IsNullOrEmpty(dir))
                {
                    return("0Missing dir parameter");
                }

                int diff = (dir == "up" ? -1 : (dir == "down" ? 1 : 0));

                if (diff == 0)
                {
                    return("0Invalid dir parameter");
                }

                bool found = false;
                foreach (CameraSpec spec in cameras)
                {
                    if (spec.id.ToLower() == id)
                    {
                        int oldOrder = spec.order;
                        int newOrder = oldOrder + diff;
                        foreach (CameraSpec swapWith in cameras)
                        {
                            if (swapWith.order == newOrder)
                            {
                                swapWith.order = oldOrder;
                            }
                        }
                        spec.order = newOrder;
                        found      = true;
                        break;
                    }
                }
                if (!found)
                {
                    return("0Invalid id parameter");
                }

                MJpegServer.cm.CleanUpCameraOrder();

                Save(Globals.ConfigFilePath);
                return("1");
            }
        }
Exemplo n.º 7
0
        public string GetHtml(SimpleHttp.HttpProcessor p, Session s, string pageKey)
        {
            try
            {
                return(@"<!DOCTYPE HTML>
<html>
<head>
	<title>CameraProxy Administration</title>
	"
                       + GetScriptCallouts(Globals.jQueryPath, "../Scripts/sha1.js", "../Scripts/TableSorter.js", Globals.jQueryUIJsPath)
                       + GetStyleCallouts("../Styles/TableSorter_Green.css", Globals.jQueryUICssPath, "../Styles/Site.css")
                       + GetAdminScript(p, s, pageKey)
                       + @"
</head>
<body>
<table id=""layoutroot"">
	<tbody>
		<tr>
			<td colspan=""2"" id=""header"">
				<div class=""title"">CameraProxy</div>
				<div class=""version"">Version "                 + Globals.Version + @"</div>
			</td>
		</tr>
		<tr id=""bodycell"">
			<td id=""menu"">
				"
                       + GetMenuHtml(p, s, pageKey)
                       + @"
			</td>
			<td id=""content"">
				"
                       + GetPageHtml(p, s)
                       + @"
			</td>
		</tr>
		<tr>
			<td colspan=""2"" id=""footer"">
				MJpegCameraProxy "                 + Globals.Version + @"
			</td>
		</tr>
	</tbody>
</table>
</body>
</html>");
            }
            catch (Exception ex)
            {
                Logger.Debug(ex);
            }
            return(null);
        }
Exemplo n.º 8
0
        protected override string GetPageHtml(SimpleHttp.HttpProcessor p, Session s)
        {
            ItemTable <CameraSpec> tbl = new ItemTable <CameraSpec>("Cameras", "camera", "id", MJpegWrapper.cfg.cameras, MJpegWrapper.cfg, ItemTableMode.Add, new ItemTableColumnDefinition <CameraSpec>[]
            {
                new ItemTableColumnDefinition <CameraSpec>(" ", c => { return("<a href=\"../image/" + c.id + ".cam\"><img src=\"../image/" + c.id + ".jpg?maxwidth=40&maxheight=40&nocache=" + DateTime.Now.ToBinary().ToString() + "\" alt=\"[img]\" /></a>"); }),
                new ItemTableColumnDefinition <CameraSpec>("Name", c => { return("<a href=\"javascript:EditItem('" + c.id + "')\">" + HttpUtility.HtmlEncode(c.name) + "</a>"); }),
                new ItemTableColumnDefinition <CameraSpec>("ID", c => { return(c.id); }),
                new ItemTableColumnDefinition <CameraSpec>("Enabled", c => { return(c.enabled ? ("<span style=\"color:Green;\">Enabled</span>") : "<span style=\"color:Red;\">Disabled</span>"); }),
                new ItemTableColumnDefinition <CameraSpec>("Type", c => { return(c.type.ToString() + (c.type == CameraType.h264_rtsp_proxy ? ":" + c.h264_port : "")); }),
                new ItemTableColumnDefinition <CameraSpec>("Ptz", c => { return(c.ptzType.ToString()); }),
                new ItemTableColumnDefinition <CameraSpec>("TTL", c => { return(c.maxBufferTime.ToString()); }),
                new ItemTableColumnDefinition <CameraSpec>("Permission", c => { return(c.minPermissionLevel.ToString()); }),
                new ItemTableColumnDefinition <CameraSpec>("Url", c => { return(c.imageryUrl); }),
                new ItemTableColumnDefinition <CameraSpec>("Order", c => { return("<a href=\"javascript:void(0)\" onclick=\"$.post('reordercam', { dir: 'up', id: '" + c.id + "' }).done(function(){location.href=location.href;});\">Up</a><br/><a href=\"javascript:void(0)\" onclick=\"$.post('reordercam', { dir: 'down', id: '" + c.id + "' }).done(function(){location.href=location.href;});\">Down</a>"); })
            });

            return(tbl.GetSectionHtml());
        }
Exemplo n.º 9
0
        public static string HandleSaveList(SimpleHttp.HttpProcessor p, Session s)
        {
            string pageKey = p.GetPostParam("pagename").ToLower();

            if (s.permission < 100)
            {
                return("0Insufficient Permission");
            }

            Type type;

            if (!pageKeyToType.TryGetValue(pageKey, out type))
            {
                return("0Invalid pagename");
            }

            ConstructorInfo ctor     = type.GetConstructor(new Type[0]);
            object          instance = ctor.Invoke(null);
            AdminBase       page     = (AdminBase)instance;

            SortedList <string, SortedList <string, string> > items = new SortedList <string, SortedList <string, string> >();

            string rawFullItemString = p.GetPostParam("items");

            string[] itemStrings = rawFullItemString.Split('|');
            foreach (string itemString in itemStrings)
            {
                SortedList <string, string> valuesList = new SortedList <string, string>();
                string[] keyValuePairs = itemString.Split('*');
                for (int i = 1; i < keyValuePairs.Length; i++)
                {
                    string[] keyAndValue = keyValuePairs[i].Split(':');
                    valuesList.Add(keyAndValue[0], keyAndValue[1]);
                }
                items.Add(keyValuePairs[0], valuesList);
            }

            page.HandleSave(p, s, items);

            return("1");
        }
Exemplo n.º 10
0
        public string GetRTSPUrl(string id, SimpleHttp.HttpProcessor p)
        {
            IPCameraBase cam = GetCameraById(id);

            if (cam == null || cam.cameraSpec.type != CameraType.h264_rtsp_proxy)
            {
                return("");
            }
            cam.ImageLastViewed = DateTime.Now;
            if (!cam.isRunning)
            {
                cam.Start();
                int timesWaited = 0;
                Thread.Sleep(50);
                while (timesWaited++ < 50)
                {
                    Thread.Sleep(20);
                }
                cam.ImageLastViewed = DateTime.Now;
            }
            H264Camera h264cam = (H264Camera)cam;

            return("rtsp://" + h264cam.access_username + ":" + h264cam.access_password + "@$$$HOST$$$:" + cam.cameraSpec.h264_port + "/proxyStream");
        }
Exemplo n.º 11
0
        internal override void HandleSave(SimpleHttp.HttpProcessor p, Session s, SortedList <string, SortedList <string, string> > items)
        {
            SortedList <string, int> newWWWFiles = new SortedList <string, int>();

            foreach (var item in items)
            {
                int permission;
                if (int.TryParse(item.Value["permission"], out permission))
                {
                    newWWWFiles.Add(item.Key.ToLower(), permission);
                }
            }
            List <SimpleWwwFile> wwwFileList = new List <SimpleWwwFile>();

            foreach (var item in newWWWFiles)
            {
                wwwFileList.Add(new SimpleWwwFile(item.Key, item.Value));
            }
            lock (MJpegWrapper.cfg)
            {
                MJpegWrapper.cfg.SetWwwFilesList(wwwFileList);
                MJpegWrapper.cfg.Save(Globals.ConfigFilePath);
            }
        }
Exemplo n.º 12
0
        public string SaveItem(SimpleHttp.HttpProcessor p)
        {
            bool   isNew = p.GetBoolParam("new");
            string originalIdNotLowerCase = p.GetPostParam("itemid");
            string originalId             = originalIdNotLowerCase.ToLower();
            string itemtype = p.GetPostParam("itemtype");

            if (itemtype == "camera")
            {
                CameraSpec cs     = new CameraSpec();
                string     result = cs.setFieldValues(p.RawPostParams);
                if (result.StartsWith("0"))
                {
                    return(result);
                }
                lock (this)
                {
                    if (isNew)
                    {
                        cs.id = originalId;
                        if (CameraIdIsUsed(cs.id))
                        {
                            return("0A camera with this ID already exists.");
                        }
                        cameras.Add(cs);
                    }
                    else
                    {
                        if (originalId != cs.id && CameraIdIsUsed(cs.id))
                        {
                            return("0A camera with this ID already exists.");
                        }
                        bool foundCamera = false;
                        for (int i = 0; i < cameras.Count; i++)
                        {
                            if (cameras[i].id == originalId)
                            {
                                cs.order    = cameras[i].order;
                                foundCamera = true;
                                MJpegServer.cm.KillCamera(originalId);
                                cameras[i] = cs;
                                break;
                            }
                        }
                        if (!foundCamera)
                        {
                            cameras.Add(cs);
                        }
                    }
                    MJpegServer.cm.CleanUpCameraOrder();
                    Save(Globals.ConfigFilePath);
                }
                return(result);
            }
            else if (itemtype == "user")
            {
                Configuration.User u      = new Configuration.User();
                string             result = u.setFieldValues(p.RawPostParams);
                if (result.StartsWith("0"))
                {
                    return(result);
                }
                lock (this)
                {
                    if (isNew)
                    {
                        u.name = originalId;
                        if (UserNameIsUsed(u.name))
                        {
                            return("0A user with this name already exists.");
                        }
                        users.Add(u);
                    }
                    else
                    {
                        if (originalId != u.name && UserNameIsUsed(u.name))
                        {
                            return("0A user with this name already exists.");
                        }
                        bool foundUser = false;
                        for (int i = 0; i < users.Count; i++)
                        {
                            if (users[i].name == originalId)
                            {
                                foundUser = true;
                                users[i]  = u;
                                break;
                            }
                        }
                        if (!foundUser)
                        {
                            users.Add(u);
                        }
                    }
                    Save(Globals.ConfigFilePath);
                }
                return(result);
            }
            else if (itemtype == "ptzprofile")
            {
                PTZProfile f       = new PTZProfile();
                int        version = p.GetPostIntParam("version", 1);
                if (version == 1)
                {
                    f.spec = new PTZSpecV1();
                }
                string result = f.spec.setFieldValues(p.RawPostParams);

                if (result.StartsWith("0"))
                {
                    return(result);
                }
                lock (this)
                {
                    if (isNew)
                    {
                        f.name = originalIdNotLowerCase;
                        if (ProfileNameIsUsed(f.name))
                        {
                            return("0A PTZ Profile with this name already exists.");
                        }
                        f.Save(Globals.PTZProfilesDirectoryBase + f.name + ".xml");
                    }
                    else
                    {
                        if (originalId != f.name.ToLower() && ProfileNameIsUsed(f.name))
                        {
                            return("0A PTZ Profile with this name already exists.");
                        }
                        File.Delete(Globals.PTZProfilesDirectoryBase + originalId + ".xml");
                        f.Save(Globals.PTZProfilesDirectoryBase + f.name + ".xml");
                    }
                }
                return(result);
            }
            return("0Invalid item type: " + itemtype);
        }
Exemplo n.º 13
0
 protected override string GetPageHtml(SimpleHttp.HttpProcessor p, Session s)
 {
     p.responseCookies.Add("cps", "", TimeSpan.Zero);
     p.responseCookies.Add("auth", "", TimeSpan.Zero);
     return(MJpegCameraProxy.Login.GetLoginScripts("main") + "<div style=\"margin-bottom: 10px;\">Please log in to continue:</div>" + MJpegCameraProxy.Login.GetLoginBody());
 }
Exemplo n.º 14
0
        public CamPage2(string html, SimpleHttp.HttpProcessor p)
        {
            // Set the parameters so the eval statements later can access them.
            cameraId = p.GetParam("cam");
            IPCameraBase cam = MJpegServer.cm.GetCameraAndGetItRunning(cameraId);

            if (cam == null)
            {
                Html = "The specified camera is not available.";
                return;
            }
            disableRefreshAfter = p.GetIntParam("override", 600000);
            string userAgent       = p.GetHeaderValue("User-Agent", "");
            bool   isMobile        = userAgent.Contains("iPad") || userAgent.Contains("iPhone") || userAgent.Contains("Android") || userAgent.Contains("BlackBerry");
            bool   isLanConnection = p == null ? false : p.IsLanConnection;
            int    defaultRefresh  = isLanConnection && !isMobile ? 0 : 250;

            refreshDelay = p.GetIntParam("refresh", defaultRefresh);
            cameraName   = cam.cameraSpec.name;
            if (cam.cameraSpec.type == CameraType.h264_rtsp_proxy)
            {
                bool sizeOverridden = cam.cameraSpec.h264_video_width > 0 && cam.cameraSpec.h264_video_height > 0;
                originWidth  = sizeOverridden ? cam.cameraSpec.h264_video_width : 640;
                originHeight = sizeOverridden ? cam.cameraSpec.h264_video_height : 360;
            }
            else
            {
                for (int i = 0; i < 50; i++)
                {
                    if (cam.ImageSize.Width != 0 && cam.ImageSize.Height != 0)
                    {
                        break;
                    }
                    Thread.Sleep(100);
                }
                if (cam.ImageSize.Width == 0 || cam.ImageSize.Height == 0)
                {
                    Html = @"<!DOCTYPE HTML>
						<html>
						<head>
							<title>"                             + HttpUtility.HtmlEncode(cam.cameraSpec.name) + @"</title>
						</head>
						<body>
						This camera is starting up.<br/>
						Please <a href=""javascript:top.location.reload();"">try again in a few moments</a>.
						</body>
						</html>"                        ;
                    return;
                }
                originWidth  = cam.ImageSize.Width;
                originHeight = cam.ImageSize.Height;
            }
            webSocketUrl = "ws" + (p.secure_https ? "s" : "") + "://\" + location.hostname + \":" + (p.secure_https ? MJpegWrapper.cfg.webSocketPort_secure : MJpegWrapper.cfg.webSocketPort);

            thumbnailBoxPercentWidth  = cam.cameraSpec.ptz_panorama_selection_rectangle_width_percent;
            thumbnailBoxPercentHeight = cam.cameraSpec.ptz_panorama_selection_rectangle_height_percent;
            zoomMagnification         = cam.cameraSpec.ptz_magnification;

            // Evaluate the <%...%> expressions present in the html markup
            CSE.CsEval.EvalEnvironment = this;
            StringBuilder sb = new StringBuilder();
            int           idxCopyFrom = 0;
            int           idxStart = 0, idxEnd = 0;

            idxStart = html.IndexOf("<%");
            while (idxStart != -1)
            {
                sb.Append(html.Substring(idxCopyFrom, idxStart - idxCopyFrom));

                idxEnd = html.IndexOf("%>", idxStart + 2);
                if (idxEnd == -1)
                {
                    idxCopyFrom = idxStart;
                    break;
                }
                else
                {
                    string expression = html.Substring(idxStart + 2, idxEnd - (idxStart + 2)).Trim();
                    try
                    {
                        sb.Append(CSE.CsEval.Eval(expression));
                    }
                    catch (Exception)
                    {
                        Html = "<h1>Internal Server Errror</h1><p>The page you requested has errors and is unable to be produced.</p>";
                        return;
                    }
                    idxCopyFrom = idxEnd + 2;
                    idxStart    = html.IndexOf("<%", idxEnd + 2);
                }
            }
            if (idxCopyFrom < html.Length)
            {
                sb.Append(html.Substring(idxCopyFrom));
            }


            this.Html = sb.ToString();
        }
Exemplo n.º 15
0
        protected override string GetPageHtml(SimpleHttp.HttpProcessor p, Session s)
        {
            sb.Clear();
            string itemtype = p.GetParam("itemtype");
            string itemid   = p.GetParam("itemid").ToLower();

            sb.Append("<div id=\"itemtype\" itemtype=\"").Append(itemtype).Append("\" style=\"display:none;\"></div>");
            sb.Append("<div id=\"itemid\" itemid=\"").Append(itemid).Append("\" style=\"display:none;\"></div>");
            sb.Append("<div id=\"itemfields\">");
            if (itemtype == "camera")
            {
                sb.AppendLine("<div style=\"display:none;\" id=\"pageToLoadWhenFinished\" page=\"cameras\"></div>");
                bool foundCamera = false;
                lock (MJpegWrapper.cfg)
                {
                    foreach (CameraSpec cs in MJpegWrapper.cfg.cameras)
                    {
                        if (cs.id == itemid)
                        {
                            foundCamera = true;
                            CreateItemEditor(cs);
                            break;
                        }
                    }
                }
                if (!foundCamera)
                {
                    sb.Append("Could not find camera");
                }
                return(sb.ToString());
            }
            else if (itemtype == "user")
            {
                sb.AppendLine("<div style=\"display:none;\" id=\"pageToLoadWhenFinished\" page=\"users\"></div>");
                bool foundUser = false;
                lock (MJpegWrapper.cfg)
                {
                    foreach (Configuration.User u in MJpegWrapper.cfg.users)
                    {
                        if (u.name == itemid)
                        {
                            foundUser = true;
                            CreateItemEditor(u);
                            break;
                        }
                    }
                }
                if (!foundUser)
                {
                    sb.Append("Could not find user");
                }
                return(sb.ToString());
            }
            else if (itemtype == "ptzprofile")
            {
                sb.AppendLine("<div style=\"display:none;\" id=\"pageToLoadWhenFinished\" page=\"ptzprofiles\"></div>");
                bool foundProfile = false;
                lock (MJpegWrapper.cfg)
                {
                    foreach (Configuration.PTZProfile f in PTZProfile.GetPtzProfiles())
                    {
                        if (f.spec.name.ToLower() == itemid)
                        {
                            foundProfile = true;
                            CreateItemEditor(f.spec);
                            break;
                        }
                    }
                }
                if (!foundProfile)
                {
                    sb.Append("Could not find PTZ Profile");
                }
                return(sb.ToString());
            }
            else
            {
                sb.AppendLine("<div style=\"display:none;\" id=\"pageToLoadWhenFinished\" page=\"main\"></div>");
            }
            sb.Append("</div>");
            return(sb.ToString());
        }
Exemplo n.º 16
0
 protected abstract string GetPageHtml(SimpleHttp.HttpProcessor p, Session s);
Exemplo n.º 17
0
        /// <summary>
        /// Returns an image when it is deemed necessary to send it to the client.
        /// </summary>
        /// <returns></returns>
        public byte[] GetImageAuto(SimpleHttp.HttpProcessor p)
        {
            Stopwatch watch = new Stopwatch();

            watch.Start();
            while (!PhotoFrameWrapper.isStopping)
            {
                Alert topAlert = alertManager.GetTopActiveAlertOrNull();
                if (topAlert != null)
                {
                    // We are going to send an alert image.  But first, make sure the photo frame state is preserved.
                    if (!nextPhotoFrameImageDelay.ContainsKey(p.RemoteIPAddress))
                    {
                        // No state has been preserved.  Preserve it!
                        ImageLoadInfo ili;
                        TimeSpan      span = TimeSpan.Zero;
                        if (lastLoadedImages.TryGetValue(p.RemoteIPAddress, out ili))
                        {
                            TimeSpan timeToWait          = TimeSpan.FromMilliseconds(millisecondsBetweenPhotoUpdates);
                            TimeSpan timeWaitedAlready   = DateTime.Now - ili.lastLoadTime;
                            TimeSpan timeRemainingToWait = timeToWait - timeWaitedAlready;
                            if (timeRemainingToWait < TimeSpan.Zero)
                            {
                                timeRemainingToWait = TimeSpan.Zero;
                            }
                            span = timeRemainingToWait;
                        }
                        nextPhotoFrameImageDelay.AddOrUpdate(p.RemoteIPAddress, span, (s, ts) => { return(span); });
                    }

                    byte[] imgData = SimpleProxy.GetData(PhotoFrameWrapper.cfg.blueIrisAddress + "image/" + topAlert.cameraShortName);
                    return(imgData);
                }
                else
                {
                    // Determine if it is time to move to another photo.
                    ImageLoadInfo ili;
                    if (lastLoadedImages.TryGetValue(p.RemoteIPAddress, out ili))
                    {
                        // Restore state if necessary
                        TimeSpan span;
                        if (nextPhotoFrameImageDelay.TryGetValue(p.RemoteIPAddress, out span))
                        {
                            // Restore the state
                            nextPhotoFrameImageDelay.TryRemove(p.RemoteIPAddress, out span);

                            TimeSpan timeToWait          = TimeSpan.FromMilliseconds(millisecondsBetweenPhotoUpdates);
                            TimeSpan timeWaitedAlready   = span;
                            TimeSpan timeRemainingToWait = timeToWait - timeWaitedAlready;
                            ili.lastLoadTime = DateTime.Now - timeRemainingToWait;
                            lastLoadedImages.AddOrUpdate(p.RemoteIPAddress, ili, (o1, o2) => { return(ili); });

                            // A motion alert just ended, so send the photo frame image to the client again.
                            byte[] restoreImageData = File.ReadAllBytes(ili.lastImage.FullName);
                            return(restoreImageData);
                        }
                        if (ili.lastLoadTime.AddMilliseconds(millisecondsBetweenPhotoUpdates) > DateTime.Now)
                        {
                            // Not yet time.
                            Thread.Sleep(100);
                            continue;
                        }
                        else
                        {
                            // There was a previous image and it is time to move on.
                            ili = ili.GetNext();
                        }
                    }
                    else
                    {
                        // No previous image
                        ili = GetRandomImage();
                    }
                    if (ili == null)
                    {
                        return(new byte[0]);
                    }

                    ili.lastLoadTime = DateTime.Now;
                    lastLoadedImages.AddOrUpdate(p.RemoteIPAddress, ili, (o1, o2) => { return(ili); });
                    // If we get here, then we need to send a photo frame image to the client.
                    byte[] imgData = File.ReadAllBytes(ili.lastImage.FullName);
                    return(imgData);
                }
            }
            return(new byte[0]);
        }
Exemplo n.º 18
0
 internal virtual void HandleSave(SimpleHttp.HttpProcessor p, Session s, SortedList <string, SortedList <string, string> > items)
 {
     throw new Exception("HandleSave is not implemented by this class!");
 }
Exemplo n.º 19
0
        private string GetAdminScript(SimpleHttp.HttpProcessor p, Session s, string pageKey)
        {
            return(@"<script type=""text/javascript"">
	var isCreatingItem = false;
	$(function()
	{
		$('#newItemDialog').dialog(
		{
			modal: true,
			autoOpen: false,
			buttons:
			{
				'Cancel': function()
				{
					if(isCreatingItem)
						return;
					$(this).dialog('close');
				},
				'Accept': function()
				{
					if(isCreatingItem)
						return;
					isCreatingItem = true;
					CreateItem();
				}
			}
		});
	});
	function EditItem(itemId)
	{
		top.location.href=""edititem?itemtype="" + $('#newItemDialog').attr('itemtype') + ""&itemid="" + itemId;
	}
	function AddItem()
	{
		$('#newItemDialog').dialog('open');
	}
	function CreateItem()
	{
		$.post(""saveitem?new=1"", { itemid: $('#newId').val(), itemtype: $('#newItemDialog').attr('itemtype') }).done(gotCreateItem).fail(failCreateItem);
	}
	function gotCreateItem(data, textStatus, jqXHR)
	{
		$('#newItemErrorMessage').html('');
		if(data[0] == '1')
			EditItem($('#newId').val());
		else
		{
			isCreatingItem = false;
			$('#newItemErrorMessage').html(data.substr(1));
		}
	}
	function failCreateItem()
	{
		isCreatingItem = false;
		failedContent();
	}
	var isDeleting = false;
	function DeleteSelected(itemtype)
	{
		if(isDeleting)
			return;
		var deletions = new Array();
		$('.listItemSelectionCheckbox_' + itemtype).each(function(idx, ele)
		{
			if($(ele).is(':checked'))
				deletions.push($(ele).attr('itemid'));
		});
		if(deletions.length > 0)
		{
			if(confirm('Please confirm that you wish to delete ' + deletions.join(', ')))
			{
				isDeleting = true;
				$.post('deleteitems', { itemtype: itemtype, ids: deletions.join(',') }).done(gotDeleteItems).fail(failedContent);
			}
		}
		else
			alert('Nothing is selected!');
	}
	function gotDeleteItems(data, textStatus, jqXHR)
	{
		$('#errorMessage').html('');
		if(data[0] == '1')
			location.href = location.href;
		else
		{
			isDeleting = false;
			$('#errorMessage').html(data.substr(1));
		}
	}
	function failedContent()
	{
		alert('Failed to load page!');
	}
	function SaveList()
	{
		var outerStr = new Array();
		var items = new Object();
		$('*[saveitemfield][saveitemkey]').each(function(idx, ele)
		{
			var itemkey = $(ele).attr('saveitemkey');
			if(typeof(items[itemkey]) == 'undefined')
				items[itemkey] = new Object();
			items[itemkey][$(ele).attr('saveitemfield')] = $(ele).val();
		});
		var outerChildren = Object.keys(items);
		for (var i = 0; i < outerChildren.length; i++)
		{
			var child = outerChildren[i];
			var innerStr = new Array();
			var innerChildren = Object.keys(items[child]);
			for (var j = 0; j < innerChildren.length; j++)
			{
				var innerChild = innerChildren[j];
				innerStr.push(innerChild + ':' + items[child][innerChild]);
			}
			outerStr.push(child + '*' + innerStr.join('*'));
		}
		var finalStr = outerStr.join('|');
		console.log(finalStr);
		$.post('savelist', {pagename: '"         + pageKey + @"', items: finalStr}).done(function(data)
		{
			if(data.indexOf('0') == 0)
				alert(data.substr(1));
			if(data.indexOf('1') == 0)
				alert('Saved');
		});
	}
</script>");
        }
Exemplo n.º 20
0
        public string DeleteItems(SimpleHttp.HttpProcessor p)
        {
            string itemtype = p.GetPostParam("itemtype");
            string ids      = p.GetPostParam("ids").ToLower();

            if (ids == null || ids.Length < 1)
            {
                return("0No items were specified for deletion");
            }
            string[]         parts   = ids.Split(',');
            HashSet <string> hsParts = new HashSet <string>(parts);

            if (itemtype == "camera")
            {
                lock (this)
                {
                    cameras.RemoveAll(cs =>
                    {
                        bool remove = hsParts.Contains(cs.id);
                        if (remove)
                        {
                            MJpegServer.cm.KillCamera(cs.id);
                        }
                        return(remove);
                    });
                    MJpegServer.cm.CleanUpCameraOrder();
                    Save(Globals.ConfigFilePath);
                }
            }
            else if (itemtype == "user")
            {
                lock (this)
                {
                    users.RemoveAll(u =>
                    {
                        return(hsParts.Contains(u.name));
                    });
                    Save(Globals.ConfigFilePath);
                }
            }
            else if (itemtype == "ptzprofile")
            {
                lock (this)
                {
                    foreach (string s in parts)
                    {
                        if (ProfileNameIsUsed(s))
                        {
                            File.Delete(Globals.PTZProfilesDirectoryBase + s + ".xml");
                        }
                    }
                }
            }
            else if (itemtype == "wwwfile")
            {
                lock (this)
                {
                    wwwFiles.RemoveAll(f =>
                    {
                        return(hsParts.Contains(f.Key) && !File.Exists(Globals.WWWDirectoryBase + f.Key));
                    });
                    Save(Globals.ConfigFilePath);
                }
            }
            return("1");
        }
Exemplo n.º 21
0
        protected override string GetPageHtml(SimpleHttp.HttpProcessor p, Session s)
        {
            return(@"
	<script type=""text/javascript"">
	var camDefs = "     + MJpegServer.cm.GenerateAllCameraIdNameList(s == null ? 0 : s.permission) + @";
	var remoteIp = '"     + p.RemoteIPAddress + @"';
	var refreshDisabled = false;
	var refreshTime = 2500;
	$(function()
	{
		setTimeout(""disableRefresh()"", 300000);
		var isLocal = remoteIp.indexOf(""192.168.0."") > -1;
		for(var i = 0; i < camDefs.length; i++)
		{
			var myid = camDefs[i][0];
			$(""#maindiv"").append('<div class=""outer""><a href=""../image/' + myid + '.cam""><table><tbody><tr><td class=""imgbox""><img id=""' + myid + '"" alt=""' + camDefs[i][1] + '""></td></tr></tbody></table><div class=""caption"">' + camDefs[i][1] + '</div></a></div>');
			if(isLocal)
				refreshTime = 250;
			$(""#"" + myid).load(function ()
			{
				if(!refreshDisabled)
				{
					lastUpdate = new Date().getTime();
					setTimeout(""GetNewImage('"" + this.id + ""');"", refreshTime);
				}
			});
			$(""#"" + myid).error(function ()
			{
				setTimeout(""GetNewImage('"" + this.id + ""');"", refreshTime);
			});
			GetNewImage(myid);
		}
	});
	function GetNewImage(id)
	{
		$(""#"" + id).attr('src', '../image/' + id + '.jpg?maxwidth=320&maxheight=240&nocache=' + new Date().getTime());
	}
	function disableRefresh()
	{
		$(""#maindiv"").prepend('<div style=""color: Red;"">Camera Updating Stopped to conserve resources</div>');
		refreshDisabled = true;
	}
	function PopupMessage(msg)
	{
		var pm = $(""#popupMessage"");
		if(pm.length < 1)
			$(""#maindiv"").after('<div id=""popupFrame""><div id=""popupMessage"">' + msg + '</div><center><input type=""button"" value=""Close Message"" onclick=""CloseMessage()""/></center></div>');
		else
			pm.append(msg);
	}
	function CloseMessage()
	{
		$(""#popupFrame"").remove();
	}
	</script>
	<style type=""text/css"">
	img
	{
		max-width: 320px;
		max-height: 240px;
		vertical-align: middle;
	}
	.caption
	{
		text-align: center;
	}
	a
	{
		text-decoration: none;
		color: Black;
	}
	.imgbox
	{
		width: 320px;
		height: 240px;
	}
	.outer
	{
		display: inline-block;
		padding-right: 20px;
		padding-bottom: 20px;
	}
	</style>
	<div id=""maindiv""></div>"    );
        }