Пример #1
0
        static void Main(string[] args)
        {
            try
            {
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
            Console.Title = "Evercam Movie Maker";
            Stopwatch sw = new Stopwatch();
            sw.Start();

            sw.Stop();
            //Console.WriteLine("Cache loaded in " + sw.ElapsedMilliseconds / 1000 + " s");
            Evercam.SANDBOX = Settings.EvercamSandboxMode;
            Evercam = new Evercam(Settings.EvercamClientID, Settings.EvercamClientSecret, Settings.EvercamClientUri);

            MovieMaker mm = new MovieMaker(delegate(string str) { Console.WriteLine(str); }, Evercam);
            mm.Start();

            Console.WriteLine("Press enter to continue...");
            Console.ReadLine();
            }
            catch (Exception ex)
            {
               //SaveMovieLog(DateTime.UtcNow + ": " + ex.Message);
            }
        }
Пример #2
0
        public static int DownloadAllImages(Evercam evercam, Camera camera, DateTime userFromDate, DateTime userToDate, string path)
        {
            byte[] data = null;
            int index = 0;
            while (userFromDate < userToDate)
            {
                var diff_date = userToDate - userFromDate;
                DateTime newToDate = DateTime.Now;
                if (diff_date.Hours >= 1)
                {
                    newToDate = userFromDate.AddHours(1);
                }
                else
                {
                    newToDate = userToDate;
                }

                long fromTimestamp = Utility.ToUnixTimestamp(userFromDate);
                long toTimestamp = Utility.ToUnixTimestamp(newToDate);
                List<Snapshot> snaps = evercam.GetSnapshots(camera.ID, fromTimestamp, toTimestamp, 3600, 1);

                foreach (Snapshot s in snaps)
                {
                    try
                    {
                        Snapshot snap = evercam.GetSnapshot(camera.ID, s.CreatedAt.ToString(), "Evercam Proxy", true, 0);
                        DateTime datetime = Utility.ToWindowsDateTime(snap.CreatedAt);
                        DateTime snaptime = ConvertFromUtc(datetime, Utility.ToWindowsTimezone(camera.Timezone));
                        if (snap != null && snaptime >= userFromDate && snaptime <= newToDate)
                        {
                            data = snap.ToBytes();

                            //if (timestamp == "true")
                            //    data = Utils.TimestampImage(data, snaptime.ToString(), Settings.WatermarkPostion);

                            Console.WriteLine("Camera: " + camera.ID + ", " + index + " : " + snap.CreatedAt + " = " + snaptime);
                            try
                            {
                                if (SaveFile(Path.Combine(path, index + ".jpg"), data))
                                    index++;
                            }
                            catch (Exception x)
                            {
                                Console.WriteLine(" - ERR1 :" + x.Message);
                            }
                        }
                    }
                    catch (Exception x)
                    {
                        Console.WriteLine(" - ERR2 :" + x.Message);
                    }
                }
                userFromDate = newToDate;
            }
            return index;
        }
Пример #3
0
        public static int DownloadAllImages(Evercam evercam, string user, string camera, string timezone, DateTime userFromDate, DateTime userToDate, int startIndex, string timestamp, string path)
        {
            byte[] data = null;
            int index = startIndex;
            long fromTimestamp = Utility.ToUnixTimestamp(userFromDate);
            long toTimestamp = Utility.ToUnixTimestamp(userToDate);
            List<Snapshot> snaps = evercam.GetSnapshots(camera, fromTimestamp, toTimestamp, 10000, null);

            foreach (Snapshot s in snaps)
            {
                try
                {
                    Snapshot snap = evercam.GetSnapshot(camera, s.CreatedAt.ToString(), "Evercam Proxy", true, 0);
                    DateTime datetime = Utility.ToWindowsDateTime(snap.CreatedAt);
                    DateTime snaptime = Utils.ConvertFromUtc(datetime, timezone);
                    if (snap != null && snaptime >= userFromDate)
                    {
                        data = snap.ToBytes();

                        //if (timestamp == "true")
                        //    data = Utils.TimestampImage(data, snaptime.ToString(), Settings.WatermarkPostion);

                        Console.WriteLine(index + " : " + snap.CreatedAt + " = " + snaptime);

                        try
                        {
                            if (SaveFile(path + index + ".jpg", data))
                                index++;
                        }
                        catch (Exception x)
                        {
                            Console.WriteLine(" - ERR1 :" + x.Message);
                        }
                    }
                }
                catch (Exception x)
                {
                    Console.WriteLine(" - ERR2 :" + x.Message);
                }
            }
            return index;
        }
Пример #4
0
 public List<Snapshot> GetSnapshots(string key)
 {
     SnapmailRowData snapmail = SnapmailDao.Get(key);
     Evercam.SANDBOX = Settings.EvercamSandboxMode;
     Evercam evercam = new Evercam(snapmail.AccessToken);
     string[] cred = snapmail.AccessToken.Split(':');
     if (cred.Length >= 2)
         evercam = new Evercam(cred[0], cred[1]);
     List<Snapshot> snaps = new List<Snapshot>();
     string[] camids = snapmail.Cameras.Split(',');
     List<Camera> cams = evercam.GetCameras(null, snapmail.UserId, true);
     foreach (Camera c in cams)
     {
         var results = Array.FindAll(camids, s => s.Equals(c.ID));
         if (results.Length > 0 && c.Thumbnail != null)
         {
             Snapshot snap = new Snapshot() { Data = c.Thumbnail };
             snaps.Add(snap);
         }
     }
     return snaps;
 }
