示例#1
0
        public static void GenerateWebInterfaceLinkDocument(string outPath)
        {
            StringBuilder sb = new StringBuilder();

            sb.AppendLine("<!DOCTYPE html>");
            sb.AppendLine("<html>");
            sb.AppendLine("	<head>");
            sb.AppendLine("		<title>Camera Configuration Links</title>");
            sb.AppendLine(@"		<style type=""text/css"">
body
{
	font-family: Arial;
}
table
{
	border-collapse: collapse;
}
td, th
{
	border-bottom: 1px solid #b5b5b5;
	padding: 2px 12px;
}
img
{
	max-width: 120px;
	max-height: 120px;
	cursor: pointer;
}
		</style>"        );
            sb.AppendLine("	</head>");
            sb.AppendLine("<body>");
            sb.AppendLine("<table><thead><tr><th>Camera Name</th><th>Short Name</th><th>Configuration URL</th><th>Snapshot</th></tr></thead><tbody>");
            RegistryKey cameras = RegistryUtil.HKLM.OpenSubKey("SOFTWARE\\Perspective Software\\Blue Iris\\Cameras");

            if (cameras == null)
            {
                MessageBox.Show("Could not find Blue Iris's camera list in the registry.  Either you have no cameras configured or your Blue Iris version is not compatible.");
                return;
            }
            else
            {
                string[] cameraNames = cameras.GetSubKeyNames();
                if (cameraNames.Length == 0)
                {
                    MessageBox.Show("No cameras were found in Blue Iris's registry settings.  Either you have no cameras configured or your Blue Iris version is not compatible.");
                    return;
                }
                else
                {
                    BiServerInfo.Reload();
                    if (!BiServerInfo.enabled)
                    {
                        MessageBox.Show("This function is not supported on your system.  Possible reasons are that your Blue Iris version is incompatible, or your Blue Iris web server is not enabled.");
                        return;
                    }
                    //BiUserInfo.Reload();
                    AdvWebClient wc      = new AdvWebClient();
                    string       session = null;
                    try
                    {
                        wc.Proxy = null;
                        try
                        {
                            UserInfo user = BiUserInfo.CreateTemporaryUser();
                            session = GetSecureAuthenticatedSession(wc, out bool isAdmin, user.name, user.GetDecodedPassword());
                            wc.CookieContainer.Add(new Cookie("session", session, "/", BiServerInfo.GetWebserverIp()));
                        }
                        catch (Exception ex)
                        {
                            Logger.Debug(ex);
                            wc = null;
                        }

                        List <CameraInfo> camList = new List <CameraInfo>(cameraNames.Length);
                        foreach (string cameraName in cameraNames)
                        {
                            RegistryKey cam       = cameras.OpenSubKey(cameraName);
                            string      shortName = cam.GetValue("shortname").ToString();
                            string      ip        = cam.GetValue("ip").ToString();
                            if (string.IsNullOrWhiteSpace(ip))
                            {
                                continue;
                            }
                            string     port  = cam.GetValue("ip_port").ToString();
                            bool       https = cam.GetValue("https").ToString() != "0";
                            int        index = int.Parse(cam.GetValue("pos").ToString());
                            CameraInfo ci    = new CameraInfo(cameraName, shortName, ip, port, https, index);
                            camList.Add(ci);
                        }
                        camList.Sort(new Comparison <CameraInfo>((c1, c2) => c1.index.CompareTo(c2.index)));
                        foreach (CameraInfo ci in camList)
                        {
                            AddCameraLink(sb, ci, wc);
                        }
                    }
                    finally
                    {
                        wc?.UploadString(CameraWebInterfaceLinker.GetJsonURL(), "{\"cmd\":\"logout\",\"session\":\"" + session + "\"}");
                        wc?.Dispose();
                    }
                }
            }
            sb.AppendLine("</tbody></table></body>");
            sb.AppendLine("</html>");
            File.WriteAllText(outPath, sb.ToString());
            Process.Start(outPath);
        }
示例#2
0
        private void UpdateWatch()
        {
            try
            {
                try
                {
                    Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.AboveNormal;
                }
                catch (ThreadAbortException) { throw; }
                catch { }
                Try.Swallow(() => { BiUserInfo.CreateTemporaryUser(); });
                cpuCounterTotal       = new PerformanceCounter("Processor", "% Processor Time", "_Total");
                interruptCounterTotal = new PerformanceCounter("Processor", "% Interrupt Time", "_Total");
                DateTime lastDailyRegistryBackup = DateTime.MinValue;
                while (true)
                {
                    Thread.Sleep(1500);
                    Verbose("Starting Iteration");
                    try
                    {
                        PerformanceDataCollector.HandlePossiblePerfDataReport();
                        DateTime now = DateTime.Now;
                        if (lastDailyRegistryBackup.Year != now.Year || lastDailyRegistryBackup.Month != now.Month || lastDailyRegistryBackup.Day != now.Day)
                        {
                            lastDailyRegistryBackup = now;
                            if (Program.settings.dailyRegistryBackups)
                            {
                                RegistryBackup.BackupNow(BiUpdateHelperSettings.GetDailyRegistryBackupLocation() + Path.DirectorySeparatorChar + "BI_REG_" + DateTime.Now.ToString("yyyy-MM-dd") + ".reg");
                            }
                        }
                        // Build a list of unique directories that have an active blueiris.exe.
                        // There is not likely to be more than one directory, though a single directory
                        // can easily have two blueiris.exe (service and GUI).
                        List <BiUpdateMapping> biUpdateMap = GetUpdateInfo();

                        if (biUpdateMap.Count == 0)
                        {
                            Verbose("No Blue Iris processes detected");
                        }
                        else
                        {
                            foreach (BiUpdateMapping mapping in biUpdateMap)
                            {
                                if (mapping.updateProcs.Length > 0)
                                {
                                    // Blue Iris is currently being updated.  Kill the blueiris.exe processes if configured to do so.
                                    Logger.Info("Blue Iris update detected in path: " + mapping.dirPath);
                                    if (Program.settings.includeRegistryWithUpdateBackup)
                                    {
                                        BiVersionInfo versionInfo = GetBiVersionInfo(mapping);
                                        TryBackupRegistryForBiVersion(versionInfo);
                                    }
                                    if (Program.settings.killBlueIrisProcessesDuringUpdate2)
                                    {
                                        Logger.Info("Killing " + mapping.GetNumProcsLabel());
                                        mapping.KillBiProcs();
                                    }
                                    Verbose("Waiting for update to complete");
                                    mapping.WaitUntilUpdateProcsStop(TimeSpan.FromMinutes(5));
                                }
                                else
                                {
                                    // Blue Iris is not being updated in this directory.

                                    if (Program.settings.killBlueIrisProcessesDuringUpdate2 && (blueIrisServiceStopping || systemInFrozenState))
                                    {
                                        mapping.KillBiProcs();

                                        if (blueIrisServiceStopping)
                                        {
                                            Logger.Info("Blue Iris service found in stopping state. Killed " + mapping.GetNumProcsLabel());
                                        }
                                        else if (systemInFrozenState)
                                        {
                                            Logger.Info("System freeze with high interrupt % detected. Killed " + mapping.GetNumProcsLabel());
                                        }
                                        continue;
                                    }

                                    // Back up the update file if configured to do so.
                                    if (!Program.settings.backupUpdateFiles)
                                    {
                                        continue;
                                    }

                                    //Check for the existence of an update.exe file
                                    FileInfo fiUpdate = new FileInfo(GetUpdateDir5_1() + "update.exe");
                                    if (!fiUpdate.Exists)
                                    {
                                        Verbose("No update file to back up in path: " + fiUpdate.DirectoryName);
                                        fiUpdate = new FileInfo(mapping.dirPath + "update.exe");
                                    }
                                    if (!fiUpdate.Exists)
                                    {
                                        Verbose("No update file to back up in path: " + fiUpdate.DirectoryName);
                                        continue;
                                    }

                                    Verbose("Backing up update file: " + fiUpdate.FullName);

                                    // Get Blue Iris process(es) (necessary to learn if it is 64 or 32 bit)
                                    BiVersionInfo versionInfo = GetBiVersionInfo(mapping);
                                    if (versionInfo == null)
                                    {
                                        continue;                                         // BI is probably not running
                                    }
                                    FileInfo targetUpdateFile = new FileInfo(mapping.dirPath + "update" + versionInfo.cpu_32_64 + "_" + versionInfo.version + ".exe");
                                    if (targetUpdateFile.Exists)
                                    {
                                        // A backed-up update file for the active Blue Iris version already exists, so we should do nothing now
                                        Verbose("Target update file \"" + targetUpdateFile.FullName + "\" already exists.  Probably, the new update file hasn't been installed yet.");
                                        TryBackupRegistryForBiVersion(versionInfo);
                                    }
                                    else
                                    {
                                        // Find out if the file can be opened exclusively (meaning it is finished downloading, etc)
                                        bool fileIsUnlocked = false;
                                        try
                                        {
                                            using (FileStream fs = new FileStream(fiUpdate.FullName, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
                                            {
                                                fileIsUnlocked = true;
                                            }
                                        }
                                        catch (ThreadAbortException) { throw; }
                                        catch (Exception) { }

                                        if (fileIsUnlocked)
                                        {
                                            // This is a pretty good sign that the update is not curently being installed, so we should be safe to rename the update file.
                                            Logger.Info("Renaming update file to: " + targetUpdateFile.FullName);
                                            fiUpdate.MoveTo(targetUpdateFile.FullName);
                                        }
                                        else
                                        {
                                            Verbose("Update file could not be exclusively locked. Backup will not occur this iteration.");
                                        }
                                    }
                                }
                            }
                        }
                    }
                    catch (ThreadAbortException) { throw; }
                    catch (Exception ex)
                    {
                        Logger.Debug(ex);
                    }
                }
            }
            catch (ThreadAbortException) { }
            catch (Exception ex)
            {
                Logger.Debug(ex);
            }
        }
示例#3
0
        /// <summary>
        /// Creates an anonymous usage record.  This method spends 10 seconds measuring CPU usage.  Returns null if any BlueIris.exe processes close while CPU usage is being measured, or if no BlueIris.exe processes were open.
        /// </summary>
        /// <returns></returns>
        public static Upload_Record GetPerfDataRecord()
        {
            Upload_Record record = new Upload_Record();

            BlueIrisConfiguration c = new BlueIrisConfiguration();

            c.Load();

            record.CpuUsage                = c.activeStats.CpuUsage;
            record.BiCpuUsage              = c.activeStats.BiCpuUsage;
            record.CpuThreads              = (short)Environment.ProcessorCount;
            record.BiVersion               = c.activeStats.BiVersion;
            record.BiMemUsageMB            = c.activeStats.BiMemUsageMB;
            record.BiPeakVirtualMemUsageMB = c.activeStats.BiPeakVirtualMemUsageMB;
            record.ConsoleOpen             = c.activeStats.ConsoleOpen;
            record.ConsoleWidth            = c.activeStats.ConsoleWidth;
            record.ConsoleHeight           = c.activeStats.ConsoleHeight;
            record.Secret = Program.settings.secret;
            record.OS     = c.OS;

            if (c.cpu == null)
            {
                record.CpuModel = "Unknown";
                record.CpuMHz   = 0;
            }
            else
            {
                record.CpuModel = c.cpu.GetModel();
                record.CpuMHz   = NumberUtil.ParseInt(c.cpu.maxClockSpeed);
            }

            record.HelperVersion  = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
            record.HwAccel        = (byte)c.global.HardwareAcceleration;
            record.ServiceMode    = c.global.ServiceMode;
            record.LivePreviewFPS = (short)c.global.LivePreviewFPS;

            record.MemMB     = c.activeStats.MemMB;
            record.MemFreeMB = c.activeStats.MemFreeMB;

            record.RamGiB        = c.mem.GiB;
            record.RamChannels   = c.mem.Channels;
            record.DimmLocations = c.mem.DimmLocations;
            record.RamMHz        = c.mem.MHz;

            // Get camera info.
            // Get frame rates, current profile (only accessible via BI's web server).
            Dictionary <string, double> fpsMap = new Dictionary <string, double>();

            int  currentProfile = 1;
            bool isAdmin        = false;
            bool gotCamlist     = false;
            bool gotStatus      = false;

            BiServerInfo.Reload();
            //BiUserInfo.Reload();
            if (BiServerInfo.enabled)
            {
                try
                {
                    using (WebClient wc = new WebClient())
                    {
                        UserInfo user    = BiUserInfo.CreateTemporaryUser();
                        string   session = CameraWebInterfaceLinker.GetSecureAuthenticatedSession(wc, out isAdmin, user.name, user.GetDecodedPassword());
                        try
                        {
                            try
                            {
                                string          response        = wc.UploadString(CameraWebInterfaceLinker.GetJsonURL(), "{\"cmd\":\"camlist\",\"session\":\"" + session + "\"}");
                                CamListResponse camListResponse = JsonConvert.DeserializeObject <CamListResponse>(response);
                                if (camListResponse != null && camListResponse.result == "success")
                                {
                                    foreach (CameraListCamera camera in camListResponse.data)
                                    {
                                        if (camera.group == null)
                                        {
                                            fpsMap[camera.optionValue] = camera.FPS;
                                        }
                                    }
                                    gotCamlist = true;
                                }
                            }
                            catch (Exception ex)
                            {
                                Logger.Debug(ex, "Error reading camera list from web server.");
                            }

                            try
                            {
                                string         response       = wc.UploadString(CameraWebInterfaceLinker.GetJsonURL(), "{\"cmd\":\"status\",\"session\":\"" + session + "\"}");
                                StatusResponse statusResponse = JsonConvert.DeserializeObject <StatusResponse>(response);
                                if (statusResponse != null && statusResponse.result == "success")
                                {
                                    currentProfile = statusResponse.data.profile;
                                    gotStatus      = true;
                                    if (currentProfile < 1 || currentProfile > 7)
                                    {
                                        currentProfile = 1;
                                        gotStatus      = false;
                                    }
                                    else
                                    {
                                        record.ProfileConfirmed = true;
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                Logger.Debug(ex, "Error reading camera list from web server.");
                            }
                        }
                        finally
                        {
                            wc.UploadString(CameraWebInterfaceLinker.GetJsonURL(), "{\"cmd\":\"logout\",\"session\":\"" + session + "\"}");
                        }
                    }
                }
                catch (Exception ex)
                {
                    Logger.Debug(ex, "Error dealing with web server.");
                }
            }
            record.webserverState = 0;
            if (gotCamlist && gotStatus)
            {
                record.webserverState = 1;
                if (isAdmin)                 // and any future admin-requiring stuff all worked
                {
                    record.webserverState = 2;
                }
            }


            // Get camera info
            List <Upload_Camera> cameras = new List <Upload_Camera>();

            foreach (Camera camSrc in c.cameras.Values)
            {
                if (!camSrc.enabled)
                {
                    continue;
                }

                Upload_Camera cam = new Upload_Camera();

                if (fpsMap.TryGetValue(camSrc.shortname, out double fps))
                {
                    cam.FPS          = (byte)Math.Round(fps).Clamp(0, 255);
                    cam.FPSConfirmed = true;
                }
                else
                {
                    cam.FPS = (byte)(Math.Round(camSrc.MaxRate).Clamp(0, 255));
                }
                cam.CapType     = (byte)camSrc.CapType;
                cam.Hwaccel     = (byte)camSrc.Hwva;
                cam.LimitDecode = camSrc.LimitDecode;
                cam.Pixels      = camSrc.Pixels;
                if (camSrc.hasSubStream)
                {
                    cam.MainPixels = camSrc.MainPixels;
                }
                cam.Type              = (byte)camSrc.Type;
                cam.MotionDetector    = camSrc.triggerSettings[currentProfile].motionDetectionEnabled;
                cam.RecordTriggerType = (byte)camSrc.recordSettings[currentProfile].triggerType;
                cam.RecordFormat      = (byte)camSrc.recordSettings[currentProfile].recordingFormat;
                cam.DirectToDisk      = camSrc.recordSettings[currentProfile].DirectToDisc;
                cam.VCodec            = camSrc.recordSettings[currentProfile].VCodec;
                cameras.Add(cam);
            }

            record.AllFPSConfirmed = cameras.All(cam => cam.FPSConfirmed);             // Ignored and recalculated by server. This exists here for the sake of local json output.
            record.cameras         = cameras.ToArray();
            record.gpus            = c.gpus.Select(g => new Upload_Gpu()
            {
                Name = g.Name, Version = g.DriverVersion
            }).ToArray();

            record.Total_FPS = record.Total_Megapixels = record.Total_MPPS = 0;
            foreach (Upload_Camera cam in cameras)
            {
                float MP = cam.Pixels / 1000000f;
                record.Total_Megapixels += MP;
                record.Total_FPS        += cam.FPS;
                record.Total_MPPS       += MP * cam.FPS;
            }

            return(record);
        }