Exemple #1
0
 public WebSocketServer(LocalServer server)
 {
     _localServer = server;
     Connections = new List<WebSocketConnection>();
     _tmrBroadcast = new Timer(1000);
     _tmrBroadcast.Elapsed += TmrBroadcastElapsed;
     _tmrBroadcast.Start();
 }
Exemple #2
0
        private void MainInit()
        {
            UISync.Init(this);

            try
            {
                File.WriteAllText(Program.AppDataPath + "exit.txt", "RUNNING");
            }
            catch (Exception ex)
            {
                LogExceptionToFile(ex);
            }

            InitLogging();

            if (!SilentStartup)
            {
                switch (Conf.StartupMode)
                {
                    case 0:
                        break;
                    case 2:
                        break;
                    case 3:
                        WinApi.SetWinFullScreen(Handle);
                        break;
                }
            }

            mediaPanelControl1.MainClass = this;
            EncoderParams = new EncoderParameters(1)
                            {
                                Param =
                                {
                                    [0] =
                                        new EncoderParameter(
                                        System.Drawing.Imaging.Encoder.Quality,
                                        Conf.JPEGQuality)
                                }
                            };

            //this initializes the port mapping collection
            IStaticPortMappingCollection map = NATControl.Mappings;
            if (string.IsNullOrEmpty(Conf.MediaDirectory) || Conf.MediaDirectory == "NotSet")
            {
                Conf.MediaDirectory = Program.AppDataPath + @"WebServerRoot\Media\";
            }

            if (Conf.MediaDirectories == null || Conf.MediaDirectories.Length == 0)
            {
                Conf.MediaDirectories = new[]
                                        {
                                            new configurationDirectory
                                            {
                                                Entry = Conf.MediaDirectory,
                                                DeleteFilesOlderThanDays =
                                                    Conf.DeleteFilesOlderThanDays,
                                                Enable_Storage_Management =
                                                    Conf.Enable_Storage_Management,
                                                MaxMediaFolderSizeMB = Conf.MaxMediaFolderSizeMB,
                                                StopSavingOnStorageLimit =
                                                    Conf.StopSavingOnStorageLimit,
                                                ID = 0
                                            }
                                        };
            }
            else
            {
                if (Conf.MediaDirectories.First().Entry == "NotSet")
                {
                    Conf.MediaDirectories = new[]
                                            {
                                                new configurationDirectory
                                                {
                                                    Entry = Conf.MediaDirectory,
                                                    DeleteFilesOlderThanDays =
                                                        Conf.DeleteFilesOlderThanDays,
                                                    Enable_Storage_Management =
                                                        Conf.Enable_Storage_Management,
                                                    MaxMediaFolderSizeMB =
                                                        Conf.MaxMediaFolderSizeMB,
                                                    StopSavingOnStorageLimit =
                                                        Conf.StopSavingOnStorageLimit,
                                                    ID = 0
                                                }
                                            };
                }
            }

            //reset stop saving flag
            foreach (configurationDirectory d in Conf.MediaDirectories)
            {
                d.StopSavingFlag = false;
            }

            if (!Directory.Exists(Conf.MediaDirectories[0].Entry))
            {
                string notfound = Conf.MediaDirectories[0].Entry;
                LogErrorToFile("Media directory could not be found (" + notfound + ") - reset it to " +
                               Program.AppDataPath + @"WebServerRoot\Media\" + " in settings if it doesn't attach.");
            }

            if (!VlcHelper.VlcInstalled)
            {
                LogWarningToFile(
                    "VLC not installed - install VLC (" + Program.Platform + ") for additional connectivity.");
                if (Program.Platform == "x64")
                {
                    LogWarningToFile(
                        "VLC64  must be unzipped so the dll files and folders including libvlc.dll and the plugins folder are in " +
                        Program.AppPath + "VLC64\\");
                    LogWarningToFile("Download: <a href=\""+VLCx64+"\">"+VLCx64+"</a>");
                }
                else
                    LogWarningToFile("Download: <a href=\"" + VLCx86 + "\">" + VLCx86 + "</a>");
            }
            else
            {
                Version v = VlcHelper.VlcVersion;
                if (v.CompareTo(VlcHelper.VMin) < 0)
                {
                    LogWarningToFile(
                        "Old VLC installed - update VLC (" + Program.Platform + ") for additional connectivity.");
                }
                else
                {
                    if (v.CompareTo(new Version(2, 0, 2)) == 0)
                    {
                        LogWarningToFile(
                            "VLC v2.0.2 detected - there are known issues with this version of VLC (HTTP streaming is broken for a lot of cameras) - if you are having problems with VLC connectivity we recommend you install v2.0.1 ( http://download.videolan.org/pub/videolan/vlc/2.0.1/ ) or the latest (if available).");
                    }
                }
            }

            _fsw = new FileSystemWatcher
                   {
                       Path = Program.AppDataPath,
                       IncludeSubdirectories = false,
                       Filter = "external_command.txt",
                       NotifyFilter = NotifyFilters.LastWrite
                   };
            _fsw.Changed += FswChanged;
            _fsw.EnableRaisingEvents = true;

            tsslPRO.Visible = !Conf.Subscribed;

            Menu = mainMenu;
            notifyIcon1.ContextMenuStrip = ctxtTaskbar;
            Identifier = Guid.NewGuid().ToString();
            MWS = new LocalServer(this)
                  {
                      ServerRoot = Program.AppDataPath + @"WebServerRoot\",
                  };

            if (Conf.Monitor)
            {
                Process[] w = Process.GetProcessesByName("ispymonitor");
                if (w.Length == 0)
                {
                    try
                    {
                        var si = new ProcessStartInfo(Program.AppPath + "/ispymonitor.exe", "ispy");
                        Process.Start(si);
                    }
                    catch
                    {
                        // ignored
                    }
                }
            }

            //GC.KeepAlive(MWS);

            SetBackground();

            toolStripMenu.Visible = Conf.ShowToolbar;
            statusStrip1.Visible = Conf.ShowStatus && Helper.HasFeature(Enums.Features.View_Status_Bar);
            Menu = !Conf.ShowFileMenu ? null : mainMenu;

            if (SilentStartup)
            {
                WindowState = FormWindowState.Minimized;
            }

            if (Conf.Password_Protect_Startup)
            {
                _locked = true;
                WindowState = FormWindowState.Minimized;
            }

            if (Conf.Fullscreen && !SilentStartup && !_locked)
            {
                WindowState = FormWindowState.Maximized;
                FormBorderStyle = FormBorderStyle.None;
                WinApi.SetWinFullScreen(Handle);
            }

            statusBarToolStripMenuItem.Checked = menuItem4.Checked = Conf.ShowStatus;
            toolStripToolStripMenuItem.Checked = menuItem6.Checked = Conf.ShowToolbar;
            fileMenuToolStripMenuItem.Checked = menuItem5.Checked = Conf.ShowFileMenu;
            fullScreenToolStripMenuItem1.Checked = menuItem3.Checked = Conf.Fullscreen;
            alwaysOnTopToolStripMenuItem1.Checked = menuItem8.Checked = Conf.AlwaysOnTop;
            mediaPaneToolStripMenuItem.Checked = menuItem7.Checked = Conf.ShowMediaPanel;
            menuItem22.Checked = Conf.LockLayout;
            TopMost = Conf.AlwaysOnTop;

            Iconfont = new Font(FontFamily.GenericSansSerif, Conf.BigButtons ? 22 : 15, FontStyle.Bold,
                GraphicsUnit.Pixel);
            double dOpacity;
            Double.TryParse(Conf.Opacity.ToString(CultureInfo.InvariantCulture), NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out dOpacity);
            Opacity = dOpacity/100.0;

            if (Conf.ServerName == "NotSet")
            {
                Conf.ServerName = SystemInformation.ComputerName;
            }

            notifyIcon1.Text = Conf.TrayIconText;
            notifyIcon1.BalloonTipClicked += NotifyIcon1BalloonTipClicked;
            autoLayoutToolStripMenuItem.Checked = menuItem26.Checked = Conf.AutoLayout;

            _updateTimer = new Timer(200);
            _updateTimer.Elapsed += UpdateTimerElapsed;
            _updateTimer.AutoReset = true;
            _updateTimer.SynchronizingObject = this;
            //GC.KeepAlive(_updateTimer);

            _houseKeepingTimer = new Timer(1000);
            _houseKeepingTimer.Elapsed += HouseKeepingTimerElapsed;
            _houseKeepingTimer.AutoReset = true;
            _houseKeepingTimer.SynchronizingObject = this;
            //GC.KeepAlive(_houseKeepingTimer);

            //load plugins
            LoadPlugins();

            resetLayoutToolStripMenuItem1.Enabled = mnuResetLayout.Enabled = false; //reset layout

            NetworkChange.NetworkAddressChanged += NetworkChangeNetworkAddressChanged;
            mediaPaneToolStripMenuItem.Checked = Conf.ShowMediaPanel;
            ShowHideMediaPane();
            if (!string.IsNullOrEmpty(Conf.MediaPanelSize))
            {
                string[] dd = Conf.MediaPanelSize.Split('x');
                int d1 = Convert.ToInt32(dd[0]);
                int d2 = Convert.ToInt32(dd[1]);
                try
                {
                    splitContainer1.SplitterDistance = d1;
                    splitContainer2.SplitterDistance = d2;
                }
                catch
                {
                    // ignored
                }
            }
            //load in object list

            if (_startCommand.Trim().StartsWith("open"))
            {
                ParseCommand(_startCommand);
                _startCommand = "";
            }
            else
            {
                if (!File.Exists(Program.AppDataPath + @"XML\objects.xml"))
                {
                    File.Copy(Program.AppPath + @"XML\objects.xml", Program.AppDataPath + @"XML\objects.xml");
                }
                ParseCommand("open " + Program.AppDataPath + @"XML\objects.xml");
            }
            if (_startCommand != "")
            {
                ParseCommand(_startCommand);
            }

            StopAndStartServer();

            if (_mWindowState == null)
            {
                _mWindowState = new PersistWindowState {Parent = this, RegistryPath = @"Software\ispy\startup"};
            }

            if (Conf.Enabled_ShowGettingStarted)
                ShowGettingStarted();

            if (File.Exists(Program.AppDataPath + "custom.txt"))
            {
                string[] cfg =
                    File.ReadAllText(Program.AppDataPath + "custom.txt").Split(Environment.NewLine.ToCharArray());
                bool setSecure = false;
                foreach (string s in cfg)
                {
                    if (!string.IsNullOrEmpty(s))
                    {
                        string[] nv = s.Split('=');

                        if (nv.Length > 1)
                        {
                            switch (nv[0].ToLower().Trim())
                            {
                                case "business":
                                    Conf.Vendor = nv[1].Trim();
                                    break;
                                case "link":
                                    PurchaseLink = nv[1].Trim();
                                    break;
                                case "manufacturer":
                                    IPTYPE = Conf.DefaultManufacturer = nv[1].Trim();
                                    break;
                                case "model":
                                    IPMODEL = nv[1].Trim();
                                    break;
                                case "affiliateid":
                                case "affiliate id":
                                case "aid":
                                    int aid;
                                    if (Int32.TryParse(nv[1].Trim(), out aid))
                                    {
                                        Affiliateid = aid;
                                    }
                                    break;
                                case "tags":
                                    if (string.IsNullOrEmpty(Conf.Tags))
                                        Conf.Tags = nv[1].Trim();
                                    break;
                                case "featureset":
                                    //only want to set this on install (allow them to modify)
                                    if (Conf.FirstRun)
                                    {
                                        int featureset;
                                        if (Int32.TryParse(nv[1].Trim(), out featureset))
                                        {
                                            Conf.FeatureSet = featureset;
                                        }
                                    }
                                    break;
                                case "permissions":
                                    //only want to set this on install (allow them to modify)
                                    if (Conf.FirstRun)
                                    {
                                        var groups = nv[1].Trim().Split('|');
                                        var l = new List<configurationGroup>();
                                        foreach (var g in groups)
                                        {
                                            if (!string.IsNullOrEmpty(g))
                                            {
                                                var g2 = g.Split(',');
                                                if (g2.Length >= 3)
                                                {
                                                    if (!string.IsNullOrEmpty(g2[0]))
                                                    {
                                                        int perm;
                                                        if (int.TryParse(g2[2], out perm))
                                                        {
                                                            l.Add(new configurationGroup
                                                                  {
                                                                      featureset = perm,
                                                                      name = g2[0],
                                                                      password =
                                                                          EncDec.EncryptData(g2[1],
                                                                              Conf.EncryptCode)
                                                                  });
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                        if (l.FirstOrDefault(p => p.name.ToLower() == "admin") == null)
                                        {
                                            l.Add(new configurationGroup{
                                                      featureset = 1,
                                                      name = "Admin",
                                                      password = ""
                                                  });
                                        }
                                        if (l.Count>0)
                                            Conf.Permissions = l.ToArray();

                                    }
                                    break;
                                case "webserver":
                                    Webserver = nv[1].Trim().Trim('/');
                                    if (!setSecure)
                                        WebserverSecure = Webserver;
                                    break;
                                case "webserversecure":
                                    WebserverSecure = nv[1].Trim().Trim('/');
                                    setSecure = true;
                                    break;
                                case "recordondetect":
                                    bool defaultRecordOnDetect;
                                    if (bool.TryParse(nv[1].Trim(), out defaultRecordOnDetect))
                                        Conf.DefaultRecordOnDetect = defaultRecordOnDetect;
                                    break;
                                case "recordonalert":
                                    bool defaultRecordOnAlert;
                                    if (bool.TryParse(nv[1].Trim(), out defaultRecordOnAlert))
                                        Conf.DefaultRecordOnAlert = defaultRecordOnAlert;
                                    break;
                            }
                        }
                    }
                }
                Conf.FirstRun = false;
                LogMessageToFile("Webserver: " + Webserver);

                string logo = Program.AppDataPath + "logo.jpg";
                if (!File.Exists(logo))
                    logo = Program.AppDataPath + "logo.png";

                if (File.Exists(logo))
                {
                    try
                    {
                        Image bmp = Image.FromFile(logo);
                        var pb = new PictureBox {Image = bmp};
                        pb.Width = pb.Image.Width;
                        pb.Height = pb.Image.Height;

                        pb.Left = _pnlCameras.Width/2 - pb.Width/2;
                        pb.Top = _pnlCameras.Height/2 - pb.Height/2;

                        _pnlCameras.Controls.Add(pb);
                        _pnlCameras.BrandedImage = pb;
                    }
                    catch (Exception ex)
                    {
                        LogExceptionToFile(ex);
                    }
                }
            }

            LoadCommands();
            if (!SilentStartup && Conf.ViewController)
            {
                ShowViewController();
                viewControllerToolStripMenuItem.Checked = menuItem14.Checked = true;
            }

            pTZControllerToolStripMenuItem.Checked =
                menuItem18.Checked = pTZControllerToolStripMenuItem1.Checked = Conf.ShowPTZController;

            if (Conf.ShowPTZController && !SilentStartup)
                ShowHidePTZTool();

            ListGridViews();

            Conf.RunTimes++;

            try
            {
                _cputotalCounter = new PerformanceCounter("Processor", "% Processor Time", "_total", true);
                _cpuCounter = new PerformanceCounter("Process", "% Processor Time",
                    Process.GetCurrentProcess().ProcessName, true);
                try
                {
                    _pcMem = new PerformanceCounter("Process", "Working Set - Private",
                        Process.GetCurrentProcess().ProcessName, true);
                }
                catch
                {
                    try
                    {
                        _pcMem = new PerformanceCounter("Memory", "Available MBytes");
                    }
                    catch (Exception ex2)
                    {
                        LogExceptionToFile(ex2);
                        _pcMem = null;
                    }
                }
            }
            catch (Exception ex)
            {
                LogExceptionToFile(ex);
                _cputotalCounter = null;
            }

            if (Conf.StartupForm != "iSpy")
            {
                ShowGridView(Conf.StartupForm);

            }

            foreach (var cg in Conf.GridViews)
            {
                if (cg.ShowAtStartup)
                {
                    ShowGridView(cg.name);
                }
            }

            var t = new Thread(()=>ConnectServices()) {IsBackground = true};
            t.Start();

            _updateTimer.Start();
            _houseKeepingTimer.Start();
        }