Пример #5
0
        public TimelapseModel Update(string code, [FromBody]TimelapseInfoModel data, string id)
        {
            Timelapse t = TimelapseDao.Get(code);
            if (t.UserId != id)
                throw new HttpResponseException(HttpStatusCode.Forbidden);

            t = TimelapseModel.Convert(data, t.UserId, t.ID, code, t.Status);

            if (!TimelapseDao.Update(t))
                throw new HttpResponseException(HttpStatusCode.BadRequest);

            if (t.FromDT.Hour >= t.ToDT.Hour)
            {
                // ToDT is in next day
                DateTime from = new DateTime();
                DateTime to = new DateTime();
                if (t.DateAlways)
                {
                    from = new DateTime(DateTime.UtcNow.Year, DateTime.UtcNow.Month, DateTime.UtcNow.Day,
                        t.FromDT.Hour, t.FromDT.Minute, t.FromDT.Second);
                    to = new DateTime(from.Year, from.Month, from.Day,
                        t.ToDT.Hour, t.ToDT.Minute, t.ToDT.Second).AddDays(1);
                }
                else
                {
                    from = new DateTime(t.FromDT.Year, t.FromDT.Month, t.FromDT.Day,
                        t.FromDT.Hour, t.FromDT.Minute, t.FromDT.Second);
                    to = new DateTime(t.ToDT.Year, t.ToDT.Month, t.ToDT.Day,
                        t.ToDT.Hour, t.ToDT.Minute, t.ToDT.Second);
                }

                if (!t.DateAlways && t.ToDT.Date <= t.FromDT.Date)
                    TimelapseDao.UpdateStatus(t.Code, TimelapseStatus.Stopped, "Out of schedule", t.TimeZone);
                else if ((DateTime.UtcNow < from || DateTime.UtcNow > to))
                {
                    if (t.DateAlways)
                        TimelapseDao.UpdateStatus(t.Code, TimelapseStatus.Scheduled, "Recording on schedule", t.TimeZone);
                    else
                        TimelapseDao.UpdateStatus(t.Code, TimelapseStatus.Stopped, "Out of schedule", t.TimeZone);
                }
            }
            else if (t.Status > (int)TimelapseStatus.Processing) {
                if (t.DateAlways && t.TimeAlways)
                    TimelapseDao.UpdateStatus(t.Code, TimelapseStatus.Processing, "Processing...", t.TimeZone);
                else if (t.DateAlways && !t.TimeAlways)
                {
                    if (DateTime.UtcNow.TimeOfDay >= t.FromDT.TimeOfDay && DateTime.UtcNow.TimeOfDay <= t.ToDT.TimeOfDay)
                        TimelapseDao.UpdateStatus(t.Code, TimelapseStatus.Processing, "Processing...", t.TimeZone);
                }
                else if (DateTime.UtcNow >= t.FromDT && DateTime.UtcNow <= t.ToDT)
                    TimelapseDao.UpdateStatus(t.Code, TimelapseStatus.Processing, "Processing...", t.TimeZone);
            }

            string base64 = Settings.TimelapseAPIUrl + "testimage/" + Settings.TempTimelapse;
            if (!string.IsNullOrEmpty(data.watermark_file))
            {
                //// create placeholder image at the same time
                Evercam.SANDBOX = Settings.EvercamSandboxMode;
                Evercam evercam = new Evercam(Settings.EvercamClientID, Settings.EvercamClientSecret, Settings.EvercamClientUri);
                if (!string.IsNullOrEmpty(t.OauthToken))
                {
                    string[] cred = t.OauthToken.Split(':');
                    if (cred.Length >= 2)
                        evercam = new Evercam(cred[0], cred[1]);
                    else
                        evercam = new Evercam(t.OauthToken);
                }

                Camera c = evercam.GetCamera(t.CameraId);
                string cleanCameraId = BLL.Common.Utils.RemoveSymbols(c.ID);
                string filePath = Path.Combine(Settings.BucketUrl, Settings.BucketName, cleanCameraId, t.ID.ToString());
                if (!Directory.Exists(filePath))
                    Directory.CreateDirectory(filePath);

                try
                {
                    byte[] image = evercam.CreateSnapshot(c.ID, Settings.EvercamClientName, true).ToBytes();
                    base64 = "data:image/jpeg;base64," + Convert.ToBase64String(
                            Utils.WatermarkImage(
                                t.ID,
                                image,
                                filePath + "\\" + t.Code + ".jpg",
                                t.WatermarkImage,
                                t.WatermarkPosition));
                }
                catch (Exception x) { BLL.Common.Utils.FileLog(t.ID + " - " + x.ToString()); }
            }

            return TimelapseModel.Convert(TimelapseDao.Get(code), base64);
        }
Пример #6
0
        public TimelapseModel Post([FromBody]TimelapseInfoModel data, string id)
        {
            Timelapse t = TimelapseModel.Convert(data, id);
            t.ServerIP = Request.RequestUri.Host;
            t.TimelapsePath = Settings.BucketUrl;
            t.Status = (int)TimelapseStatus.Processing;
            t.Code = Utils.GeneratePassCode(10);

            int tid = 0;
            if ((tid = TimelapseDao.Insert(t)) == 0)
                throw new HttpResponseException(HttpStatusCode.BadRequest);

            string base64 = Settings.TimelapseAPIUrl + "testimage/" + Settings.TempTimelapse;
            if (!string.IsNullOrEmpty(data.watermark_file))
            {
                //// create placeholder image at the same time
                Evercam.SANDBOX = Settings.EvercamSandboxMode;
                Evercam evercam = new Evercam(Settings.EvercamClientID, Settings.EvercamClientSecret, Settings.EvercamClientUri);
                if (!string.IsNullOrEmpty(t.OauthToken))
                {
                    string[] cred = t.OauthToken.Split(':');
                    if (cred.Length >= 2)
                        evercam = new Evercam(cred[0], cred[1]);
                    else
                        evercam = new Evercam(t.OauthToken);
                }

                Camera c = evercam.GetCamera(t.CameraId);
                string cleanCameraId = BLL.Common.Utils.RemoveSymbols(c.ID);
                string filePath = Path.Combine(Settings.BucketUrl, Settings.BucketName, cleanCameraId, tid.ToString());
                if (!Directory.Exists(filePath))
                    Directory.CreateDirectory(filePath);

                try
                {
                    byte[] image = evercam.CreateSnapshot(c.ID, Settings.EvercamClientName, true).ToBytes();
                    base64 = "data:image/jpeg;base64," + Convert.ToBase64String(
                        Utils.WatermarkImage(
                            t.ID,
                            image,
                            filePath + "\\" + t.Code + ".jpg",
                            t.WatermarkImage,
                            t.WatermarkPosition));
                }
                catch (Exception x) { BLL.Common.Utils.FileLog(t.ID + " - " + x.ToString()); }
            }

            return TimelapseModel.Convert(TimelapseDao.Get(tid), base64);
        }
Пример #7
0
        public DataModel GetPlaceholder(string code)
        {
            Evercam.SANDBOX = Settings.EvercamSandboxMode;
            Evercam evercam = new Evercam(Settings.EvercamClientID, Settings.EvercamClientSecret, Settings.EvercamClientUri);
            Timelapse t = TimelapseDao.Get(code);
            if (!string.IsNullOrEmpty(t.OauthToken))
            {
                string[] cred = t.OauthToken.Split(':');
                if (cred.Length >= 2)
                    evercam = new Evercam(cred[0], cred[1]);
                else
                    evercam = new Evercam(t.OauthToken);
            }

            Camera c = evercam.GetCamera(t.CameraId);

            string cleanCameraId = BLL.Common.Utils.RemoveSymbols(c.ID);
            string filePath = Path.Combine(Settings.BucketUrl, Settings.BucketName, cleanCameraId, t.ID.ToString());
            if (!Directory.Exists(filePath))
                Directory.CreateDirectory(filePath);

            try
            {
                byte[] image = evercam.CreateSnapshot(c.ID, Settings.EvercamClientName, true).ToBytes();
                return new DataModel
                {
                    data = "data:image/jpeg;base64," + Convert.ToBase64String(
                        Utils.WatermarkImage(
                            t.ID,
                            image,
                            filePath + "\\" + t.Code + ".jpg",
                            t.WatermarkImage,
                            t.WatermarkPosition))
                };
            }
            catch (Exception x) { return new DataModel(); }
        }
