Ejemplo n.º 1
0
 internal static bool RemoveRecipient(string smtpAddress, EcsConfiguration configuration, string senderAddress, string id,
     string server, string port, out string error)
 {
     const string SOURCE = CLASS_NAME + "RemoveRecipient";
     try
     {
         var post = AssembleLoginParams(smtpAddress, configuration.Password) +
             string.Format("{0}&parms={1} {2}",
             "REMOVE%20RECIPIENT",
             senderAddress,
             id);
         byte[] postData = Encoding.UTF8.GetBytes(post);
         if (string.IsNullOrEmpty(server)) server = configuration.Server;
         if (string.IsNullOrEmpty(port)) port = configuration.Port;
         HttpWebRequest request = CreateRequest(server, port, postData);
         if (request == null)
         {
             Logger.Error(SOURCE, "failed to create HttpWebRequest object");
             error = "Internal error";
             return false;
         }
         var response = request.GetResponse() as HttpWebResponse;
         if (!request.HaveResponse)
         {
             Logger.Error(SOURCE, "server did not respond");
             request.Abort();
             error = "Internal error";
             return false;
         }
         if (response == null)
         {
             Logger.Error(SOURCE, "response is null");
             request.Abort();
             error = "Internal error";
             return false;
         }
         var stream = response.GetResponseStream();
         if (stream == null)
         {
             Logger.Error(SOURCE, "ResponseStream == null");
             request.Abort();
             error = "Internal error";
             return false;
         }
         var reader = new StreamReader(stream);
         string responseText = reader.ReadToEnd();
         error = ParseRemoveRecipResponse(responseText);
         return string.IsNullOrEmpty(error);
     }
     catch (Exception ex)
     {
         Logger.Error(SOURCE, ex.ToString());
         error = "Internal error";
         return false;
     }
 }
Ejemplo n.º 2
0
 internal static void PostContent(string smtpAddress, EcsConfiguration configuration, string encodedContent,
     string recips, ref BackgroundWorker bw, ref DoWorkEventArgs e,
     ref string pointer, out string error)
 {
     const string SOURCE = CLASS_NAME + "PostContent";
     try
     {
         //1 MB is the max for RECEIVE CONTENT, so split into chunks
         var chunks = SegmentContent(encodedContent);
         AppConstants.TotalChunks = chunks.Count;
         AppConstants.TotalSize = encodedContent.Length;
         //assemble the post
         var post = AssembleLoginParams(smtpAddress, configuration.Password) +
             string.Format("{0}&parms={1}%20{2}",
             "RECEIVE%20CONTENT", HttpUtility.UrlEncode(recips), HttpUtility.UrlEncode(chunks[0]));
         var postData = Encoding.UTF8.GetBytes(post);
         var request = CreateRequestAsync(configuration.Server, configuration.Port, postData,
             ref bw, ref e);
         if (request == null && !e.Cancel && !bw.CancellationPending)
         {
             Logger.Error(SOURCE, "failed to create WebRequest");
             error = "Internal error";
             return;
         }
         GetResponseAsync(request, "ReceiveContent", ref bw, ref e, out pointer, out error);
         AppConstants.UploadedSize = chunks[0].Length;
         if(chunks.Count <= 1 || string.IsNullOrEmpty(pointer)) return;
         for (var j = 1; j < chunks.Count; j++)
         {
             AppConstants.CurrentChunk = j;
             if (e.Cancel || bw.CancellationPending) return;
             Logger.Info(SOURCE, string.Format("sending segment #{0} of {1} segments",
                                              j + 1, chunks.Count));
             ReceiveSegment(smtpAddress, configuration, chunks[j], pointer, ref bw, ref e, out error);
             AppConstants.UploadedSize += chunks[j].Length;
             if (error == "success") continue;
             Logger.Error(SOURCE, string.Format("exiting on error at chunk #{0}: {1}",
                                               j + 1, error));
             break;
         }
         AppConstants.CurrentChunk = AppConstants.TotalChunks;
     }
     catch (Exception ex)
     {
         Logger.Error(SOURCE, ex.ToString());
         error = "Internal error";
     }
 }
