Esempio n. 1
0
        public static SnapmailInfoModel ToInfoModel(SnapmailRowData data)
        {
            return new SnapmailInfoModel()
            {
                key = data.RowKey,
                user_id = data.UserId,

                cameras = data.Cameras,
                camera_names = data.CameraNames,
                recipients = data.Recipients,
                notify_days = data.NotifyDays,
                notify_time = data.NotifyTime,
                timezone = data.TimeZone,
                last_sent = data.LastSent != null ? data.LastSent.ToString() : DateTime.MinValue.ToString(),
                sent_mail = data.SentMail,
                is_active = data.IsActive,
                is_scheduled = data.IsScheduled,
                timestamp = data.Timestamp.ToString(),
                access_token = data.AccessToken
            };
        }
Esempio n. 2
0
        public static SnapmailRowData Update2(string key, SnapmailRowData snapmail)
        {
            string query = @"UPDATE [dbo].[Snapmails] " +
                           "SET [UserId]=@UserId,[UserName]=@UserName,[Cameras]=@Cameras,[CameraNames]=@CameraNames,[Recipients]=@Recipients,[NotifyDays]=@NotifyDays,[NotifyTime]=@NotifyTime,[TimeZone]=@TimeZone,[AccessToken]=@AccessToken) " +
                           "WHERE (RowKey = '" + key + "')";
            try
            {
                var p1 = new SqlParameter("@UserId", (string.IsNullOrEmpty(snapmail.UserId)) ? (object)DBNull.Value : snapmail.UserId);
                var p2 = new SqlParameter("@UserName", (string.IsNullOrEmpty(snapmail.UserName)) ? (object)DBNull.Value : snapmail.UserName);
                var p3 = new SqlParameter("@Cameras", (string.IsNullOrEmpty(snapmail.Cameras)) ? (object)DBNull.Value : snapmail.Cameras);
                var p4 = new SqlParameter("@CameraNames", (string.IsNullOrEmpty(snapmail.CameraNames)) ? (object)DBNull.Value : snapmail.CameraNames);
                var p5 = new SqlParameter("@Recipients", (string.IsNullOrEmpty(snapmail.Recipients)) ? (object)DBNull.Value : snapmail.Recipients);
                var p6 = new SqlParameter("@NotifyDays", (string.IsNullOrEmpty(snapmail.NotifyDays)) ? (object)DBNull.Value : snapmail.NotifyDays);
                var p7 = new SqlParameter("@NotifyTime", (string.IsNullOrEmpty(snapmail.NotifyTime)) ? (object)DBNull.Value : snapmail.NotifyTime);
                var p8 = new SqlParameter("@TimeZone", (string.IsNullOrEmpty(snapmail.TimeZone)) ? (object)DBNull.Value : snapmail.TimeZone);
                var p9 = new SqlParameter("@AccessToken", (string.IsNullOrEmpty(snapmail.AccessToken)) ? (object)DBNull.Value : snapmail.AccessToken);

                var list = new[] { p1, p2, p3, p4, p5, p6, p7, p8, p9 };
                var cmd = new SqlCommand { CommandText = query, CommandType = CommandType.Text };
                cmd.Parameters.AddRange(list);
                Connection.OpenConnection();
                cmd.Connection = Connection.DbConnection;
                bool result = (cmd.ExecuteNonQuery() > 0);
                Connection.CloseConnection();
                cmd.Dispose();
                return snapmail;
            }
            catch (Exception ex)
            {
                Utils.FileLog("TimelapseDao Update(Timelapse timelapse) " + ex.Message);
                return new SnapmailRowData();
            }
            finally
            { Connection.CloseConnection(); }
        }
Esempio n. 3
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]);
            }
        }