Пример #8
0
        static void Main(string[] args)
        {
            Evercam.SANDBOX = Settings.EvercamSandboxMode;

            //// for testing
            //args = new string[1];
            //args[0] = "448d9df0-981b-4589-a17c-b80402d0bec9";

            if (!string.IsNullOrEmpty(args[0]))
            {
                while ((data = SnapmailDao.Get(args[0])) != null && data.IsActive && !string.IsNullOrEmpty(data.Recipients))
                {
                    if (!string.IsNullOrEmpty(data.AccessToken))
                    {
                        evercam = new Evercam(data.AccessToken);
                        string[] cred = data.AccessToken.Split(':');
                        if (cred.Length >= 2)
                            evercam = new Evercam(cred[0], cred[1]);
                        int hh = int.Parse(data.NotifyTime.Substring(0, 2));
                        int mm = int.Parse(data.NotifyTime.Substring(3, 2));
                        DateTime scheduled = new DateTime(DateTime.UtcNow.Year, DateTime.UtcNow.Month, DateTime.UtcNow.Day, hh, mm, 0);
                        scheduled = Utils.ConvertToUtc(scheduled, data.TimeZone, true);

                        DayOfWeek[] days = Utils.GetDaysOfWeek(data.NotifyDays);
                        if (days.Contains<DayOfWeek>(DateTime.UtcNow.DayOfWeek))
                        {
                            if (DateTime.UtcNow >= scheduled && DateTime.UtcNow <= scheduled.AddMinutes(1))
                            {
                                Utils.FileLog("User: "******", Cameras: " + data.Cameras, data.RowKey);

                                List<string> attachments = new List<string>();
                                bool anyImages = false;
                                bool anyErrors = false;
                                bool anyDebugs = false;
                                string images = "";
                                string errors = "<ul>";
                                string debugs = "<ul>";
                                string[] cc = data.Cameras.Split(',', ' ');
                                foreach (string c in cc)
                                {
                                    bool gotImage = false;
                                    string timestamp = DateTime.UtcNow.ToString("yyyyMMddHHmmssfff");
                                    string temppath = Path.Combine(Settings.TempImagePath, c + timestamp + ".jpg");

                                    Camera camera = new Camera();
                                    byte[] image = null;
                                    for (int i = 1; i <= Settings.TryCount; i++)
                                    {
                                        try
                                        {
                                            if (camera == null || string.IsNullOrEmpty(camera.ID))
                                                camera = evercam.GetCamera(c);

                                            // store and returns live snapshot on evercam
                                            image = evercam.CreateSnapshot(c, Settings.EvercamClientName, true).ToBytes();
                                            Utils.FileLog("Image data retrieved (try#" + i + "): " + data.RowKey, data.RowKey);

                                            if (image != null && Storage.SaveFile(temppath, image))
                                            {
                                                attachments.Add(temppath);
                                                temppath = WebUtility.UrlDecode(Path.Combine(Settings.TempImagePath, c + timestamp + ".jpg")).Replace(@"/", @"\\");
                                                temppath = temppath.Replace(Settings.TempImagePath.Replace(@"/", @"\\"), Settings.ServerUrl + @"images/");
                                                images += "<br /><img src='" + temppath + "' width='100%' /> <br /><br /><strong>" + camera.Name + "</strong> (" + camera.ID + ") - See the live view on Evercam by <a target='_blank' href='https:////dash.evercam.io/v1/cameras/" + c + "/live'>clicking here</a><br />";

                                                anyImages = true;
                                                gotImage = true;

                                                break;
                                            }
                                            else
                                            {
                                                debugs += "<li> <i>Image could not be saved from <a target='_blank' href='https:////dash.evercam.io/v1/cameras/" + c + "'>" + c + "</a></i>";
                                                Utils.FileLog("Image could not be saved from Camera " + c, data.RowKey);
                                                anyDebugs = true;
                                            }
                                        }
                                        catch (Exception x)
                                        {
                                            anyDebugs = true;
                                            debugs += "<li> <i>Image could not be saved from <a target='_blank' href='https:////dash.evercam.io/v1/cameras/" + c + "'>" + c + "</a></i>. [Error: " + x.Message + "]";
                                            Utils.FileLog("Error (try#" + i + "): " + data.RowKey + ": " + x.ToString(), data.RowKey);

                                            if (x.Message.Contains("offline"))
                                                break;

                                            if (i < Settings.TryCount)
                                                Thread.Sleep(Settings.RetryInterval);    // 15 seconds
                                        }
                                    }

                                    if (!gotImage)
                                    {
                                        // download latest snapshot from evercam
                                        try
                                        {
                                            image = evercam.GetThumbnail(c, true);

                                            // assuming that snapshot timestamp is in camera timezone
                                            if (Storage.SaveFile(temppath, image))
                                            {
                                                attachments.Add(temppath);
                                                temppath = WebUtility.UrlDecode(Path.Combine(Settings.TempImagePath, c + timestamp + ".jpg")).Replace(@"/", @"\\");
                                                temppath = temppath.Replace(Settings.TempImagePath.Replace(@"/", @"\\"), Settings.ServerUrl + @"images/");
                                                images += "<br /><img src='" + temppath + "' width='100%' /> <br /><br /><strong>" + camera.Name + "</strong> (" + camera.ID + ") - See the live view on Evercam by <a target='_blank' href='https:////dash.evercam.io/v1/cameras/" + c + "/live'>clicking here</a><br />";

                                                anyImages = true;
                                            }
                                            else
                                            {
                                                errors += "<li> <i>Could not retrieve an image from <a target='_blank' href='https:////dash.evercam.io/v1/cameras/" + c + "'>" + c + "</a></i>";
                                                debugs += "<li> <i>Latest image could not be retrieved from <a target='_blank' href='https:////dash.evercam.io/v1/cameras/" + c + "'>" + c + "</a></i>";
                                                Utils.FileLog("Latest image could not be saved from Camera " + c, data.RowKey);

                                                anyErrors = anyDebugs = true;
                                            }
                                        }
                                        catch (Exception x)
                                        {
                                            errors += "<li> <i>Could not retrieve an image from <a target='_blank' href='https:////dash.evercam.io/v1/cameras/" + c + "'>" + c + "</a></i>";
                                            debugs += "<li> <i>Latest image could not be retrieved from <a target='_blank' href='https:////dash.evercam.io/v1/cameras/" + c + "'>" + c + "</a>. [Error: " + x.Message + "]</i>";
                                            Utils.FileLog("Latest image could not be retrieved from Camera " + c, data.RowKey);
                                            anyErrors = anyDebugs = true;
                                        }
                                    }
                                }
                                errors += "</ul>";
                                debugs += "</ul>";

                                string message = "";
                                string debug = "";
                                if (anyImages) {
                                    message = data.Message.Replace("{br}", "<br />").Replace("{snapshots}", images + (!anyErrors ? "" : "<br />But...<br />" + errors)).Replace("{unsubscribe}", "<center style='font-size:11px'>If you want to change your Snapmail settings, <a target='_blank' href='" + Settings.ServerUrl + "?user="******"'>click here</a>.<br />If you would prefer not to receive future emails for this Scheduled SnapMail @ " + data.NotifyTime + ", you may <a target='_blank' href='" + Settings.ServerUrl + "Unsubscribe.html?id=" + data.RowKey + "&email={email}'>unsubscribe here</a>.</center>");
                                    debug = data.Message.Replace("{br}", "<br />").Replace("{snapshots}", images + (!anyDebugs ? "" : "<br />But...<br />" + debugs)).Replace("{unsubscribe}", "<center style='font-size:11px'>If you want to change your Snapmail settings, <a target='_blank' href='" + Settings.ServerUrl + "?user="******"'>click here</a>.<br />If you would prefer not to receive future emails for this Scheduled SnapMail @ " + data.NotifyTime + ", you may <a target='_blank' href='" + Settings.ServerUrl + "Unsubscribe.html?id=" + data.RowKey + "&email={email}'>unsubscribe here</a>.</center>");
                                }
                                else
                                {
                                    message = data.Message.Replace("{br}", "<br />").Replace("Here's the snapshot(s) from your cameras.", "").Replace("{snapshots}", (!anyErrors ? "" : errors)).Replace("{unsubscribe}", "<center style='font-size:11px'>If you want to change your Snapmail settings, <a target='_blank' href='" + Settings.ServerUrl + "?user="******"'>click here</a>.<br />If you would prefer not to receive future emails for this Scheduled SnapMail @ " + data.NotifyTime + ", you may <a target='_blank' href='" + Settings.ServerUrl + "Unsubscribe.html?id=" + data.RowKey + "&email={email}'>unsubscribe here</a>.</center>");
                                    debug = data.Message.Replace("{br}", "<br />").Replace("Here's the snapshot(s) from your cameras.", "").Replace("{snapshots}", (!anyDebugs ? "" : debugs)).Replace("{unsubscribe}", "<center style='font-size:11px'>If you want to change your Snapmail settings, <a target='_blank' href='" + Settings.ServerUrl + "?user="******"'>click here</a>.<br />If you would prefer not to receive future emails for this Scheduled SnapMail @ " + data.NotifyTime + ", you may <a target='_blank' href='" + Settings.ServerUrl + "Unsubscribe.html?id=" + data.RowKey + "&email={email}'>unsubscribe here</a>.</center>");
                                }

                                // Finally send email
                                Utils.SendMail(data.Subject.Replace("{notify_time}", data.NotifyTime), message, data.Recipients, attachments);

                                if (!string.IsNullOrEmpty(Settings.DebugEmail) && anyDebugs)
                                    Utils.SendMail("[DEBUG] " + data.Subject.Replace("{notify_time}", data.NotifyTime), debug, Settings.DebugEmail, attachments);

                                SnapmailDao.UpdateEmail(data.RowKey, message.Replace("{email}", data.Recipients), DateTime.UtcNow);

                                Utils.FileLog("SendMail: " + message, data.RowKey);
                            }
                            else
                            {
                                Utils.FileLog("Schedule out of time @ UTC " + scheduled.ToString(), data.RowKey);
                            }
                        }
                        else
                        {
                            Utils.FileLog("Schedule out of days @ " + data.NotifyDays, data.RowKey);
                        }
                    }
                    else
                    {
                        Utils.FileLog("Evercam Access Token Not Found @ " + data.RowKey, data.RowKey);
                    }

                    if (!data.IsScheduled)
                        SnapmailDao.UpdateScheduled(data.RowKey, true);

                    Thread.Sleep(Settings.CheckInterval);
                }

                if (data != null && !string.IsNullOrEmpty(data.RowKey))
                    Utils.FileLog("Exiting Snapmailer...", data.RowKey);
                else
                    Utils.FileLog("Exiting Snapmailer (no data)...", args[0]);
            }
        }