Ejemplo n.º 3
0
 internal static void ReceiveSegment(string smtpAddress, EcsConfiguration configuration, string segment,
     string id, out string error)
 {
     const string SOURCE = CLASS_NAME + "ReceiveSegment";
     try
     {
         //assemble the post
         string post = AssembleLoginParams(smtpAddress, configuration.Password) +
             string.Format("{0}&parms={1}%20{2}",
             "RECEIVE%20SEGMENT", id, segment);
         var postData = Encoding.UTF8.GetBytes(post);
         var request = CreateRequest(configuration.Server, configuration.Port, postData);
         if (request == null)
         {
             Logger.Error(SOURCE, "HttpWebRequest is null");
             error = "Internal error";
             return;
         }
         var response = request.GetResponse() as HttpWebResponse;
         if (!request.HaveResponse)
         {
             Logger.Error(SOURCE, "HaveResponse == false");
             request.Abort();
             error = "Internal error";
             return;
         }
         if (response == null)
         {
             Logger.Error(SOURCE, "response == null");
             request.Abort();
             error = "Internal error";
             return;
         }
         var stream = response.GetResponseStream();
         if (stream == null)
         {
             Logger.Error(SOURCE, "ResponseStream == null");
             request.Abort();
             error = "Internal error";
             return;
         }
         var reader = new StreamReader(stream);
         var responseText = reader.ReadToEnd();
         error = ParseSegmentResponse(responseText);
     }
     catch (Exception ex)
     {
         Logger.Error(SOURCE, ex.ToString());
         error = "Internal error";
     }
 }
Ejemplo n.º 4
0
 internal static void DeleteContent(string smtpAddress, EcsConfiguration configuration, 
     string id, out string error, bool deletePointer)
 {
     const string SOURCE = CLASS_NAME + "DeleteContent";
     try
     {
         string post = AssembleLoginParams(smtpAddress, configuration.Password) +
             string.Format("{0}&parms={1}",
             deletePointer ? "DELETE%20CONTENT" : "DELETE%20DATA", id);
         byte[] postData = Encoding.UTF8.GetBytes(post);
         HttpWebRequest request = CreateRequest(configuration.Server, configuration.Port, postData);
         if (request == null)
         {
             Logger.Error(SOURCE, "failed to create HttpWebRequest object");
             error = "Internal error";
             return;
         }
         var response = request.GetResponse() as HttpWebResponse;
         if (!request.HaveResponse)
         {
             Logger.Error(SOURCE, "server did not respond");
             request.Abort();
             error = "Internal error";
             return;
         }
         if (response == null)
         {
             Logger.Error(SOURCE, "response is null");
             request.Abort();
             error = "Internal error";
             return;
         }
         var stream = response.GetResponseStream();
         if (stream == null)
         {
             Logger.Error(SOURCE, "ResponseStream == null");
             request.Abort();
             error = "Internal error";
             return;
         }
         var reader = new StreamReader(stream);
         var responseText = reader.ReadToEnd();
         error = ParseDeleteResponse(responseText);
     }
     catch (Exception ex)
     {
         Logger.Error(SOURCE, ex.ToString());
         error = "Internal error";
     }
 }
Ejemplo n.º 5
0
        internal static void PostContent(string smtpAddress, EcsConfiguration configuration, string encodedContent, 
            string recips, ref string pointer, out string error)
        {
            const string SOURCE = CLASS_NAME + "PostContent";
            try
            {
                //1 MB is the max for RECEIVE CONTENT, so split into chunks
                var chunks = SegmentContent(encodedContent);
                //assemble the post
                var post = AssembleLoginParams(smtpAddress, configuration.Password) +
                    string.Format("{0}&parms={1}%20{2}",
                    "RECEIVE%20CONTENT", HttpUtility.UrlEncode(recips), chunks[0]);
                var postData = Encoding.UTF8.GetBytes(post);

                var request = CreateRequest(configuration.Server, configuration.Port, postData);
                if (request == null)
                {
                    Logger.Error(SOURCE,"HttpWebRequest is null");
                    error = "Internal error";
                    return;
                }
                request.Timeout = 30000;
                var response = request.GetResponse() as HttpWebResponse;
                if (!request.HaveResponse)
                {
                    Logger.Error(SOURCE,"HaveResponse == false");
                    error = "Internal error";
                    request.Abort();
                    return;
                }
                if (response == null)
                {
                    Logger.Error(SOURCE, "response == null");
                    error = "Internal error";
                    request.Abort();
                    return;
                }
                var stream = response.GetResponseStream();
                if (stream == null)
                {
                    Logger.Error(SOURCE, "ResponseStream == null");
                    error = "Internal error";
                    request.Abort();
                    return;
                }
                var reader = new StreamReader(stream);
                var responseText = reader.ReadToEnd();
                ParsePostResponse(responseText, ref pointer, out error);
                if (chunks.Count <= 1 || string.IsNullOrEmpty(pointer)) return;
                for(var j = 1; j< chunks.Count; j++)
                {
                    Logger.Info(SOURCE,string.Format("sending segment #{0} of {1} segments",
                                                     j + 1, chunks.Count));
                    ReceiveSegment(smtpAddress,configuration,chunks[j],pointer,out error);
                    if (error == "success") continue;
                    Logger.Error(SOURCE,string.Format("exiting on error at chunk #{0}: {1}",
                                                      j + 1, error));
                    break;
                }
            }
            catch (Exception ex)
            {
                Logger.Error(SOURCE, ex.ToString());
                error = "Internal error";
            }
        }
