Exemplo n.º 1
0
        public static void SetString(Control ctrl, string identifier)
        {
            if (!_inited)
            {
                Init();
            }

            try
            {
                ctrl.Text = Res[identifier];
            }
            catch (KeyNotFoundException)
            {
                ctrl.Text = identifier;
                MainForm.LogErrorToFile("No Translation for token " + identifier);
                if (CultureCode != "en")
                {
                    var eng   = TranslationSets.FirstOrDefault(p => p.CultureCode == "en");
                    var token = eng?.Translation.FirstOrDefault(p => p.Token == identifier);
                    if (token != null)
                    {
                        Res.Add(identifier, token.Value);
                        ctrl.Text = Res[identifier];
                    }
                }
            }
            catch
            {
                //possible threading error where language is reset
            }
        }
Exemplo n.º 2
0
        public void FTP(object taskObject)
        {
            var task = (FTPTask)taskObject;
            int i    = 0;

            while (task.FileName.IndexOf("{") != -1 && i < 20)
            {
                task.FileName = String.Format(System.Globalization.CultureInfo.InvariantCulture, task.FileName, DateTime.Now);
                i++;
            }
            string error;

            FTP(task.Server, task.UsePassive, task.Username, task.Password, task.FileName, task.Contents, out error);

            if (error != "")
            {
                MainForm.LogErrorToFile(error);
            }

            objectsCamera oc = MainForm.Cameras.SingleOrDefault(p => p.id == task.CameraId);

            if (oc != null)
            {
                oc.ftp.ready = true;
            }
        }
Exemplo n.º 3
0
        public void FTP(object taskObject)
        {
            var task = (FTPTask)taskObject;
            int i    = 0;

            while (task.FileName.IndexOf("{", StringComparison.Ordinal) != -1 && i < 20)
            {
                task.FileName = String.Format(CultureInfo.InvariantCulture, task.FileName, Helper.Now);
                i++;
            }
            string error;

            FTP(task.Server, task.Port, task.UsePassive, task.Username, task.Password, task.FileName, task.Counter, task.Contents, out error, task.Rename, task.UseSftp);

            if (error != "")
            {
                MainForm.LogErrorToFile(error, "FTP");
            }

            objectsCamera oc = MainForm.Cameras.SingleOrDefault(p => p.id == task.CameraId);

            if (oc != null)
            {
                oc.ftp.ready = true;
            }
        }
Exemplo n.º 4
0
 public static string GetString(string identifier)
 {
     if (!_inited)
     {
         Init();
     }
     try
     {
         return(Res[identifier]);
     }
     catch (KeyNotFoundException)
     {
         MainForm.LogErrorToFile("No Translation for token " + identifier);
         if (CultureCode != "en")
         {
             var eng   = TranslationSets.FirstOrDefault(p => p.CultureCode == "en");
             var token = eng?.Translation.FirstOrDefault(p => p.Token == identifier);
             if (token == null)
             {
                 return(identifier);
             }
             Res.Add(identifier, token.Value);
             return(Res[identifier]);
         }
     }
     catch
     {
         //possible threading error where language is reset
     }
     return(identifier);
 }
Exemplo n.º 5
0
        public static string Connect(bool tryLoopback)
        {
            if (!MainForm.Conf.ServicesEnabled)
            {
                return(WebservicesDisabledMessage);
            }
            string r = "";

            if (WebsiteLive)
            {
                int port = MainForm.Conf.ServerPort;
                if (MainForm.Conf.IPMode == "IPv6")
                {
                    port = MainForm.Conf.LANPort;
                }

                try
                {
                    bool   success;
                    string ip = MainForm.IPAddressExternal(out success);
                    if (success)
                    {
                        r = Wsa.Connect2(MainForm.Conf.WSUsername, MainForm.Conf.WSPassword, port,
                                         MainForm.Identifier, tryLoopback, Application.ProductVersion,
                                         MainForm.Conf.ServerName, MainForm.Conf.IPMode == "IPv4", ip, MainForm.Affiliateid,
                                         X509.SslEnabled);
                        if (r == "OK" && tryLoopback)
                        {
                            MainForm.LoopBack = true;
                        }
                    }
                    //MainForm.LogMessageToFile("Webservices: " + r);
                }
                catch (Exception ex)
                {
                    MainForm.LogExceptionToFile(ex);
                    WebsiteLive = false;
                }

                if (WebsiteLive)
                {
                    LoginFailed = (r == "Webservices_LoginFailed");
                    if (r != "OK")
                    {
                        MainForm.LogErrorToFile("Webservices: " + r);
                        return(LocRm.GetString(r));
                    }
                    return(r);
                }
            }
            return(LocRm.GetString("iSpyDown"));
        }