Пример #9
0
 //public string Prefix = Settings.BucketUrl + Settings.AwsBucketName + @"\";
 public MovieMaker(LogLine logger, Evercam evercam)
 {
     _logger = logger;
     _evercam = evercam;
     _tries = 0;
 }
Пример #10
0
        public static int DownloadImagesAtInterval(Evercam evercam, string user, Camera camera, DateTime fromDay, DateTime toDay, int fromHour, int toHour, int interval, int startIndex, string timestamp, string path)
        {
            int index = startIndex;
            DateTime from = new DateTime(fromDay.Year, fromDay.Month, fromDay.Day, fromHour, 0, 0);
            DateTime to = new DateTime(toDay.Year, toDay.Month, toDay.Day, toHour, 59, 59);
            while (from <= to)
            {
                byte[] data = null;
                long time = Utility.ToUnixTimestamp(Utils.ConvertToUtc(from, camera.Timezone));
                for (int i = 1; i <= 1; i++)
                {
                    try
                    {
                        int sec = interval * 60;
                        int range = Convert.ToInt32(sec / 2);
                        Snapshot snap = evercam.GetSnapshot(camera.ID, time.ToString(), "Evercam Proxy", true, range);
                        if (snap != null)
                        {
                            data = snap.ToBytes();

                            DateTime datetime = Utility.ToWindowsDateTime(snap.CreatedAt);
                            DateTime stamp = Utils.ConvertFromUtc(datetime, camera.Timezone);
                            //if (timestamp == "true")
                            //    Utils.TimestampImage(data, stamp.ToString(), 2);

                            Console.WriteLine(index + " : " + snap.CreatedAt + " = " + stamp);
                            break;
                        }
                    }
                    catch (Exception x)
                    {
                        //if (i < 2) Thread.Sleep(10 * 1000);
                        Console.WriteLine(" - ERR " + time + " :" + x.Message);
                    }
                }

                try
                {
                    if (SaveFile(path + index + ".jpg", data))
                        index++;
                }
                catch (Exception x)
                {
                    Console.WriteLine(" - ERR2 :" + x.Message);
                }

                from = from.AddMinutes(interval);
            }
            return index;
        }
Пример #11
0
 public static bool updateArchive(Evercam evercam, string camera_id, string archive_id, int total_frames, ArchiveStatus status)
 {
     try
     {
         ArchiveInfo archiveInfo = new ArchiveInfo();
         archiveInfo.CameraId = camera_id;
         archiveInfo.ID = archive_id;
         archiveInfo.Status = status;
         archiveInfo.Frames = total_frames;
         var res = evercam.UpdateArchive(archiveInfo);
         return true;
     }
     catch (Exception ex) {
         Console.WriteLine(ex.ToString());
         return false;
     }
 }