Ejemplo n.º 6
0
 internal static string LoadEmbeddedVideos(string content, List<Match> matches,
     Dictionary<string, Attachment> attachList, string baseUrl, Account account,
     EcsConfiguration configuration, string senderAddress,
     string serverName, string serverPort, string encryptKey2, string userAgent)
 {
     //extract the src paths
     foreach (var match in matches)
     {
         //extract the filename from the src
         var filePath = match.Groups[2].Value;
         var fileName = HttpUtility.UrlDecode(filePath.Substring(filePath.LastIndexOf("/")).Replace("/", ""));
         if (string.IsNullOrEmpty(fileName)) continue;
         //find pointer for matching attachment
         var pointer = GetAttachPointer(attachList, fileName);
         if (string.IsNullOrEmpty(pointer)) continue;
         //save to modified 'src' path
         var path = Path.Combine(baseUrl, pointer);
         if (!Directory.Exists(path))
         {
             Directory.CreateDirectory(path);
         }
         path = Path.Combine(path, fileName);
         if (!File.Exists(path))
         {
             //get the content and write it to the path
             GetEmbeddedFile(pointer, path, account, configuration, senderAddress,
                             serverName, serverPort, "", encryptKey2, userAgent);
         }
         //read the bytes, base64 encode
         var data = Convert.ToBase64String(File.ReadAllBytes(path));
         var ext = Path.GetExtension(path);
         if (!string.IsNullOrEmpty(ext))
             ext = ext.Replace(".", "");
         var dataUri = string.Format("data:video/{0};base64,{1}", ext, data);
         //update the src link with the local path
         content = content.Replace(filePath, dataUri);
     }
     return content;
 }
Ejemplo n.º 7
0
 internal static ThisAddIn.RegistrationState CheckRegistered(string smtpAddress, EcsConfiguration configuration, string senderAddresses, out string error)
 {
     const string SOURCE = CLASS_NAME + "CheckRegistered";
     try
     {
         var post = AssembleLoginParams(smtpAddress, configuration.Password) +
             string.Format("{0}&parms={1}",
             "USER%20REGISTERED", senderAddresses);
         var postData = Encoding.UTF8.GetBytes(post);
         var request = CreateRequest(configuration.Server, configuration.Port, postData);
         if (request == null)
         {
             Logger.Error(SOURCE, "failed to create HttpWebRequest object");
             error = "unable to connect";
             return ThisAddIn.RegistrationState.Unknown;
         }
         var response = request.GetResponse() as HttpWebResponse;
         if (!request.HaveResponse)
         {
             Logger.Error(SOURCE, "server did not respond");
             request.Abort();
             error = "no response";
             return ThisAddIn.RegistrationState.Unknown;
         }
         if (response == null)
         {
             Logger.Error(SOURCE, "response is null");
             error = "no response";
             return ThisAddIn.RegistrationState.Unknown;
         }
         var stream = response.GetResponseStream();
         if (stream == null)
         {
             Logger.Error(SOURCE, "response stream is null");
             error = "no response";
             return ThisAddIn.RegistrationState.Unknown;
         }
         var reader = new StreamReader(stream);
         string responseText = reader.ReadToEnd();
         /* -16 SELECT error in user_registered(), e:
         *  -10 Invalid number of parameters
         *  -2 Login not complete
         *  7 User registered =
         */
         if (responseText.StartsWith("7 "))
         {
             var value = responseText.Replace("7 User registered =", "").Replace(",","").Trim();
             bool answer;
             if (bool.TryParse(value, out answer))
             {
                 error = "";
                 return answer
                            ? ThisAddIn.RegistrationState.Registered
                            : ThisAddIn.RegistrationState.NotRegistered;
             }
             error = value;
             return ThisAddIn.RegistrationState.ServerError;
         }
         Logger.Warning(SOURCE, responseText);
         string code;
         EvalResponse(responseText, out code, out error);
         return code == "-1"
             ? ThisAddIn.RegistrationState.BadCredentials
             : ThisAddIn.RegistrationState.ServerError;
     }
     catch (Exception ex)
     {
         Logger.Error(SOURCE, ex.ToString());
         error = "internal error";
         return ThisAddIn.RegistrationState.Unknown;
     }
 }