Exemplo n.º 6
0
        private static void Init()
        {
            string lang = MainForm.Conf.Language;

            if (lang == "NotSet")
            {
                lang = CultureInfo.CurrentCulture.Name.ToLower();
                string lang1 = lang;
                if (TranslationSets.FirstOrDefault(p => p.CultureCode == lang1) != null)
                {
                    MainForm.Conf.Language = lang;
                }
                else
                {
                    lang = lang.Split('-')[0];
                    string lang2 = lang;
                    if (TranslationSets.FirstOrDefault(p => p.CultureCode == lang2) != null)
                    {
                        MainForm.Conf.Language = lang;
                    }
                    else
                    {
                        MainForm.Conf.Language = lang = "en";
                    }
                }
            }

            Res.Clear();
            _currentSet = TranslationSets.FirstOrDefault(p => p.CultureCode == lang);
            if (_currentSet != null)
            {
                foreach (TranslationsTranslationSetTranslation tran in _currentSet.Translation)
                {
                    try
                    {
                        Res.Add(tran.Token,
                                tran.Value.Replace("&amp;", "&")
                                .Replace("&lt;", "<")
                                .Replace("&gt;", ">")
                                .Replace(",", ",")
                                .Replace("#39;", "'"));
                    }
                    catch (Exception ex)
                    {
                        MainForm.LogErrorToFile("Translation: " + tran.Token + ": " + ex.Message);
                    }
                }
            }

            _inited = true;
        }
Exemplo n.º 7
0
 static void WsaSendTweetCompleted(object sender, SendTweetCompletedEventArgs e)
 {
     if (e.Error != null)
     {
         MainForm.LogExceptionToFile(e.Error);
     }
     else
     {
         if (e.Result != "OK")
         {
             MainForm.LogErrorToFile("Send Tweet: " + e.Result);
         }
     }
 }
Exemplo n.º 8
0
 static void WsaSyncCompleted(object sender, SyncCompletedEventArgs e)
 {
     if (e.Error != null)
     {
         WebsiteLive        = false;
         MainForm.NeedsSync = true;
         MainForm.LogExceptionToFile(e.Error);
     }
     else
     {
         if (e.Result != "OK")
         {
             MainForm.LogErrorToFile("Sync: " + e.Result);
         }
     }
 }
Exemplo n.º 9
0
        public static string[] TestConnection(string username, string password, bool tryLoopback)
        {
            var r = new string[] {};

            int port = MainForm.Conf.ServerPort;

            if (MainForm.Conf.IPMode == "IPv6")
            {
                port = MainForm.Conf.LANPort;
            }

            try
            {
                bool   success;
                string ip = MainForm.IPAddressExternal(out success);
                if (success)
                {
                    r           = Wsa.TestConnection2(username, password, port, MainForm.Identifier, tryLoopback, MainForm.Conf.IPMode == "IPv4", ip, X509.SslEnabled);
                    WebsiteLive = true;
                }
            }
            catch (Exception ex)
            {
                WebsiteLive = false;
                MainForm.LogExceptionToFile(ex);
            }
            if (WebsiteLive)
            {
                LoginFailed = (r[0] == "Webservices_LoginFailed");
                if (r.Length == 1 && r[0] != "OK")
                {
                    r[0] = LocRm.GetString(r[0]);
                    MainForm.LogErrorToFile("Webservices: " + r[0]);
                }
                if (r.Length > 3 && r[3] != "")
                {
                    r[3] = LocRm.GetString(r[3]);
                    MainForm.LogErrorToFile("Webservices: " + r[3]);
                }
                return(r);
            }

            return(new[] { LocRm.GetString("iSpyDown") });
        }