Пример #12
0
        static void Main(string[] args)
        {
            string ApiId = ConfigurationSettings.AppSettings["EvercamApiId"];
            string ApiKey = ConfigurationSettings.AppSettings["EvercamApiKey"];
            string UserId = ConfigurationSettings.AppSettings["UserId"];
            string CameraId = ConfigurationSettings.AppSettings["CameraId"];
            DateTime fromDay = DateTime.Parse(ConfigurationSettings.AppSettings["FromDate"]);
            DateTime toDay = DateTime.Parse(ConfigurationSettings.AppSettings["ToDate"]);
            int fromHour = int.Parse(ConfigurationSettings.AppSettings["FromHour"]);
            int toHour = int.Parse(ConfigurationSettings.AppSettings["ToHour"]);
            int fromMin = int.Parse(ConfigurationSettings.AppSettings["FromMin"]);
            int toMin = int.Parse(ConfigurationSettings.AppSettings["ToMin"]);
            int fromSec = int.Parse(ConfigurationSettings.AppSettings["FromSec"]);
            int toSec = int.Parse(ConfigurationSettings.AppSettings["ToSec"]);
            int intervalMin = int.Parse(ConfigurationSettings.AppSettings["IntervalMin"]);
            int startIndex = int.Parse(ConfigurationSettings.AppSettings["StartIndex"]);
            int moveIndex = int.Parse(ConfigurationSettings.AppSettings["MoveIndex"]);
            int fps = int.Parse(ConfigurationSettings.AppSettings["Fps"]);
            int x = int.Parse(ConfigurationSettings.AppSettings["CropX"]);
            int y = int.Parse(ConfigurationSettings.AppSettings["CropY"]);
            int w = int.Parse(ConfigurationSettings.AppSettings["CropW"]);
            int h = int.Parse(ConfigurationSettings.AppSettings["CropH"]);
            int watermarkPostion = int.Parse(ConfigurationSettings.AppSettings["WatermarkPostion"]);
            int timelapseId = int.Parse(ConfigurationSettings.AppSettings["TimelapseId"]);
            string imagesDir = ConfigurationSettings.AppSettings["ImagesDir"];
            string resizedDir = ConfigurationSettings.AppSettings["ResizedDir"];
            string moveDir = ConfigurationSettings.AppSettings["MoveDir"];
            string toDir = ConfigurationSettings.AppSettings["ToDir"];
            string videoDir = ConfigurationSettings.AppSettings["VideoDir"];
            string videoFile = ConfigurationSettings.AppSettings["VideoFile"];
            string concatFileA = ConfigurationSettings.AppSettings["ConcatFileA"];
            string concatFileB = ConfigurationSettings.AppSettings["ConcatFileB"];
            string watermarkFile = ConfigurationSettings.AppSettings["WatermarkFile"];
            string bitRate = ConfigurationSettings.AppSettings["BitRate"];
            string scale = ConfigurationSettings.AppSettings["Scale"];
            string reindexImages = ConfigurationSettings.AppSettings["ReindexImages"].ToLower();
            string moveImages = ConfigurationSettings.AppSettings["MoveImages"].ToLower();
            string downloadImages = ConfigurationSettings.AppSettings["DownloadImages"].ToLower();
            string resizeImages = ConfigurationSettings.AppSettings["ResizeImages"].ToLower();
            string makeVideo = ConfigurationSettings.AppSettings["MakeVideo"].ToLower();
            string timestampVideo = ConfigurationSettings.AppSettings["TimestampVideo"].ToLower();
            string watermarkVideo = ConfigurationSettings.AppSettings["WatermarkVideo"].ToLower();
            string compressVideo = ConfigurationSettings.AppSettings["CompressVideo"].ToLower();
            string concatVideos = ConfigurationSettings.AppSettings["ConcatVideos"].ToLower();

            Evercam evercam = new Evercam(ApiId, ApiKey);
            Camera camera = evercam.GetCamera(CameraId);
            DateTime userFrom = new DateTime(fromDay.Year, fromDay.Month, fromDay.Day, fromHour, fromMin, fromSec);
            DateTime userTo = new DateTime(toDay.Year, toDay.Month, toDay.Day, toHour, toMin, toSec);

            if (reindexImages == "true")
            {
                string s = DateTime.UtcNow.ToString();
                int count = Tasks.ReindexImages(imagesDir, startIndex);
                //BLL.Common.Utils.SendMail("Timelapse Images (" + CameraId + ":" + timelapseId + ")", "Reindexed: " + count + Environment.NewLine + "Started: " + s + Environment.NewLine + "Finished: " + DateTime.UtcNow, BLL.Common.Settings.DebugEmail);
            }

            if (moveImages == "true")
            {
                string s = DateTime.UtcNow.ToString();
                int count = Tasks.MoveImages(moveDir, toDir, moveIndex);
                //BLL.Common.Utils.SendMail("Timelapse Images (" + CameraId + ":" + timelapseId + ")", "Moved: " + count + Environment.NewLine + "Started: " + s + Environment.NewLine + "Finished: " + DateTime.UtcNow, BLL.Common.Settings.DebugEmail);
            }

            if (concatVideos == "true")
            {
                Tasks.ConcatVideos(concatFileA, concatFileB, videoFile);
            }

            if (downloadImages == "true" && !string.IsNullOrEmpty(imagesDir))
            {
                if (intervalMin > 0)
                {
                    if (timelapseId > 0)
                    {
                        Tasks.DownloadTimelapseImages(
                            evercam,
                            UserId,
                            camera.ID,
                            Utility.ToWindowsTimezone(camera.Timezone),
                            userFrom,
                            userTo,
                            startIndex,
                            imagesDir,
                            intervalMin);
                    }
                    else
                    {
                        Tasks.DownloadImagesAtInterval(
                            evercam,
                            UserId,
                            camera,
                            fromDay,
                            toDay,
                            fromHour,
                            toHour,
                            intervalMin,
                            startIndex,
                            timestampVideo,
                            imagesDir);
                    }
                }
                else
                {
                    Tasks.DownloadAllImages(
                        evercam,
                        UserId,
                        camera.ID,
                        Utility.ToWindowsTimezone(camera.Timezone),
                        userFrom,
                        userTo,
                        startIndex,
                        timestampVideo,
                        imagesDir);
                }
            }

            if (resizeImages == "true" && !string.IsNullOrEmpty(resizedDir))
            {
                Tasks.ResizeImages(imagesDir, resizedDir, x, y, w, h);
            }

            if (makeVideo == "true" && !string.IsNullOrEmpty(videoDir))
            {
                Tasks.CreateVideoFromImages(imagesDir, fps, bitRate, scale, videoDir + "base-" + videoFile);
            }

            if (watermarkVideo == "true" && !string.IsNullOrEmpty(watermarkFile))
            {
                Tasks.WatermarkVideo(videoDir + "base-" + videoFile, watermarkFile, watermarkPostion, videoDir + videoFile);
            }

            if (compressVideo == "true" && !string.IsNullOrEmpty(videoDir))
            {
                Tasks.CompressVideo(videoDir + videoFile, videoDir + "compressed-" + videoFile, bitRate, scale);
            }

            Console.WriteLine("Press any key to exit...");
            Console.ReadLine();
        }