Ejemplo n.º 8
0
 internal static void UpdateContent(string smtpAddress, EcsConfiguration configuration, string encodedContent,
     string id, ref BackgroundWorker bw, ref DoWorkEventArgs e, out string error)
 {
     const string SOURCE = CLASS_NAME + "UpdateContent";
     try
     {
         //1 MB is the max for RECEIVE CONTENT, so split into chunks
         var chunks = SegmentContent(encodedContent);
         //assemble the post
         var post = AssembleLoginParams(smtpAddress, configuration.Password) +
             string.Format("{0}&parms={1}%20{2}",
             "UPDATE%20CONTENT", id, chunks[0]);
         var postData = Encoding.UTF8.GetBytes(post);
         var request = CreateRequestAsync(configuration.Server, configuration.Port, postData,
             ref bw, ref e);
         if (request == null && !e.Cancel && !bw.CancellationPending)
         {
             Logger.Error(SOURCE, "failed to create WebRequest");
             error = "Internal error";
             return;
         }
         string pointer;
         GetResponseAsync(request, "UpdateContent", ref bw, ref e, out pointer, out error);
         if (chunks.Count <= 1 || !string.IsNullOrEmpty(error)) return;
         for (var j = 1; j < chunks.Count; j++)
         {
             Logger.Info(SOURCE, string.Format("sending segment #{0} of {1} segments",
                                              j + 1, chunks.Count));
             ReceiveSegment(smtpAddress, configuration, chunks[j], id, ref bw, ref e, out error);
             if (error == "success") continue;
             Logger.Error(SOURCE, string.Format("exiting on error at chunk #{0}: {1}",
                                                j + 1, error));
             break;
         }
     }
     catch (Exception ex)
     {
         Logger.Error(SOURCE, ex.ToString());
         error = "Internal error";
     }
 }
Ejemplo n.º 9
0
        private static void ReceiveSegment(string smtpAddress, EcsConfiguration configuration, string segment,
            string id, ref BackgroundWorker bw, ref DoWorkEventArgs e, out string error)
        {
            const string SOURCE = CLASS_NAME + "ReceiveSegment";
            try
            {
                //assemble the post
                var post = AssembleLoginParams(smtpAddress, configuration.Password) +
                           string.Format("{0}&parms={1} {2}",
                                         "RECEIVE%20SEGMENT", id, HttpUtility.UrlEncode(segment));

                var postData = Encoding.UTF8.GetBytes(post);
                var request = CreateRequestAsync(configuration.Server, configuration.Port, postData,
                                                 ref bw, ref e);
                if (request == null && !e.Cancel && !bw.CancellationPending)
                {
                    Logger.Error(SOURCE, "failed to create WebRequest");
                    error = "Internal error";
                    return;
                }
                string pointer;
                GetResponseAsync(request, "ReceiveSegment", ref bw, ref e, out pointer, out error);
            }
            catch (Exception ex)
            {
                Logger.Error(SOURCE, ex.ToString());
                error = "Internal error";
            }
        }
Ejemplo n.º 10
0
        internal static string FetchEmbeddedImages(string content, List<Match> matches, 
            string baseUrl, Account account, EcsConfiguration configuration, string senderAddress, 
            string serverName, string serverPort, string encryptKey2, string userAgent)
        {
            //extract the src paths, if any
            foreach (var match in matches)
            {
                //extract the link from the src
                var ptrMatch = MatchPointer(match.Groups[2].Value);
                var pointer = ptrMatch.Groups[1].Value;
                var fileName = HttpUtility.UrlDecode(ptrMatch.Groups[2].Value);

                if (string.IsNullOrEmpty(fileName) || string.IsNullOrEmpty(pointer)) continue;
                //save to modified 'src' path
                var path = Path.Combine(baseUrl, pointer);
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                path = Path.Combine(path, fileName);
                if (!File.Exists(path))
                {
                    //get the content and write it to the path
                    GetEmbeddedFile(pointer, path, account, configuration, senderAddress,
                                    serverName, serverPort, "", encryptKey2, userAgent);
                }
                //read the bytes, base64 encode
                var data = Convert.ToBase64String(File.ReadAllBytes(path));
                var newValue = match.Groups[1].Value +
                               string.Format("data:image/{0};base64,{1}", Path.GetExtension(path), data) +
                               match.Groups[3].Value;
                //make sure we keep the pointer in the alt attribute
                //replace the link with base64 data protocol
                content = content.Replace(match.Value, newValue);
            }
            return content;
        }