Esempio n. 4
0
        public static SnapmailRowData Update(string key, SnapmailRowData snapmail)
        {
            try
            {
                CloudTable tblSnapmails = GetAzureTable(SNAPMAIL_TABLE_NAME);
                SnapmailRowData old = Get(key);
                SnapmailRowData mail = new SnapmailRowData()
                {
                    RowKey = key,
                    PartitionKey = snapmail.PartitionKey,
                    ETag = snapmail.ETag,
                    Timestamp = snapmail.Timestamp,
                    Cameras = snapmail.Cameras,
                    CameraNames = snapmail.CameraNames,
                    Message = old.Message,
                    NotifyDays = snapmail.NotifyDays,
                    NotifyTime = snapmail.NotifyTime,
                    TimeZone = snapmail.TimeZone,
                    Recipients = snapmail.Recipients,
                    Subject = old.Subject,
                    UserId = snapmail.UserId,
                    UserName = snapmail.UserName,
                    IsActive = old.IsActive,
                    IsScheduled = old.IsScheduled,
                    AccessToken = snapmail.AccessToken,
                    RefreshToken = snapmail.RefreshToken,
                    TokenExpires = snapmail.TokenExpires,
                    TokenCreated = snapmail.TokenCreated
                };

                TableOperation updateEmail = TableOperation.Replace(mail);
                var result = tblSnapmails.Execute(updateEmail);
                return Get(key);
            }
            catch (Exception x)
            {
                return snapmail;
            }
        }
Esempio n. 5
0
        public static SnapmailRowData Insert2(SnapmailRowData snapmail)
        {
            string query = @"INSERT INTO [dbo].[Snapmails] " +
                           "([RowKey],[UserId],[UserName],[Cameras],[CameraNames],[Subject],[Recipients],[Message],[NotifyDays],[NotifyTime],[TimeZone],[SentMail],[LastSent],[IsActive],[IsScheduled],[AccessToken],[RefreshToken],[TokenExpires],[TokenCreated]) " +
                           "VALUES " +
                           "(@RowKey,@UserId,@UserName,@Cameras,@CameraNames,@Subject,@Recipients,@Message,@NotifyDays,@NotifyTime,@TimeZone,@SentMail,@LastSent,@IsActive,@IsScheduled,@AccessToken,@RefreshToken,@TokenExpires,@TokenCreated) ";
            try
            {
                var p1 = new SqlParameter("@RowKey", snapmail.RowKey);
                var p2 = new SqlParameter("@UserId", (string.IsNullOrEmpty(snapmail.UserId)) ? (object)DBNull.Value : snapmail.UserId);
                var p3 = new SqlParameter("@UserName", (string.IsNullOrEmpty(snapmail.UserName)) ? (object)DBNull.Value : snapmail.UserName);
                var p4 = new SqlParameter("@Cameras", (string.IsNullOrEmpty(snapmail.Cameras)) ? (object)DBNull.Value : snapmail.Cameras);
                var p5 = new SqlParameter("@CameraNames", (string.IsNullOrEmpty(snapmail.CameraNames)) ? (object)DBNull.Value : snapmail.CameraNames);
                var p6 = new SqlParameter("@Subject", (string.IsNullOrEmpty(snapmail.Subject)) ? (object)DBNull.Value : snapmail.Subject);
                var p7 = new SqlParameter("@Recipients", (string.IsNullOrEmpty(snapmail.Recipients)) ? (object)DBNull.Value : snapmail.Recipients);
                var p8 = new SqlParameter("@Message", (string.IsNullOrEmpty(snapmail.Message)) ? (object)DBNull.Value : snapmail.Message);
                var p9 = new SqlParameter("@NotifyDays", (string.IsNullOrEmpty(snapmail.NotifyDays)) ? (object)DBNull.Value : snapmail.NotifyDays);
                var p10 = new SqlParameter("@NotifyTime", (string.IsNullOrEmpty(snapmail.NotifyTime)) ? (object)DBNull.Value : snapmail.NotifyTime);
                var p11 = new SqlParameter("@TimeZone", (string.IsNullOrEmpty(snapmail.TimeZone)) ? (object)DBNull.Value : snapmail.TimeZone);
                var p12 = new SqlParameter("@SentMail", (string.IsNullOrEmpty(snapmail.SentMail)) ? (object)DBNull.Value : snapmail.SentMail);
                var p13 = new SqlParameter("@LastSent", (string.IsNullOrEmpty(snapmail.LastSent)) ? (object)DBNull.Value : snapmail.LastSent);
                var p14 = new SqlParameter("@IsActive", snapmail.IsActive);
                var p15 = new SqlParameter("@IsScheduled", snapmail.IsScheduled);
                var p16 = new SqlParameter("@AccessToken", (string.IsNullOrEmpty(snapmail.AccessToken)) ? (object)DBNull.Value : snapmail.AccessToken);
                var p17 = new SqlParameter("@RefreshToken", (string.IsNullOrEmpty(snapmail.RefreshToken)) ? (object)DBNull.Value : snapmail.RefreshToken);
                var p18 = new SqlParameter("@TokenExpires", (string.IsNullOrEmpty(snapmail.TokenExpires)) ? (object)DBNull.Value : snapmail.TokenExpires);
                var p19 = new SqlParameter("@TokenCreated", (string.IsNullOrEmpty(snapmail.TokenCreated)) ? (object)DBNull.Value : snapmail.TokenCreated);

                var list = new[] { p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, p15, p16, p17, p18, p19 };
                var cmd = new SqlCommand { CommandText = query, CommandType = CommandType.Text };
                cmd.Parameters.AddRange(list);
                Connection.OpenConnection();
                cmd.Connection = Connection.DbConnection;
                cmd.ExecuteNonQuery();
                Connection.CloseConnection();
                cmd.Dispose();
                return snapmail;
            }
            catch (Exception ex)
            {
                Utils.FileLog("SnapmailDao Insert(SnapmailRowData snapmail) " + ex.Message);
                return new SnapmailRowData();
            }
            finally
            { Connection.CloseConnection(); }
        }