Пример #13
0
        static void Main(string[] args)
        {
            //Utils.UpdateTimelapsesOnAzure();
            //Utils.CopyTimelapsesToAzure();

            AppDomain.CurrentDomain.UnhandledException += CurrentDomainUnhandledException;
            int tId = Convert.ToInt32(args[0]);

            // testing any timelapse
            //int tId = 398;

            Evercam.SANDBOX = Settings.EvercamSandboxMode;
            Evercam = new Evercam(Settings.EvercamClientID, Settings.EvercamClientSecret, Settings.EvercamClientUri);
            Timelapse timelapse = new Timelapse();
            try
            {
                tl = timelapse = TimelapseDao.Get(tId);
                string cleanCameraId = BLL.Common.Utils.RemoveSymbols(timelapse.CameraId);

                if (timelapse.ID == 0)
                {
                    TimelapseDao.UpdateStatus(timelapse.Code, TimelapseStatus.NotFound, "Timelapse details not found", timelapse.TimeZone);
                    ExitProcess("Timelapse not found. ID = " + tId);
                }
                if (!timelapse.IsRecording)
                {
                    TimelapseDao.UpdateStatus(timelapse.Code, TimelapseStatus.Stopped, "Recording stopped", timelapse.TimeZone);
                    ExitProcess("Timelapse stopped. ID = " + tId);
                }
                if (string.IsNullOrEmpty(cleanCameraId))
                {
                    TimelapseDao.UpdateStatus(timelapse.Code, TimelapseStatus.NotFound, "Camera details could not be retreived from Evercam", timelapse.TimeZone);
                    ExitProcess("Invalid Camera ID. Timelapse ID = " + tId + ", Camera ID = " + timelapse.CameraId);
                }

                //// User AuthToken is Unauthorized to access certain cameras, e.g. wayra_office
                //// may be shared cameras ?
                if (!string.IsNullOrEmpty(timelapse.OauthToken))
                    Evercam = new Evercam(timelapse.OauthToken);

                for (int i = 1; i <= TRY_COUNT; i++)
                {
                    //// tests x times if camera is available instantly otherwise exits
                    try
                    {
                        var data = Evercam.GetLiveImage(timelapse.CameraId);
                        break;
                    }
                    catch(Exception x) {
                        Utils.TimelapseLog(timelapse, "Main Error (try#" + i + "): " + x.ToString());
                        if (i < TRY_COUNT)
                            Thread.Sleep(RETRY_INTERVAL * 1000);    // 7 seconds
                        else
                        {
                            Snapshot snap = Evercam.GetLatestSnapshot(timelapse.CameraId, true);
                            byte[] data = snap.ToBytes();
                            if (data != null && data.Length > 0)
                                break;
                            else
                            {
                                BLL.Common.Utils.AppLog("Main Error in Timelapse#" + tId + ". Camera recording not found.");
                                TimelapseDao.UpdateStatus(timelapse.Code, TimelapseStatus.Failed, "Camera not accessible", timelapse.TimeZone);
                                ExitProcess("Camera not accessible");
                            }
                        }
                    }
                }

                Camera = Evercam.GetCamera(timelapse.CameraId);

                if (Camera == null || string.IsNullOrEmpty(Camera.ID))
                {
                    TimelapseDao.UpdateStatus(timelapse.Code, TimelapseStatus.NotFound, "Camera details could not be retreived from Evercam", timelapse.TimeZone);
                    ExitProcess("Camera not found. ID = " + timelapse.CameraId);
                }
                if (!Camera.IsOnline)
                {
                    TimelapseDao.UpdateStatus(timelapse.Code, TimelapseStatus.Failed, "Camera went offline", timelapse.TimeZone);
                    ExitProcess("Camera is offline. ID = " + timelapse.CameraId);
                }

                Console.Title = "Timelapse (#" + tId + ") - Camera (#" + cleanCameraId + ")";
                Console.WriteLine("Running Timelapse (#" + tId + ") - Camera (#" + cleanCameraId + ")");

                UpPath = Path.Combine(FilePath, cleanCameraId, timelapse.ID.ToString());
                DownPath = Path.Combine(FilePath, cleanCameraId, timelapse.ID.ToString(), "images");
                TempPath = Path.Combine(FilePath, cleanCameraId, timelapse.ID.ToString(), "temp");

                if (!Directory.Exists(FfmpegCopyPath))
                    Directory.CreateDirectory(FfmpegCopyPath);
                if (!Directory.Exists(FilePath))
                    Directory.CreateDirectory(FilePath);
                if (!Directory.Exists(UpPath))
                    Directory.CreateDirectory(UpPath);
                if (!Directory.Exists(DownPath))
                    Directory.CreateDirectory(DownPath);
                if (!Directory.Exists(TempPath))
                    Directory.CreateDirectory(TempPath);

                Recorder recorder = new Recorder(timelapse);
                recorder.Start();
            }
            catch (Exception x)
            {
                if (x.Message.ToLower().Contains("not found"))
                    TimelapseDao.UpdateStatus(timelapse.Code, TimelapseStatus.NotFound, "Camera details could not be retreived from Evercam", timelapse.TimeZone);
                else if (x.Message.ToLower().Contains("not exist"))
                    TimelapseDao.UpdateStatus(timelapse.Code, TimelapseStatus.NotFound, "Camera details could not be retreived from Evercam", timelapse.TimeZone);
                else
                    TimelapseDao.UpdateStatus(timelapse.Code, TimelapseStatus.Failed, "Camera not accessible", timelapse.TimeZone);

                BLL.Common.Utils.AppLog("Main Error in Timelapse#" + tId + ". ERR: " + x.Message);
                ExitProcess(x.Message);
            }
        }
Пример #14
0
        public static int DownloadTimelapseImages(Evercam evercam, string user, string camera, string timezone, DateTime userFromDate, DateTime userToDate, int startIndex, string path, int minutes)
        {
            List<Snapshot> snaps = new List<Snapshot>();
            byte[] data = null;
            int index = startIndex;
            DateTime newFromDate = userFromDate;
            DateTime newToDate = userToDate;

            while (newFromDate <= userToDate)
            {
                newToDate = newFromDate.AddMinutes(minutes);
                long fromTimestamp = Utility.ToUnixTimestamp(newFromDate);
                long toTimestamp = Utility.ToUnixTimestamp(newToDate);

                try
                {
                    snaps = evercam.GetSnapshots(camera, fromTimestamp, toTimestamp, 1, null);
                    if (snaps.Count > 0)
                    {
                        Snapshot snap = evercam.GetSnapshot(camera, snaps[0].CreatedAt.ToString(), "Evercam Proxy", true, 0);
                        if (snap != null)
                        {
                            data = snap.ToBytes();

                            DateTime datetime = Utility.ToWindowsDateTime(snap.CreatedAt);
                            DateTime snaptime = Utils.ConvertFromUtc(datetime, timezone);
                            Console.WriteLine(index + " : " + snap.CreatedAt + " = " + snaptime);

                            try
                            {
                                if (SaveFile(path + index + ".jpg", data))
                                    index++;
                            }
                            catch (Exception x)
                            {
                                Console.WriteLine(" - ERR1 :" + x.Message);
                            }
                        }
                    }
                }
                catch (Exception x) { }

                newFromDate = newToDate;
            }
            return index;
        }
Пример #15
0
        private void StartTimelapser(Timelapse timelapse)
        {
            try
            {
                // tests if camera details are available from Evercam before starting its recorder
                Evercam.SANDBOX = Settings.EvercamSandboxMode;
                Evercam evercam = new Evercam(Settings.EvercamClientID, Settings.EvercamClientSecret, Settings.EvercamClientUri);
                if (!string.IsNullOrEmpty(timelapse.OauthToken))
                    evercam = new Evercam(timelapse.OauthToken);

                Camera camera = evercam.GetCamera(timelapse.CameraId);

                // if camera found then start its process
                if (camera.IsOnline)
                {
                    ProcessStartInfo process = new ProcessStartInfo(TimelapserExePath, timelapse.ID.ToString());
                    process.UseShellExecute = true;
                    process.WindowStyle = ProcessWindowStyle.Hidden;    //ProcessWindowStyle.Normal;

                    Process currentProcess = Process.Start(process);

                    //currentProcess.PriorityClass = ProcessPriorityClass.Idle;
                    //currentProcess.Refresh();

                    TimelapseProcessInfo tpi = new TimelapseProcessInfo();
                    tpi.ProcessId = currentProcess.Id;
                    tpi.IsResponding = true;
                    tpi.NextRun = Utils.SQLMinDate;
                    tpi.Interval = timelapse.SnapsInterval;

                    if (_timelapseInfos.ContainsKey(timelapse.ID))
                        _timelapseInfos[timelapse.ID] = tpi;
                    else
                        _timelapseInfos.Add(timelapse.ID, tpi);
                }
                else
                {
                    TimelapseDao.UpdateStatus(timelapse.Code, TimelapseStatus.Failed, "Camera not accessible", timelapse.TimeZone);
                    Utils.FileLog("Executor.StartTimelapser(" + timelapse.ID + ") Camera (" + camera.ID + ") is Offline at Evercam (" + timelapse.Title + ")");
                }
            }
            catch (Exception x)
            {
                if (x.Message.ToLower().Contains("not found"))
                {
                    TimelapseDao.UpdateStatus(timelapse.Code, TimelapseStatus.NotFound, "Camera details Could not be retrieved from Evercam", timelapse.TimeZone);
                    Utils.FileLog("Executor.StartTimelapser(" + timelapse.ID + ") Error: Could not get camera (" + timelapse.CameraId
                        + ") details from Evercam (" + timelapse.Title + ")");
                }
                else if (x.Message.ToLower().Contains("not exist"))
                {
                    TimelapseDao.UpdateStatus(timelapse.Code, TimelapseStatus.NotFound, "Camera details Could not be retrieved from Evercam", timelapse.TimeZone);
                    Utils.FileLog("Executor.StartTimelapser(" + timelapse.ID + ") Error: Camera (" + timelapse.CameraId
                        + ") does not exist at Evercam (" + timelapse.Title + ")");
                }
                else
                {
                    TimelapseDao.UpdateStatus(timelapse.Code, TimelapseStatus.Failed, "Camera not accessible", timelapse.TimeZone);
                    Utils.FileLog("Executor.StartTimelapser(" + timelapse.ID + ") (" + timelapse.Title + ") Error: " + x.Message);
                }
            }
        }