Ejemplo n.º 11
0
 internal static void GetFile(string pointer, string name, int index, string recordKey,
     Account account, EcsConfiguration configuration, string senderAddress, string serverName, 
     string serverPort, string encryptKey, string encryptKey2, string userAgent, out string path, out string hash)
 {
     const string SOURCE = CLASS_NAME + "GetFile";
     path = "";
     hash = "";
     if (string.IsNullOrEmpty(recordKey)) return;
     try
     {
         path = GetFilePath(recordKey, index, name);
         if (!File.Exists(path))
         {
             //fetch the content
             string content;
             string error;
             ContentHandler.FetchContent(account.SMTPAddress, configuration, senderAddress,
                                         pointer, serverName, serverPort, true,
                                         out content, out error);
             if (string.IsNullOrEmpty(content))
             {
                 Logger.Warning(SOURCE, string.Format(
                     "failed to retrieve content for {0} using pointer {1} from {2}: {3}",
                     name, pointer, senderAddress, error));
                 return;
             }
             ContentHandler.SaveAttachment(
                 content, encryptKey, encryptKey2, userAgent, path);
         }
         //return the hash
         byte[] buf = File.ReadAllBytes(path);
         hash = Cryptography.GetHash(buf);
     }
     catch (Exception ex)
     {
         Logger.Error(SOURCE, ex.ToString());
     }
 }
Ejemplo n.º 12
0
 internal static string FetchEmbeddedFileImages(string content, List<Match> matches, Dictionary<string,string> pointerMap, 
                                                string baseUrl, Account account, EcsConfiguration configuration,
                                                string senderAddress, string serverName, string serverPort, string encryptKey2,
          string userAgent, ref List<string> embeddedFileNames)
 {
     //extract the src paths, if any
     foreach (var match in matches)
     {
         //extract the filename from the src
         var filePath = HttpUtility.UrlDecode(match.Groups[2].Value);
         if (string.IsNullOrEmpty(filePath)) continue;
         var fileName = Path.GetFileName(filePath);
         if(string.IsNullOrEmpty(fileName)) continue;
         if (!pointerMap.ContainsKey(fileName)) continue;
         var pointer = pointerMap[fileName];
         embeddedFileNames.Add(fileName);
         //save to modified 'src' path
         var path = Path.Combine(baseUrl, pointer);
         if (!Directory.Exists(path))
         {
             Directory.CreateDirectory(path);
         }
         path = Path.Combine(path, fileName);
         if (!File.Exists(path))
         {
             //get the content and write it to the path
             GetEmbeddedFile(pointer, path, account, configuration, senderAddress,
                             serverName, serverPort, "", encryptKey2, userAgent);
         }
         //replace the path
         var newPath = "file:///" + path.Replace("\\", "/");
         //make sure the src value is wrapped with quotes
         if (content.Contains("src=" + filePath))
         {
             //no - wrap with single quotes
             newPath = "'" + newPath + "'";
         }
         content = content.Replace(filePath, newPath);
     }
     return content;
 }