Esempio n. 6
0
 public static SnapmailRowData Insert(SnapmailRowData snapmail)
 {
     try
     {
         CloudTable tblSnapmails = GetAzureTable(SNAPMAIL_TABLE_NAME);
         TableOperation insertEmail = TableOperation.Insert(snapmail);
         tblSnapmails.Execute(insertEmail);
         return Get(snapmail.RowKey);
     }
     catch (Exception x)
     {
         return snapmail;
     }
 }
Esempio n. 7
0
        private int StartSnapmailer(SnapmailRowData snapmail)
        {
            try
            {
                int pid = ProcessRunning(snapmail);
                if (snapmail.IsActive && !snapmail.IsScheduled)
                {
                    ProcessStartInfo process = new ProcessStartInfo(SnapmailExePath, snapmail.RowKey);
                    process.UseShellExecute = false;
                    process.WindowStyle = ProcessWindowStyle.Normal;

                    Process currentProcess = Process.Start(process);

                    Utils.FileLog("Executor.StartSnapmailer(" + snapmail.RowKey + ")");

                    return currentProcess.Id;
                }
                else if (snapmail.IsActive && snapmail.IsScheduled)
                {
                    if (pid == 0)
                    {
                        ProcessStartInfo process = new ProcessStartInfo(SnapmailExePath, snapmail.RowKey);
                        process.UseShellExecute = false;
                        process.WindowStyle = ProcessWindowStyle.Normal;

                        Process currentProcess = Process.Start(process);

                        Utils.FileLog("Executor.StartSnapmailer(" + snapmail.RowKey + ") - re");

                        return currentProcess.Id;
                    }
                }
                else if (!snapmail.IsActive && snapmail.IsScheduled)
                {
                    if (pid > 0)
                        KillProcess(pid, snapmail.RowKey);
                        //SnapmailDao.UpdateScheduled(snapmail.RowKey, false);
                }
                else if (!snapmail.IsActive && !snapmail.IsScheduled)
                {
                    if (pid > 0)
                        KillProcess(pid, snapmail.RowKey);
                }
            }
            catch (Exception x)
            {
                Utils.FileLog("Executor.StartSnapmailer(" + snapmail.RowKey + ") Error: " + x.Message);
            }
            return 0;
        }
Esempio n. 8
0
 private int ProcessRunning(SnapmailRowData snapmail)
 {
     try
     {
         int id = 0;
             Process[] processlist = Process.GetProcesses();
             foreach (Process process in processlist)
         {
             if (process.ProcessName.ToLower().StartsWith("snapmailer_"))
             {
                 string _id = process.ProcessName.Substring(
                     process.ProcessName.IndexOf("_") + 1,
                     process.ProcessName.Length - (process.ProcessName.IndexOf("_") + 1));
                 if (_id == Utils.CleanFileName(snapmail.RowKey))
                 {
                     if (process.Responding)
                     {
                         id = process.Id;
                         break;
                     }
                     else
                     {
                         id = 0;
                         KillProcess(process.Id, snapmail.RowKey);
                         break;
                     }
                 }
             }
         }
         return id;
     }
     catch (Exception x)
     {
         Console.WriteLine("ProcessRunning: " + snapmail.RowKey);
         return 0;
     }
 }