Пример #16
0
        protected void CreateMovie()
        {
            Console.WriteLine(DateTime.UtcNow + " Check pending archive.");
            _tries = 0;
            //Handle exception if failed to get pending id
            Archive archive = _evercam.GetPendingArchive();
            if (archive == null || string.IsNullOrEmpty(archive.ID))
            {
                return;
            }
            Camera cam = new Camera();
            try
            {
                string[] cred = getUserCreditional(archive.CameraId);
                _evercam = new Evercam(cred[0], cred[1]);
                //added condition to check movie and camera object must not empty
                cam = _evercam.GetCamera(archive.CameraId);
            }
            catch (Exception) {
                updateArchive(_evercam, archive.CameraId, archive.ID, 0, ArchiveStatus.Failed);
                _logger("Camera not found." + archive.CameraId);
            }
            if (cam == null || string.IsNullOrEmpty(cam.ID))
            {
                return;
            }
            Isbusy = true;
            var tz = Utility.ToWindowsTimezone(cam.Timezone);
            //update movie status when we sure application completed after few necessory steps.
            updateArchive(_evercam, archive.CameraId, archive.ID, 0, ArchiveStatus.Processing);

            string archivePath = Path.Combine(Settings.BucketUrl, Settings.BucketName, cam.ID, "archives");
            if (!Directory.Exists(archivePath))
                Directory.CreateDirectory(archivePath);

            string images_directory = Path.Combine(archivePath, "images");
            if (!Directory.Exists(images_directory))
                Directory.CreateDirectory(images_directory);

            _logger("Started downloading to " + archivePath);

            try
            {
                DateTime fromDate = Utility.ToWindowsDateTime(archive.FromDate);
                fromDate = ConvertFromUtc(fromDate, Utility.ToWindowsTimezone(cam.Timezone));
                DateTime toDate = Utility.ToWindowsDateTime(archive.ToDate);
                toDate = ConvertFromUtc(toDate, Utility.ToWindowsTimezone(cam.Timezone));
                int total_frames = DownloadAllImages(_evercam, cam, fromDate, toDate, images_directory);
                DirectoryInfo imagesDirectory = new DirectoryInfo(images_directory);
                if (imagesDirectory.GetFiles("*.jpg").Length == 0)
                {
                    updateArchive(_evercam, archive.CameraId, archive.ID, total_frames, ArchiveStatus.Failed);
                    _logger("Camera: " + cam.ID + ", There is no image between given time period for movie ." + archive.ID);
                }
                else
                {
                    string mp4FileName = Path.Combine(archivePath, archive.ID + ".mp4");
                    string webmFileName = Path.Combine(archivePath, archive.ID + ".webm");

                    CreateVideoFile(mp4FileName, images_directory);
                    //CreateVideoFile(webmFileName, images_directory);

                    Console.WriteLine("Camera: " + cam.ID + ", " + DateTime.UtcNow + ": Completed video processing.");
                    updateArchive(_evercam, archive.CameraId, archive.ID, total_frames, ArchiveStatus.completed);
                }
            }
            catch (Exception ex)
            {
                updateArchive(_evercam, archive.CameraId, archive.ID, 0, ArchiveStatus.Failed);
                Console.WriteLine("Camera: " + cam.ID + ", Error:" + ex.Message);
            }
            Clean(images_directory);
            if (Isbusy)
            {
                //KillFfMpeg();
                Isbusy = false;
            }
        }
Пример #17
0
        public void Execute()
        {
            Evercam Evercam = new Evercam(Settings.EvercamClientID, Settings.EvercamClientSecret, Settings.EvercamClientUri);

            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
            _timelapseInfos = new Dictionary<int, TimelapseProcessInfo>();

            // cleaning, if there is any previous garbage
            Shutdown("all");

            Utils.FileLog("Service execution started...");

            while (isServiceRunning)
            {
                List<Timelapse> timelapses; //= new List<Timelapse>();
                try
                {
                    timelapses = TimelapseDao.GetList(null, null);

                    //// for testing purpose only
                    //timelapses = new List<Timelapse>();
                    //timelapses.Add(TimelapseDao.Get(220));
                    //Utils.FileLog("TESTING Timelapse Service..." + Environment.NewLine);
                }
                catch(Exception x)
                {
                    Utils.FileLog("Error fetching timelapses:" + x.Message);
                    Thread.Sleep(1000 * 10);        // 10 seconds
                    continue;
                }

                if (timelapses == null)
                {
                    Utils.FileLog("Timelapses could not be fetched !");
                    Thread.Sleep(1000 * 15);        // 15 seconds
                    continue;
                }

                if (timelapses.Count == 0)
                {
                    Utils.FileLog("No timelapse found !");
                    Thread.Sleep(1000 * 15);        // 15 seconds
                    continue;
                }

                string hello = "Found " + timelapses.Count + " timelapses";
                Console.WriteLine(hello);
                Utils.FileLog(hello);

                foreach (Timelapse timelapse in timelapses)
                {
                    //// skipping other timelapses for testing this one
                    //if (timelapse.ID != 430)
                    //    continue;
                    try
                    {
                        if (timelapse.Status == (int)TimelapseStatus.NotFound)
                        {
                            continue;
                        }

                        if (string.IsNullOrEmpty((TimelapserExePath = CopyTimelapser(timelapse.ID))))
                        {
                            Utils.FileLog("Skipping timelapse... unable to create copy of Timelapser.exe");
                            continue;
                        }

                        int pid = Utils.TimelapseRunning(timelapse.ID);

                        if (pid == 0 && Utils.StartTimelapse(timelapse)) {
                            StartTimelapser(timelapse);
                            TimelapseDao.UpdateStatus(timelapse.Code, (TimelapseStatus)timelapse.Status, timelapse.StatusTag, timelapse.TimeZone);
                        }
                        else if (pid > 0 && Utils.StopTimelapse(timelapse))
                        {
                            Utils.KillProcess(pid, timelapse.ID);
                            TimelapseDao.UpdateStatus(timelapse.Code, (TimelapseStatus)timelapse.Status, timelapse.StatusTag, timelapse.TimeZone);
                        }
                        else if (pid < 0)   // halted process id
                        {
                            Utils.FileLog("Kill: Timelapse#" + timelapse.ID);
                            Utils.KillProcess(pid * -1, timelapse.ID);
                        }
                    }
                    catch (Exception x)
                    {
                        Utils.FileLog("Executor.CheckRequests Error (" + timelapse.ID + "): " + x.Message);
                    }
                }

                Thread.Sleep(1000 * 60 * Settings.RecheckInterval);     // RecheckInterval in minutes

                CheckStartDeletion();
            }
        }