Ejemplo n.º 13
0
        public static bool PostAttachments(Outlook.MailItem item, Account account, EcsConfiguration configuration,
            string encryptKey, string recips, ref List<string> pointers, OutlookWin32Window win, bool noPlaceholder)
        {
            const string SOURCE = CLASS_NAME + "PostAttachments";
            try
            {
                //get the bytes for the placeholder text
                var placeholder = Encoding.UTF8.GetBytes(Resources.placeholder_text);
                SafeMailItem safMail;
                try
                {
                    safMail = RedemptionLoader.new_SafeMailItem();
                }
                catch (Exception ex)
                {
                    Logger.Error(SOURCE, String.Format(
                        "unable to work with attachments for {0}, failed to instantiate SafeMailItem: {1}",
                        item.Subject, ex.Message));
                    return false;
                }
                //need to save the item first before we can work with the SafeMailItem
                item.Save();
                safMail.Item = item;
                var colAttach = safMail.Attachments;
                /* Outlook will move any embedded images to the head of the attachments table
                * if that's the case then we need to remove and re-add the other attachments
                * so that the pointer list will match the finished order
                */
                var hidden = false;
                string contentId;
                var savedAttach = new Dictionary<int, byte[]>();
                //do we have any embedded images?
                foreach (Redemption.Attachment rdoAttach in colAttach)
                {
                    GetAttachProps(rdoAttach, out contentId, out hidden);
                    if (hidden) break;
                }
                if (hidden)
                {
                    //walk through in reverse order
                    //delete and reattach each non-hidden attachment
                    for (var i = colAttach.Count; i > 0; i--)
                    {
                        Redemption.Attachment rdoAttach = colAttach[i];
                        GetAttachProps(rdoAttach, out contentId, out hidden);
                        if (hidden) continue;
                        if (rdoAttach.Type.Equals(5)) //embedded
                        {
                            var msg = rdoAttach.EmbeddedMsg;
                            rdoAttach.Delete();
                            colAttach.Add(msg, 5);
                        }
                        else
                        {
                            var path = Path.Combine(Path.GetTempPath(), "ChiaraMail", rdoAttach.FileName);
                            var displayName = rdoAttach.DisplayName;
                            if (File.Exists(path)) File.Delete(path);
                            rdoAttach.SaveAsFile(path);
                            rdoAttach.Delete();
                            rdoAttach = colAttach.Add(path, 1, Type.Missing, displayName);
                            //get the bytes and drop those in the dictionary, linked to the current index
                            savedAttach.Add(rdoAttach.Index, File.ReadAllBytes(path));
                            File.Delete(path);
                        }
                    }
                }

                //now loop through and collect the content (except for embedded messages)
                var attachList = new List<Attachment>();
                bool showForm = false;
                foreach (Redemption.Attachment rdoAttach in colAttach)
                {
                    var attach = new Attachment { Type = rdoAttach.Type };
                    switch (rdoAttach.Type)
                    {
                        case (int)Outlook.OlAttachmentType.olEmbeddeditem:
                            //is this an ECS attachment?
                            var msg = rdoAttach.EmbeddedMsg;
                            if (HasChiaraHeader(msg))
                            {
                                ForwardEmbeddedECS(msg, recips, account);
                            }
                            //always add
                            attachList.Add(attach);
                            break;
                        case (int)Outlook.OlAttachmentType.olByReference:
                        case (int)Outlook.OlAttachmentType.olOLE:
                            attachList.Add(attach);
                            break;
                        case (int)Outlook.OlAttachmentType.olByValue:
                            showForm = true;
                            //we may have already gotten the bytes
                            if (savedAttach.Count > 0 && savedAttach.ContainsKey(rdoAttach.Index))
                            {
                                attach.Content = savedAttach[rdoAttach.Index];
                            }
                            if (attach.Content == null || attach.Content.Length == 0)
                            {
                                //try just read the bytes from the binary property
                                //this could fail if the attachment is too big
                                try
                                {
                                    attach.Content = rdoAttach.AsArray != null
                                        ? rdoAttach.AsArray as byte[]
                                        : null;//.Fields[ThisAddIn.PR_ATTACH_DATA_BIN]);
                                }
                                catch
                                {
                                    attach.Content = null;
                                }
                            }
                            if (attach.Content == null)
                            {
                                //save to disk then get the bytes
                                var path = Path.Combine(Path.GetTempPath(), "ChiaraMail", rdoAttach.FileName);
                                if (File.Exists(path)) File.Delete(path);
                                rdoAttach.SaveAsFile(path);
                                attach.Content = File.ReadAllBytes(path);
                                File.Delete(path);
                            }
                            if (attach.Content != null)
                            {
                                attach.Index = rdoAttach.Index;
                                attach.Name = rdoAttach.DisplayName;
                                attachList.Add(attach);
                            }
                            else
                            {
                                Logger.Warning(SOURCE,
                                               "aborting: failed to retrieve content for " + rdoAttach.DisplayName);
                                MessageBox.Show(String.Format(
                                    "Unable to retrieve original content from {0}",
                                    rdoAttach.DisplayName), Resources.product_name,
                                                MessageBoxButtons.OK,
                                                MessageBoxIcon.Error);
                                return false;
                            }
                            break;
                    }
                }
                if (!showForm)
                {
                    pointers.AddRange(attachList.Select(attach => attach.Pointer));
                    return true;
                }
                //use the WaitForm to upload the attachments
                var form = new WaitForm
                {
                    Attachments = attachList,
                    Account = account,
                    Configuration = configuration,
                    Recips = recips,
                    EncryptKey2 = encryptKey
                };
                //use encryptKey2 for new post
                if (form.ShowDialog(win) == DialogResult.OK)
                {
                    //post succeeded for all attachments
                    //get the pointers
                    pointers.AddRange(form.Attachments.Select(attach => attach.Pointer));
                    //don't replace attachment bytes if we are sending content
                    if (noPlaceholder) return true;
                    //loop back through to replace the original content with the placeholder bytes
                    foreach (Redemption.Attachment rdoAttach in colAttach)
                    {
                        if (rdoAttach.Type.Equals(1)) //OlAttachmentType.olByValue)
                        {
                            rdoAttach.Fields[ThisAddIn.PR_ATTACH_DATA_BIN] = placeholder;
                        }
                    }
                    return true;
                }
                //get the pointer list anyway so we can delete the items that got posted
                pointers.AddRange(form.Attachments
                                      .TakeWhile(attach => !String.IsNullOrEmpty(attach.Pointer))
                                      .Select(attach => attach.Pointer));
            }
            catch (Exception ex)
            {
                Logger.Error(SOURCE, ex.ToString());
            }
            return false;
        }