Exemplo n.º 10
0
        private void Button1Click(object sender, EventArgs e)
        {
            string err = "";

            foreach (var s in mediaDirectoryEditor1.Directories)
            {
                if (!Directory.Exists(s.Entry))
                {
                    err += LocRm.GetString("Validate_MediaDirectory") + " (" + s.Entry + ")\n";
                    break;
                }
            }

            if (err != "")
            {
                MessageBox.Show(err, LocRm.GetString("Error"));
                return;
            }

            if (numJPEGQuality.Value != MainForm.Conf.JPEGQuality)
            {
                MainForm.EncoderParams.Param[0] = new EncoderParameter(Encoder.Quality, (int)numJPEGQuality.Value);
            }
            MainForm.Conf.Enable_Error_Reporting  = chkErrorReporting.Checked;
            MainForm.Conf.Enable_Update_Check     = chkCheckForUpdates.Checked;
            MainForm.Conf.Enable_Password_Protect = chkPasswordProtect.Checked;

            MainForm.Conf.NoActivityColor      = btnNoDetectColor.BackColor.ToRGBString();
            MainForm.Conf.ActivityColor        = btnDetectColor.BackColor.ToRGBString();
            MainForm.Conf.TrackingColor        = btnColorTracking.BackColor.ToRGBString();
            MainForm.Conf.VolumeLevelColor     = btnColorVolume.BackColor.ToRGBString();
            MainForm.Conf.MainColor            = btnColorMain.BackColor.ToRGBString();
            MainForm.Conf.AreaColor            = btnColorArea.BackColor.ToRGBString();
            MainForm.Conf.BackColor            = btnColorBack.BackColor.ToRGBString();
            MainForm.Conf.BorderHighlightColor = btnBorderHighlight.BackColor.ToRGBString();
            MainForm.Conf.BorderDefaultColor   = btnBorderDefault.BackColor.ToRGBString();

            MainForm.Conf.Enabled_ShowGettingStarted = chkShowGettingStarted.Checked;
            MainForm.Conf.Opacity              = tbOpacity.Value;
            MainForm.Conf.OpenGrabs            = chkOpenGrabs.Checked;
            MainForm.Conf.BalloonTips          = chkBalloon.Checked;
            MainForm.Conf.TrayIconText         = txtTrayIcon.Text;
            MainForm.Conf.IPCameraTimeout      = Convert.ToInt32(txtIPCameraTimeout.Value);
            MainForm.Conf.ServerReceiveTimeout = Convert.ToInt32(txtServerReceiveTimeout.Value);
            MainForm.Conf.ServerName           = txtServerName.Text;
            MainForm.Conf.AutoSchedule         = chkAutoSchedule.Checked;
            MainForm.Conf.CPUMax = Convert.ToInt32(numMaxCPU.Value);
            MainForm.Conf.MaxRecordingThreads         = (int)numMaxRecordingThreads.Value;
            MainForm.Conf.CreateAlertWindows          = chkAlertWindows.Checked;
            MainForm.Conf.MaxRedrawRate               = (int)numRedraw.Value;
            MainForm.Conf.Priority                    = ddlPriority.SelectedIndex + 1;
            MainForm.Conf.Monitor                     = chkMonitor.Checked;
            MainForm.Conf.ScreensaverWakeup           = chkInterrupt.Checked;
            MainForm.Conf.PlaybackMode                = ddlPlayback.SelectedIndex;
            MainForm.Conf.PreviewItems                = (int)numMediaPanelItems.Value;
            MainForm.Conf.BigButtons                  = chkBigButtons.Checked;
            MainForm.Conf.DeleteToRecycleBin          = chkRecycle.Checked;
            MainForm.Conf.SpeechRecognition           = chkSpeechRecognition.Checked;
            MainForm.Conf.AppendLinkText              = txtAppendLinkText.Text;
            MainForm.Conf.StartupForm                 = ddlStartUpForm.SelectedItem.ToString();
            MainForm.Conf.TrayOnMinimise              = chkMinimiseToTray.Checked;
            MainForm.Conf.MJPEGStreamInterval         = (int)numMJPEGStreamInterval.Value;
            MainForm.Conf.AlertOnDisconnect           = txtAlertOnDisconnect.Text;
            MainForm.Conf.AlertOnReconnect            = txtAlertOnReconnect.Text;
            MainForm.Conf.StartupMode                 = ddlStartupMode.SelectedIndex;
            MainForm.Conf.EnableGZip                  = chkGZip.Checked;
            MainForm.Conf.DisconnectNotificationDelay = (int)numDisconnectNotification.Value;
            var l = mediaDirectoryEditor1.Directories.ToList();

            MainForm.Conf.MediaDirectories = l.ToArray();
            var l2 = ftpEditor1.Servers.ToList();

            MainForm.Conf.FTPServers               = l2.ToArray();
            MainForm.Conf.MailAlertSubject         = txtAlertSubject.Text;
            MainForm.Conf.MailAlertBody            = txtAlertBody.Text;
            MainForm.Conf.SMSAlert                 = txtSMSBody.Text;
            MainForm.Conf.VLCFileCache             = (int)numFileCache.Value;
            MainForm.Conf.Password_Protect_Startup = chkPasswordProtectOnStart.Checked;
            SaveSMTPSettings();

            MainForm.Conf.Archive = txtArchive.Text.Trim();
            if (!String.IsNullOrEmpty(MainForm.Conf.Archive))
            {
                if (!MainForm.Conf.Archive.EndsWith(@"\"))
                {
                    MainForm.Conf.Archive += @"\";
                }
                if (!Directory.Exists(MainForm.Conf.Archive))
                {
                    MainForm.Conf.Archive = "";
                    MainForm.LogErrorToFile("Archive directory ignored - couldn't be found on disk");
                }
            }

            MainForm.Iconfont = new Font(FontFamily.GenericSansSerif, MainForm.Conf.BigButtons ? 22 : 15, FontStyle.Bold, GraphicsUnit.Pixel);

            MainForm.Conf.TalkMic = "";
            if (ddlTalkMic.Enabled)
            {
                if (ddlTalkMic.SelectedIndex > 0)
                {
                    MainForm.Conf.TalkMic = ddlTalkMic.SelectedItem.ToString();
                }
            }

            MainForm.Conf.MinimiseOnClose = chkMinimise.Checked;
            MainForm.Conf.JPEGQuality     = (int)numJPEGQuality.Value;
            MainForm.Conf.IPv6Disabled    = !chkEnableIPv6.Checked;

            MainForm.SetPriority();

            var ips = rtbAccessList.Text.Trim().Split(',');
            var t   = ips.Select(ip => ip.Trim()).Where(ip2 => ip2 != "").Aggregate("", (current, ip2) => current + (ip2 + ","));

            MainForm.Conf.AllowedIPList = t.Trim(',');
            LocalServer.AllowedIPs      = null;

            var refs = rtbReferrers.Text.Trim().Split(',');
            var t2   = refs.Select(ip => ip.Trim()).Where(ip2 => ip2 != "").Aggregate("", (current, ip2) => current + (ip2 + ","));

            MainForm.Conf.Referers      = t2.Trim(',');
            LocalServer.AllowedReferers = null;


            MainForm.Conf.ShowOverlayControls = chkOverlay.Checked;

            string lang = ((ListItem)ddlLanguage.SelectedItem).Value[0];

            if (lang != MainForm.Conf.Language)
            {
                ReloadResources = true;
                LocRm.Reset();
            }
            MainForm.Conf.Language = lang;
            if (chkStartup.Checked)
            {
                try
                {
                    _rkApp = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run", true);
                    if (_rkApp != null)
                    {
                        _rkApp.SetValue("iSpy", "\"" + Application.ExecutablePath + "\" -silent", RegistryValueKind.String);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                    MainForm.LogExceptionToFile(ex);
                }
            }
            else
            {
                try
                {
                    _rkApp = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run", true);
                    if (_rkApp != null)
                    {
                        _rkApp.DeleteValue("iSpy", false);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                    MainForm.LogExceptionToFile(ex);
                }
            }

            //SetStorageOptions();

            MainForm.ReloadColors();

            if (ddlJoystick.SelectedIndex > 0)
            {
                string nameid = _sticks[ddlJoystick.SelectedIndex - 1];
                MainForm.Conf.Joystick.id = nameid.Split('|')[1];

                MainForm.Conf.Joystick.XAxis = jaxis1.ID;

                MainForm.Conf.Joystick.InvertXAxis = jaxis1.Invert;

                MainForm.Conf.Joystick.YAxis       = jaxis2.ID;
                MainForm.Conf.Joystick.InvertYAxis = jaxis2.Invert;

                MainForm.Conf.Joystick.ZAxis       = jaxis3.ID;
                MainForm.Conf.Joystick.InvertZAxis = jaxis3.Invert;

                MainForm.Conf.Joystick.Record   = jbutton1.ID;
                MainForm.Conf.Joystick.Snapshot = jbutton2.ID;
                MainForm.Conf.Joystick.Talk     = jbutton3.ID;
                MainForm.Conf.Joystick.Listen   = jbutton4.ID;
                MainForm.Conf.Joystick.Play     = jbutton5.ID;
                MainForm.Conf.Joystick.Next     = jbutton6.ID;
                MainForm.Conf.Joystick.Previous = jbutton7.ID;
                MainForm.Conf.Joystick.Stop     = jbutton8.ID;
                MainForm.Conf.Joystick.MaxMin   = jbutton9.ID;
            }
            else
            {
                MainForm.Conf.Joystick.id = "";
            }

            MainForm.Conf.Logging.Enabled  = chkEnableLogging.Checked;
            MainForm.Conf.Logging.FileSize = (int)numMaxLogSize.Value;
            MainForm.Conf.Logging.KeepDays = (int)numKeepLogs.Value;

            DialogResult = DialogResult.OK;
            Close();
        }
Exemplo n.º 11
0
        private static void Upload()
        {           
            UserState us = UploadFiles.Dequeue();
            Console.WriteLine("youtube: upload " + us.AbsoluteFilePath);

            var settings = new YouTubeRequestSettings("iSpy", MainForm.Conf.YouTubeKey, MainForm.Conf.YouTubeUsername, MainForm.Conf.YouTubePassword);
            var request = new YouTubeRequest(settings);

            var v = new Google.YouTube.Video
                        {
                            Title = "iSpy: " + us.CameraData.name,
                            Description = MainForm.Website+": free open source surveillance software: " +
                                          us.CameraData.description
                        };
            if (us.CameraData == null)
            {
                if (UploadFiles.Count > 0)
                    Upload();
                return;
            }
            v.Keywords = us.CameraData.settings.youtube.tags;
            if (v.Keywords.Trim() == "")
                v.Keywords = "ispyconnect"; //must specify at least one keyword
            v.Tags.Add(new MediaCategory(us.CameraData.settings.youtube.category));
            v.YouTubeEntry.Private = !us.Ispublic;
            v.Media.Categories.Add(new MediaCategory(us.CameraData.settings.youtube.category));
            v.Private = !us.Ispublic;
            v.Author = "iSpyConnect.com - Camera Security Software (open source)";

            if (us.EmailOnComplete != "")
                v.Private = false;

            string contentType = MediaFileSource.GetContentTypeForFileName(us.AbsoluteFilePath);
            v.YouTubeEntry.MediaSource = new MediaFileSource(us.AbsoluteFilePath, contentType);

            // add the upload uri to it
            //var link =
            //    new AtomLink("http://uploads.gdata.youtube.com/resumable/feeds/api/users/" +
            //                 MainForm.Conf.YouTubeAccount + "/uploads") {Rel = ResumableUploader.CreateMediaRelation};
            //v.YouTubeEntry.Links.Add(link);

            bool success = false;
            ((GDataRequestFactory)request.Service.RequestFactory).Timeout = 60 * 60 * 1000;
            Google.YouTube.Video vCreated = null;
            try
            {
                vCreated = request.Upload(v);
                success = true;
            }
            catch (GDataRequestException ex1)
            {
                MainForm.LogErrorToFile("YouTube Uploader: " + ex1.ResponseString+" ("+ex1.Message+")");
                if (ex1.ResponseString=="NoLinkedYouTubeAccount")
                {
                    MainForm.LogMessageToFile(
                        "This is because the Google account you connected has not been linked to YouTube yet. The simplest way to fix it is to simply create a YouTube channel for that account: http://www.youtube.com/create_channel");
                }
            }
            catch (Exception ex)
            {
                MainForm.LogExceptionToFile(ex);
            }
            if (success)
            {
                Console.WriteLine("Uploaded: http://www.youtube.com/watch?v=" + vCreated.VideoId);

                string msg = "YouTube video uploaded: <a href=\"http://www.youtube.com/watch?v=" + vCreated.VideoId + "\">" +
                                vCreated.VideoId + "</a>";
                if (vCreated.Private)
                    msg += " (private)";
                else
                    msg += " (public)";
                MainForm.LogMessageToFile(msg);

                if (us.EmailOnComplete != "" && us.Ispublic)
                {
                    SendYouTubeMails(us.EmailOnComplete, us.Message, vCreated.VideoId);
                }
                //check against most recent uploaded videos
                MainForm.Conf.UploadedVideos += "," + us.AbsoluteFilePath + "|" + vCreated.VideoId;
                if (MainForm.Conf.UploadedVideos.Length > 10000)
                    MainForm.Conf.UploadedVideos = "";
            }
            if (UploadFiles.Count>0)
                Upload();
        }
Exemplo n.º 12
0
        void FfmpegMergeProcessExited(object sender, EventArgs e)
        {
            if (_ffmpegProcess.ExitCode == 0)
            {
                if (_pbMerge.Count > 0)
                {
                    var ma = 0d;
                    var fi = new FileInfo(_dir + _outfile);


                    var alertData       = new StringBuilder();
                    int durationSeconds = 0;
                    foreach (var m in _pbMerge)
                    {
                        if (m.AlertData != "")
                        {
                            alertData.Append(m.AlertData);
                            alertData.Append(",");
                        }
                        durationSeconds += m.DurationSeconds;

                        if (m.MaxAlarm > ma)
                        {
                            ma = m.MaxAlarm;
                        }
                    }

                    var ff = new FilesFile
                    {
                        CreatedDateTicks     = DateTime.Now.Ticks,
                        DurationSeconds      = durationSeconds,
                        IsTimelapse          = false,
                        TriggerLevel         = _pbMerge.First().TriggerLevel,
                        TriggerLevelMax      = _pbMerge.First().TriggerLevelMax,
                        Filename             = _outfile,
                        AlertData            = Helper.GetMotionDataPoints(alertData),
                        MaxAlarm             = ma,
                        SizeBytes            = fi.Length,
                        IsMergeFile          = true,
                        IsMergeFileSpecified = true
                    };

                    string name;
                    if (_currentObject.Ot == 1)
                    {
                        var vl = MainClass.GetVolumeLevel(_currentObject.ID);
                        vl.AddFile(ff);
                        name = vl.Micobject.name;
                    }
                    else
                    {
                        var cw = MainClass.GetCameraWindow(_currentObject.ID);
                        cw.AddFile(ff);
                        name = cw.Camobject.name;

                        var fpv = _pbMerge.First();
                        //get preview image
                        string imgname = fpv.Filename.Substring(0,
                                                                fpv.Filename.LastIndexOf(".", StringComparison.Ordinal));
                        var imgpath = _dir + "thumbs/" + imgname + "_large.jpg";

                        if (File.Exists(imgpath))
                        {
                            Image bmpPreview = Image.FromFile(imgpath);

                            string jpgname = _dir + "thumbs\\" + ff.Filename.Substring(0,
                                                                                       ff.Filename.LastIndexOf(".", StringComparison.Ordinal));

                            bmpPreview.Save(jpgname + "_large.jpg", MainForm.Encoder,
                                            MainForm.EncoderParams);

                            Image.GetThumbnailImageAbort myCallback = ThumbnailCallback;
                            Image myThumbnail = bmpPreview.GetThumbnailImage(96, 72, myCallback, IntPtr.Zero);

                            myThumbnail.Save(jpgname + ".jpg", MainForm.Encoder,
                                             MainForm.EncoderParams);

                            myThumbnail.Dispose();
                            bmpPreview.Dispose();
                        }
                    }

                    var fp = new FilePreview(_outfile, durationSeconds, name, ff.CreatedDateTicks, _currentObject.Ot, _currentObject.ID, ma, false, true);
                    MainForm.MasterFileAdd(fp);
                    MainForm.NeedsMediaRefresh = Helper.Now;
                }
                _pbMerge.Clear();
            }
            else
            {
                MainForm.LogErrorToFile("FFMPEG process exited with code " + _ffmpegProcess.ExitCode);
                MessageBox.Show(this, LocRm.GetString("ErrorCheckLogFile"));
            }
            DoClose();
        }
Exemplo n.º 13
0
 void FfmpegMergeProcessErrorDataReceived(object sender, DataReceivedEventArgs e)
 {
     MainForm.LogErrorToFile("merge process error: " + e.Data);
     DoClose();
 }
Exemplo n.º 14
0
        public bool FTP(string server, bool passive, string username, string password, string filename, byte[] contents,
                        out string error)
        {
            bool failed = false;

            try
            {
                var target = new Uri(server);
                int i      = 0;
                while (filename.IndexOf("{") != -1 && i < 20)
                {
                    filename = String.Format(System.Globalization.CultureInfo.InvariantCulture, filename, DateTime.Now);
                    i++;
                }

                //try uploading
                //directory tree
                var           filepath = filename.Split('/');
                var           path     = "";
                FtpWebRequest request;
                for (var iDir = 0; iDir < filepath.Length - 1; iDir++)
                {
                    path               += filepath[iDir] + "/";
                    request             = (FtpWebRequest)WebRequest.Create(target + path);
                    request.Credentials = new NetworkCredential(username, password);
                    request.Method      = WebRequestMethods.Ftp.MakeDirectory;
                    try { request.GetResponse(); } catch
                    {
                        //directory exists
                    }
                }

                request             = (FtpWebRequest)WebRequest.Create(target + filename);
                request.Credentials = new NetworkCredential(username, password);
                request.UsePassive  = passive;
                request.Method      = WebRequestMethods.Ftp.UploadFile;


                request.ContentLength = contents.Length;

                Stream requestStream = request.GetRequestStream();
                requestStream.Write(contents, 0, contents.Length);
                requestStream.Close();

                var response = (FtpWebResponse)request.GetResponse();
                if (response != null)
                {
                    if (response.StatusCode != FtpStatusCode.ClosingData)
                    {
                        MainForm.LogErrorToFile("FTP Failed: " + response.StatusDescription);
                        failed = true;
                    }

                    response.Close();
                }
                error = "";
            }
            catch (Exception ex)
            {
                error  = ex.Message;
                failed = true;
            }
            return(!failed);
        }
Exemplo n.º 15
0
        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            string sUrlToReadFileFrom = Url;
            var    url      = new Uri(sUrlToReadFileFrom);
            var    request  = WebRequest.Create(url);
            var    response = request.GetResponse();
            // gets the size of the file in bytes

            Int64 iSize = response.ContentLength;

            // keeps track of the total bytes downloaded so we can update the progress bar
            int iRunningByteTotal = 0;

            // use the webclient object to download the file

            using (Stream streamRemote = response.GetResponseStream())
            {
                if (streamRemote != null)
                {
                    streamRemote.ReadTimeout = 8000;
                    // loop the stream and get the file into the byte buffer
                    var byteBuffer = new byte[iSize];
                    int iByteSize;
                    while ((iByteSize = streamRemote.Read(byteBuffer, iRunningByteTotal, byteBuffer.Length - iRunningByteTotal)) > 0 && !backgroundWorker1.CancellationPending)
                    {
                        iRunningByteTotal += iByteSize;

                        // calculate the progress out of a base "100"
                        var dIndex = (double)(iRunningByteTotal);
                        var dTotal = (double)byteBuffer.Length;
                        var dProgressPercentage = (dIndex / dTotal);
                        var iProgressPercentage = (int)(dProgressPercentage * 100);

                        // update the progress bar
                        backgroundWorker1.ReportProgress(iProgressPercentage);
                        int total = iRunningByteTotal;
                        UISync.Execute(() => lblProgress.Text = total + " / " + iSize);
                    }
                    if (!backgroundWorker1.CancellationPending)
                    {
                        if (SaveLocation.EndsWith(".xml"))
                        {
                            var ms  = new MemoryStream(byteBuffer);
                            var doc = new XmlDocument();
                            try
                            {
                                doc.Load(ms);
                                doc.Save(SaveLocation);
                                success = true;
                            }
                            catch (Exception ex)
                            {
                                MainForm.LogExceptionToFile(ex);
                                DialogResult = DialogResult.Cancel;
                                aborting     = true;
                                Close();
                                return;
                            }
                            ms.Dispose();
                        }
                    }
                    else
                    {
                        MainForm.LogMessageToFile("Update cancelled");
                    }
                }
                else
                {
                    MainForm.LogErrorToFile("Response stream from " + Url + " failed");
                }
            }
            response.Close();
        }
Exemplo n.º 16
0
        public bool FTP(string server, bool passive, string username, string password, string filename, int counter, byte[] contents, out string error, bool rename)
        {
            bool failed = false;

            try
            {
                var target = new Uri(server);
                int i      = 0;
                filename = filename.Replace("{C}", counter.ToString(CultureInfo.InvariantCulture));
                if (rename)
                {
                    filename += ".tmp";
                }

                while (filename.IndexOf("{", StringComparison.Ordinal) != -1 && i < 20)
                {
                    filename = String.Format(CultureInfo.InvariantCulture, filename, Helper.Now);
                    i++;
                }

                //try uploading
                //directory tree
                var           filepath = filename.Trim('/').Split('/');
                var           path     = "";
                FtpWebRequest request;
                for (var iDir = 0; iDir < filepath.Length - 1; iDir++)
                {
                    path               += filepath[iDir] + "/";
                    request             = (FtpWebRequest)WebRequest.Create(target + path);
                    request.Credentials = new NetworkCredential(username, password);
                    request.Method      = WebRequestMethods.Ftp.MakeDirectory;
                    try { request.GetResponse(); } catch
                    {
                        //directory exists
                    }
                }

                request             = (FtpWebRequest)WebRequest.Create(target + filename);
                request.Credentials = new NetworkCredential(username, password);
                request.UsePassive  = passive;
                //request.UseBinary = true;
                request.Method        = WebRequestMethods.Ftp.UploadFile;
                request.ContentLength = contents.Length;

                Stream requestStream = request.GetRequestStream();
                requestStream.Write(contents, 0, contents.Length);
                requestStream.Close();

                var response = (FtpWebResponse)request.GetResponse();
                if (response.StatusCode != FtpStatusCode.ClosingData)
                {
                    MainForm.LogErrorToFile("FTP Failed: " + response.StatusDescription);
                    failed = true;
                }

                response.Close();

                if (rename && !failed)
                {
                    //delete existing
                    request             = (FtpWebRequest)WebRequest.Create(target + filename.Substring(0, filename.Length - 4));
                    request.Credentials = new NetworkCredential(username, password);
                    request.UsePassive  = passive;
                    //request.UseBinary = true;
                    request.Method = WebRequestMethods.Ftp.DeleteFile;
                    filename       = "/" + filename;

                    try
                    {
                        response = (FtpWebResponse)request.GetResponse();
                        if (response.StatusCode != FtpStatusCode.ActionNotTakenFileUnavailable &&
                            response.StatusCode != FtpStatusCode.FileActionOK)
                        {
                            MainForm.LogErrorToFile("FTP Delete Failed: " + response.StatusDescription);
                            failed = true;
                        }

                        response.Close();
                    }
                    catch (Exception ex)
                    {
                        MainForm.LogExceptionToFile(ex);
                        //ignore
                    }

                    //rename file
                    if (!failed)
                    {
                        request             = (FtpWebRequest)WebRequest.Create(target + filename);
                        request.Credentials = new NetworkCredential(username, password);
                        request.UsePassive  = passive;
                        //request.UseBinary = true;
                        request.Method = WebRequestMethods.Ftp.Rename;
                        filename       = "/" + filename;

                        request.RenameTo = filename.Substring(0, filename.Length - 4);

                        response = (FtpWebResponse)request.GetResponse();
                        if (response.StatusCode != FtpStatusCode.FileActionOK)
                        {
                            MainForm.LogErrorToFile("FTP Rename Failed: " + response.StatusDescription);
                            failed = true;
                        }

                        response.Close();
                    }
                }

                error = "";
            }
            catch (Exception ex)
            {
                error  = ex.Message;
                failed = true;
            }
            return(!failed);
        }