Пример #18
0
        static void Main(string[] args)
        {
            //Utils.UpdateTimelapsesOnAzure();
            //Utils.CopyTimelapsesToAzure();

            AppDomain.CurrentDomain.UnhandledException += CurrentDomainUnhandledException;
            int tId = Convert.ToInt32(args[0]);

            Evercam.SANDBOX = Settings.EvercamSandboxMode;
            Evercam = new Evercam(Settings.EvercamClientID, Settings.EvercamClientSecret, Settings.EvercamClientUri);
            Timelapse timelapse = new Timelapse();
            try
            {
                tl = timelapse = TimelapseDao.Get(tId);
                string cleanCameraId = BLL.Common.Utils.RemoveSymbols(timelapse.CameraId);
                if (timelapse.ID == 0)
                {
                    TimelapseDao.UpdateStatus(timelapse.Code, TimelapseStatus.NotFound, "Timelapse details not found", timelapse.TimeZone);
                    ExitProcess("Timelapse not found. ID = " + tId);
                }
                if (!timelapse.IsRecording)
                {
                    TimelapseDao.UpdateStatus(timelapse.Code, TimelapseStatus.Stopped, "Recording stopped", timelapse.TimeZone);
                    ExitProcess("Timelapse stopped. ID = " + tId);
                }
                if (string.IsNullOrEmpty(cleanCameraId))
                {
                    TimelapseDao.UpdateStatus(timelapse.Code, TimelapseStatus.NotFound, "Camera details could not be retreived from Evercam", timelapse.TimeZone);
                    ExitProcess("Invalid Camera ID. Timelapse ID = " + tId + ", Camera ID = " + timelapse.CameraId);
                }

                //// User AuthToken is Unauthorized to access certain cameras, e.g. wayra_office
                //// may be shared cameras ?
                if (!string.IsNullOrEmpty(timelapse.OauthToken))
                {
                    string[] cred = timelapse.OauthToken.Split(':');
                    if (cred.Length >= 2)
                        Evercam = new Evercam(cred[0], cred[1]);
                    else
                        Evercam = new Evercam(timelapse.OauthToken);
                }

                for (int i = 1; i <= TRY_COUNT; i++)
                {
                    //// tests x times if camera is available instantly otherwise exits
                    try
                    {
                        var data = Evercam.GetLiveImage(timelapse.CameraId);
                        break;
                    }
                    catch(Exception x) {
                        Utils.TimelapseLog(timelapse, "Main Error (try#" + i + "): " + x.ToString());
                        if (i < TRY_COUNT)
                            Thread.Sleep(RETRY_INTERVAL * 1000);    // 7 seconds
                        else
                        {
                            byte[] data = Evercam.GetThumbnail(timelapse.CameraId, true);

                            if (data != null && data.Length > 0)
                                break;
                            else
                            {
                                BLL.Common.Utils.AppLog("Main Error in Timelapse#" + tId + ". Camera recording not found.");
                                TimelapseDao.UpdateStatus(timelapse.Code, TimelapseStatus.Failed, "Camera not accessible", timelapse.TimeZone);
                                ExitProcess("Camera not accessible");
                            }
                        }
                    }
                }
                FilePath = timelapse.TimelapsePath + Settings.BucketName;
                UpPath = Path.Combine(FilePath, cleanCameraId, timelapse.ID.ToString());
                DownPath = Path.Combine(FilePath, cleanCameraId, timelapse.ID.ToString(), "images");
                TsPath = Path.Combine(FilePath, cleanCameraId, timelapse.ID.ToString(), "ts");
                TempPath = Path.Combine(FilePath, cleanCameraId, timelapse.ID.ToString(), "temp");
                string hlsFileUrl = "http://timelapse.evercam.io/timelapses/" + cleanCameraId + "/" + timelapse.ID.ToString();

                if (!Directory.Exists(FilePath))
                    Directory.CreateDirectory(FilePath);
                if (!Directory.Exists(UpPath))
                    Directory.CreateDirectory(UpPath);
                if (!Directory.Exists(DownPath))
                    Directory.CreateDirectory(DownPath);
                if (!Directory.Exists(TsPath))
                    Directory.CreateDirectory(TsPath);
                if (!Directory.Exists(TempPath))
                    Directory.CreateDirectory(TempPath);
                //if (!File.Exists(Path.Combine(UpPath, "timelapse.m3u8")))
                CreateManifestFile(UpPath);
                CreateManifestFileForDownload(UpPath, hlsFileUrl);
                CreateBashFile(timelapse.FPS, DownPath, TsPath, chunkSize, timelapse.SnapsInterval);

                Recorder recorder = new Recorder(timelapse);
                string bashFile = Path.Combine(Program.UpPath, "build.sh");

                if (timelapse.RecreateHls)
                {
                    string old_ts_path = Path.Combine(FilePath, cleanCameraId, timelapse.ID.ToString(), "ts_old");
                    Directory.Move(TsPath, old_ts_path);
                    if (!Directory.Exists(TsPath))
                        Directory.CreateDirectory(TsPath);
                    recorder.CreateVideoChunks(bashFile);
                    TimelapseDao.UpdateReCreateHlsParams(timelapse.Code, false, false);
                    Directory.Delete(old_ts_path, true);
                    Utils.TimelapseLog(timelapse, "Program <<< Recreate HLS stream");
                }

                DirectoryInfo imagesDirectory = new DirectoryInfo(Program.DownPath);
                int imagesCount = imagesDirectory.GetFiles("*.jpg").Length;
                DirectoryInfo ts = new DirectoryInfo(TsPath);
                int hasTsFiles = ts.GetFiles("*.*").Length;
                if (imagesCount > timelapse.SnapsCount && (imagesCount - timelapse.SnapsCount) > 1000)
                {
                    ExitProcess("Something went wrong with timelapse: " + timelapse.ID + ", imagesCount: " + imagesCount + ", SnapsCount: " + timelapse.SnapsCount);
                }
                if (hasTsFiles == 0 && imagesCount > 24)
                {
                    recorder.CreateVideoChunks(bashFile);
                    Utils.TimelapseLog(timelapse, "Program <<< CreateVideoChunks");
                }

                Camera = Evercam.GetCamera(timelapse.CameraId);

                if (Camera == null || string.IsNullOrEmpty(Camera.ID))
                {
                    TimelapseDao.UpdateStatus(timelapse.Code, TimelapseStatus.NotFound, "Camera details could not be retreived from Evercam", timelapse.TimeZone);
                    ExitProcess("Camera not found. ID = " + timelapse.CameraId);
                }
                if (!Camera.IsOnline)
                {
                    TimelapseDao.UpdateStatus(timelapse.Code, TimelapseStatus.Failed, "Camera went offline", timelapse.TimeZone);
                    ExitProcess("Camera is offline. ID = " + timelapse.CameraId);
                }

                Console.Title = "Timelapse (#" + tId + ") - Camera (#" + cleanCameraId + ")";
                Console.WriteLine("Running Timelapse (#" + tId + ") - Camera (#" + cleanCameraId + ")");

                recorder.Start();
            }
            catch (Exception x)
            {
                if (x.Message.ToLower().Contains("not found"))
                    TimelapseDao.UpdateStatus(timelapse.Code, TimelapseStatus.NotFound, "Camera details could not be retreived from Evercam", timelapse.TimeZone);
                else if (x.Message.ToLower().Contains("not exist"))
                    TimelapseDao.UpdateStatus(timelapse.Code, TimelapseStatus.NotFound, "Camera details could not be retreived from Evercam", timelapse.TimeZone);
                else
                    TimelapseDao.UpdateStatus(timelapse.Code, TimelapseStatus.Failed, "Camera not accessible", timelapse.TimeZone);

                BLL.Common.Utils.AppLog("Main Error in Timelapse#" + tId + ". ERR: " + x.Message);
                ExitProcess(x.Message);
            }
        }