Ejemplo n.º 14
0
 private static void GetEmbeddedFile(string pointer, string path, Account account,
     EcsConfiguration configuration, string senderAddress, string serverName, string serverPort, 
     string encryptKey, string encryptKey2, string userAgent)
 {
     const string SOURCE = CLASS_NAME + "GetEmbeddedFile";
     try
     {
         if (File.Exists(path)) return;
         string content;
         string error;
         ContentHandler.FetchContent(account.SMTPAddress, configuration, senderAddress,
             pointer, serverName, serverPort, true, out content,
             out error);
         if (string.IsNullOrEmpty(content))
         {
             Logger.Warning(SOURCE, string.Format(
                 "failed to retrieve image {0} using pointer {1} from {2}: {3}",
                 Path.GetFileName(path), pointer, senderAddress, error));
             return;
         }
         ContentHandler.SaveAttachment(content, encryptKey, encryptKey2, userAgent, path);
     }
     catch (Exception ex)
     {
         Logger.Error(SOURCE, ex.ToString());
     }
 }
Ejemplo n.º 15
0
        private List<Attachment> FetchParentAttachContent(MailItem parent, IList<string> pointers,
            string key, Account account, EcsConfiguration configuration, string senderAddress,
            string serverName, string serverPort, string encryptKey, string encryptKey2)
        {
            const string SOURCE = CLASS_NAME + "FetchParentAttachContent";
            var attachList = new List<Attachment>();
            try
            {
                var attachments = parent.Attachments;
                if (pointers.Count > 1 && attachments.Count > 0)
                {
                    //we need the dynamic content for each attachment
                    var parentPath = Path.Combine(Path.GetTempPath(),
                            "ChiaraMail", key);
                    MAPIUtils mapiUtils;
                    try
                    {
                        mapiUtils = RedemptionLoader.new_MAPIUtils();
                    }
                    catch (Exception ex)
                    {
                        Logger.Warning(SOURCE, string.Format(
                            "unable to fetch ECS-enabled content for attachments on {0} - error loading MAPIUtils: {1}",
                            parent.Subject, ex.Message));
                        return null;
                    }

                    for (var i = 1; i < attachments.Count + 1; i++)
                    {
                        var attach = attachments[i];
                        var cmAttach = new Attachment
                                           {
                                               Index = i,
                                               Pointer = pointers[i],
                                               Name = attach.DisplayName,
                                               Type = (int)attach.Type
                                           };

                        //only check ByValue - embedded message isn't stored on server
                        if (attach.Type == OlAttachmentType.olByValue)
                        {
                            //check for content-id on hidden attachment
                            var contentId = string.Empty;
                            try
                            {
                                var prop = mapiUtils.HrGetOneProp(attach, (int) MAPITags.PR_ATTACHMENT_HIDDEN);
                                if (prop != null && Convert.ToBoolean(prop))
                                {
                                    prop = mapiUtils.HrGetOneProp(attach, PR_ATTACH_CONTENT_ID);
                                    if (prop != null) contentId = Convert.ToString(prop);
                                }
                            }
                            catch
                            {
                                contentId = "";
                            }
                            string attachPath;
                            if (!string.IsNullOrEmpty(contentId))
                            {
                                attachPath = Path.Combine(parentPath, contentId);
                                cmAttach.ContentId = contentId;
                            }
                            else
                            {
                                attachPath = Path.Combine(parentPath, Convert.ToString(i), attach.DisplayName);
                            }
                            if (File.Exists(attachPath))
                            {
                                //load the bytes
                                cmAttach.Content = File.ReadAllBytes(attachPath);
                            }
                            else
                            {
                                //fetch it
                                string error;
                                string content;
                                ContentHandler.FetchContent(account.SMTPAddress, configuration,
                                    senderAddress, pointers[i], serverName, serverPort, true,
                                    out content, out error);
                                if (!string.IsNullOrEmpty(error) &&
                                    !error.Equals("Success",StringComparison.CurrentCultureIgnoreCase))
                                {
                                    Logger.Warning(SOURCE, string.Format(
                                        "failed to retrieve content for attachment {0} on item from sender {1}",
                                        i, senderAddress));
                                    continue;
                                }
                                cmAttach.Content = ContentHandler.GetAttachBytes(
                                    content, encryptKey, encryptKey2);
                            }
                        }
                        attachList.Add(cmAttach);
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Error(SOURCE, ex.ToString());
            }
            return attachList;
        }
Ejemplo n.º 16
0
 internal static ThisAddIn.LicenseState CheckLicensed(string smtpAddress, EcsConfiguration configuration, string serverAddress)
 {
     const string SOURCE = CLASS_NAME + "CheckLicensed";
     try
     {
         string post = AssembleLoginParams(smtpAddress, configuration.Password) +
             string.Format("{0}&parms={1}",
             "SERVER%20LICENSED", serverAddress);
         byte[] postData = Encoding.UTF8.GetBytes(post);
         var request = CreateRequest(configuration.Server, configuration.Port, postData);
         if (request == null)
         {
             Logger.Error(SOURCE, "failed to create HttpWebRequest object");
             return ThisAddIn.LicenseState.Unknown;
         }
         var response = request.GetResponse() as HttpWebResponse;
         if (!request.HaveResponse)
         {
             Logger.Error(SOURCE, "server did not respond");
             request.Abort();
             return ThisAddIn.LicenseState.Unknown;
         }
         if (response == null)
         {
             Logger.Error(SOURCE, "response is null");
             return ThisAddIn.LicenseState.Unknown;
         }
         var stream = response.GetResponseStream();
         if (stream == null)
         {
             Logger.Error(SOURCE, "response stream is null");
             return ThisAddIn.LicenseState.Unknown;
         }
         var reader = new StreamReader(stream);
         var responseText = reader.ReadToEnd();
         if (string.IsNullOrEmpty(responseText)) return 0;
         /* -27 Missing or expired content sever license:
         *  -10 Invalid number of parameters
         *  -2 Login not complete
         *  10 Server Licensed
         */
         var value = responseText.Split(new [] {' '}, 2);
         switch (value[0])
         {
             case "-27":
                 return ThisAddIn.LicenseState.NotLicensed;
             case "10":
                 return ThisAddIn.LicenseState.Licensed;
             default:
                 return ThisAddIn.LicenseState.Unknown;
         }
     }
     catch (Exception ex)
     {
         Logger.Error(SOURCE, ex.ToString());
         return ThisAddIn.LicenseState.Unknown;
     }
 }
Ejemplo n.º 17
0
 internal static EcsConfiguration GetMatchingConfiguration(string smtpAddress, string server, 
     string port, bool create)
 {
     EcsConfiguration config = null;
     //if account was just created it won't be in the list
     var account = FindMatchingAccount(smtpAddress);
     if (account != null)
     {
         config = account.Configurations.Keys
         .Select(key => account.Configurations[key])
         .FirstOrDefault(c =>
             c.Server.Equals(server, StringComparison.CurrentCultureIgnoreCase)
             && c.Port == port);
     }
     // even for an unknown account there is always a default configuration (for the public content server)
     // it just won't have a password
     if (config == null && create &&
         server.Equals(PUBLIC_SERVER, StringComparison.CurrentCultureIgnoreCase) &&
         port == Resources.default_port)
     {
         //if we have the account address try to get the password
         config = new EcsConfiguration
         {
             Server = PUBLIC_SERVER,
             Port = Resources.default_port
         };
         if (account != null)
         {
             config.Password = FetchPasswordPublicServer(account.SMTPAddress,
                 account.UserName,account.Protocol,
                 account.Host,account.Port, account.LoginName);
             account.Configurations.Add(0,config);
         }
     }
     return config;
 }
Ejemplo n.º 18
0
 public static void DeletePointers(List<string> pointers, Account account, EcsConfiguration configuration)
 {
     const string SOURCE = CLASS_NAME + "DeletePointers";
     Logger.Info(SOURCE, String.Format(
         "deleting {0} pointers after failed attachment upload",
         pointers.Count));
     foreach (var pointer in pointers)
     {
         string error;
         ContentHandler.DeleteContent(account.SMTPAddress,
             configuration, pointer, out error, true);
     }
 }