public MailAttachment ToMailAttachment(string link)
 {
     var file_name = Path.GetFileName(link);
     if (!loaded_smiles.ContainsKey(link))
     {
         var attach = new MailAttachment
                         {
                             fileName = file_name,
                             storedName = file_name,
                             contentId = link.GetMD5(),
                             data = LoadSmileData(link)
                         };
         loaded_smiles[link] = attach;
     }
     return loaded_smiles[link];
 }
示例#2
0
 private static void LoadAttachmentData(MailAttachment attach, string domain, string file_link, IDataStore current_img_storage)
 {
     using (var stream = current_img_storage.GetReadStream(domain, file_link))
     {
         attach.data = stream.GetCorrectBuffer();
     }
 }
 public void StoreAttachmentWithoutQuota(int tenant, string user, MailAttachment attachment)
 {
     StoreAttachmentWithoutQuota(tenant, user, attachment, MailDataStore.GetDataStore(tenant));
 }
        public MailAttachment AttachFile(int tenant, string user, int messageId,
                                         string name, Stream inputStream)
        {
            if (messageId < 1)
            {
                throw new AttachmentsException(AttachmentsException.Types.BadParams, "Field 'id_message' must have non-negative value.");
            }

            if (tenant < 0)
            {
                throw new AttachmentsException(AttachmentsException.Types.BadParams, "Field 'id_tenant' must have non-negative value.");
            }

            if (String.IsNullOrEmpty(user))
            {
                throw new AttachmentsException(AttachmentsException.Types.BadParams, "Field 'id_user' is empty.");
            }

            if (inputStream.Length == 0)
            {
                throw new AttachmentsException(AttachmentsException.Types.EmptyFile, "Empty files not supported.");
            }

            var message = GetMailInfo(tenant, user, messageId, false, false);

            if (message == null)
            {
                throw new AttachmentsException(AttachmentsException.Types.MessageNotFound, "Message not found.");
            }

            if (message.Folder != MailFolder.Ids.drafts)
            {
                throw new AttachmentsException(AttachmentsException.Types.BadParams, "Message is not a draft.");
            }

            if (string.IsNullOrEmpty(message.StreamId))
            {
                throw new AttachmentsException(AttachmentsException.Types.MessageNotFound, "StreamId is empty.");
            }

            var totalSize = GetAttachmentsTotalSize(messageId) + inputStream.Length;

            if (totalSize > ATTACHMENTS_TOTAL_SIZE_LIMIT)
            {
                throw new AttachmentsException(AttachmentsException.Types.TotalSizeExceeded, "Total size of all files exceeds limit!");
            }

            var fileNumber = GetMaxAttachmentNumber(messageId, tenant);

            var attachment = new MailAttachment
            {
                fileName    = name,
                contentType = MimeMapping.GetMimeMapping(name),
                fileNumber  = fileNumber,
                size        = inputStream.Length,
                data        = inputStream.ReadToEnd(),
                streamId    = message.StreamId,
                tenant      = tenant,
                user        = user,
                mailboxId   = message.MailboxId
            };

            QuotaUsedAdd(tenant, inputStream.Length);
            try
            {
                StoreAttachmentWithoutQuota(tenant, user, attachment);
            }
            catch
            {
                QuotaUsedDelete(tenant, inputStream.Length);
                throw;
            }

            using (var db = GetDb())
            {
                using (var tx = db.BeginTransaction())
                {
                    attachment.fileId = SaveAttachment(db, tenant, messageId, attachment);
                    UpdateMessageChainAttachmentsFlag(db, tenant, user, messageId);

                    tx.Commit();
                }
            }

            return(attachment);
        }
        public MailAttachment AttachFile(int id_tenant, string id_user, int id_message,
            string name, Stream input_stream, string id_stream)
        {
            if (id_message < 0)
                throw new AttachmentsException(AttachmentsException.Types.BAD_PARAMS, "Field 'id_message' must have non-negative value.");

            if (id_tenant < 0)
                throw new AttachmentsException(AttachmentsException.Types.BAD_PARAMS, "Field 'id_tenant' must have non-negative value.");

            if (String.IsNullOrEmpty(id_user))
                throw new AttachmentsException(AttachmentsException.Types.BAD_PARAMS, "Field 'id_user' is empty.");

            if (input_stream.Length == 0)
                throw new AttachmentsException(AttachmentsException.Types.EMPTY_FILE, "Empty files not supported.");


            if (string.IsNullOrEmpty(id_stream))
                throw new AttachmentsException(AttachmentsException.Types.MESSAGE_NOT_FOUND, "Message not found.");

            var total_size = GetAttachmentsTotalSize(id_message) + input_stream.Length;

            if (total_size > ATTACHMENTS_TOTAL_SIZE_LIMIT)
                throw new AttachmentsException(AttachmentsException.Types.TOTAL_SIZE_EXCEEDED, "Total size of all files exceeds limit!");

            var file_number = GetMaxAttachmentNumber(id_message);

            var attachment = new MailAttachment
            {
                fileName = name,
                contentType = MimeMapping.GetMimeMapping(name),
                fileNumber = file_number,
                size = input_stream.Length,
                data = input_stream.GetCorrectBuffer(),
                streamId = id_stream,
                tenant = id_tenant,
                user = id_user
            };

            QuotaUsedAdd(id_tenant, input_stream.Length);
            try
            {
                StoreAttachmentWithoutQuota(id_tenant, id_user, attachment);
            }
            catch
            {
                QuotaUsedDelete(id_tenant, input_stream.Length);
                throw;
            }

            try
            {
                using (var db = GetDb())
                {
                    using (var tx = db.BeginTransaction())
                    {
                        attachment.fileId = SaveAttachment(db, id_tenant, id_message, attachment);
                        UpdateMessageChainAttachmentsFlag(db, id_tenant, id_user, id_message);

                        tx.Commit();
                    }
                }
            }
            catch
            {
                //TODO: If exception has happened, need to remove stored files from s3 and remove quota
                throw;
            }

            return attachment;
        }
        private MailAttachment ToMailItemAttachment(object[] r)
        {
            if (r.Length != SelectMailItemAttachmentFieldsCont)
            {
                Console.WriteLine("Count of returned fields not equal to");
                var results = r;
                foreach (var field in results)
                {
                    Console.WriteLine(field == null ? "null" : field.ToString());
                }
                return null;
            }

            var attachment = new MailAttachment
                {
                    fileId = Convert.ToInt32(r[(int) MailItemAttachmentSelectPosition.Id]),
                    fileName = Convert.ToString(r[(int) MailItemAttachmentSelectPosition.Name]),
                    storedName = Convert.ToString(r[(int) MailItemAttachmentSelectPosition.StoredName]),
                    contentType = Convert.ToString(r[(int) MailItemAttachmentSelectPosition.Type]),
                    size = Convert.ToInt64(r[(int) MailItemAttachmentSelectPosition.Size]),
                    fileNumber = Convert.ToInt32(r[(int) MailItemAttachmentSelectPosition.FileNumber]),
                    streamId = Convert.ToString(r[(int)MailItemAttachmentSelectPosition.IdStream]),
                    tenant = Convert.ToInt32(r[(int)MailItemAttachmentSelectPosition.Tenant]),
                    user = Convert.ToString(r[(int)MailItemAttachmentSelectPosition.User]),
                    contentId = Convert.ToString(r[(int)MailItemAttachmentSelectPosition.ContentId])
                };
            
            // if StoredName is empty then attachment had been stored by filename (old attachment);
            attachment.storedName = string.IsNullOrEmpty(attachment.storedName)? attachment.fileName: attachment.storedName;

            return attachment;
        }
示例#7
0
        public MailAttachment AttachFile(int tenant, string user, MailMessage message,
                                         string name, Stream inputStream, string contentType = null)
        {
            if (message == null)
            {
                throw new AttachmentsException(AttachmentsException.Types.MessageNotFound, "Message not found.");
            }

            if (string.IsNullOrEmpty(message.StreamId))
            {
                throw new AttachmentsException(AttachmentsException.Types.MessageNotFound, "StreamId is empty.");
            }

            var messageId = (int)message.Id;

            var totalSize = GetAttachmentsTotalSize(messageId) + inputStream.Length;

            if (totalSize > ATTACHMENTS_TOTAL_SIZE_LIMIT)
            {
                throw new AttachmentsException(AttachmentsException.Types.TotalSizeExceeded, "Total size of all files exceeds limit!");
            }

            var fileNumber = GetMaxAttachmentNumber(messageId, tenant);

            var attachment = new MailAttachment
            {
                fileName    = name,
                contentType = string.IsNullOrEmpty(contentType) ? MimeMapping.GetMimeMapping(name) : contentType,
                fileNumber  = fileNumber,
                size        = inputStream.Length,
                data        = inputStream.ReadToEnd(),
                streamId    = message.StreamId,
                tenant      = tenant,
                user        = user,
                mailboxId   = message.MailboxId
            };

            QuotaUsedAdd(tenant, inputStream.Length);
            try
            {
                var storage = new StorageManager(tenant, user);
                storage.StoreAttachmentWithoutQuota(attachment);
            }
            catch
            {
                QuotaUsedDelete(tenant, inputStream.Length);
                throw;
            }

            using (var db = GetDb())
            {
                using (var tx = db.BeginTransaction())
                {
                    attachment.fileId = SaveAttachment(db, tenant, messageId, attachment);
                    UpdateMessageChainAttachmentsFlag(db, tenant, user, messageId);

                    tx.Commit();
                }
            }

            return(attachment);
        }
 public void StoreAttachmentWithoutQuota(int id_tenant, string id_user, MailAttachment attachment)
 {
     StoreAttachmentWithoutQuota(id_tenant, id_user, attachment, MailDataStore.GetDataStore(id_tenant));
 }
 public int SaveAttachment(DbManager db, int id_tenant, int id_mail, MailAttachment attachment)
 {
     return SaveAttachment(db, id_tenant, id_mail, attachment, true);
 }
 public int SaveAttachment(int id_tenant, int id_mail, MailAttachment attachment)
 {
     using (var db = GetDb())
     {
         return SaveAttachment(db, id_tenant, id_mail, attachment);
     }
 }
        public int SaveAttachmentInTransaction(int id_tenant, int id_mail, MailAttachment attachment)
        {
            int id;
            using (var db = GetDb())
            {
                using (var tx = db.BeginTransaction())
                {
                    id = SaveAttachment(db, id_tenant, id_mail, attachment);

                    tx.Commit();
                }
            }
            return id;
        }
        public void StoreAttachmentWithoutQuota(int id_tenant, string id_user, MailAttachment attachment, IDataStore storage)
        {
            try
            {
                if (attachment.data == null || attachment.data.Length == 0)
                    return;

                if (string.IsNullOrEmpty(attachment.fileName))
                    attachment.fileName = "attachment.ext";

                var content_disposition = MailStoragePathCombiner.PrepareAttachmentName(attachment.fileName);

                var ext = Path.GetExtension(attachment.fileName);

                attachment.storedName = CreateNewStreamId();

                if (!string.IsNullOrEmpty(ext))
                    attachment.storedName = Path.ChangeExtension(attachment.storedName, ext);

                attachment.fileNumber =
                    !string.IsNullOrEmpty(attachment.contentId) //Upload hack: embedded attachment have to be saved in 0 folder
                        ? 0
                        : attachment.fileNumber;

                var attachment_path = attachment.GerStoredFilePath();

                using (var reader = new MemoryStream(attachment.data))
                {
                    var upload_url = storage.UploadWithoutQuota(string.Empty, attachment_path, reader, attachment.contentType, content_disposition);
                    attachment.storedFileUrl = MailStoragePathCombiner.GetStoredUrl(upload_url);
                }
            }
            catch (Exception e)
            {
                _log.Error("StoreAttachmentWithoutQuota(). filename: {0}, ctype: {1} Exception:\r\n{2}\r\n",
                    attachment.fileName,
                    attachment.contentType,
                    e.ToString());

                throw;
            }
        }
 public void StoreAttachmentWithoutQuota(int id_tenant, string id_user, MailAttachment attachment)
 {
     StoreAttachmentWithoutQuota(id_tenant, id_user, attachment, GetDataStore(id_tenant));
 }
        public void StoreAttachmentCopy(int id_tenant, string id_user, MailAttachment attachment, string stream_id)
        {
            try
            {
                if (!attachment.streamId.Equals(stream_id))
                {
                    var s3_key = attachment.GerStoredFilePath();

                        var data_client = GetDataStore(id_tenant);

                        if (data_client.IsFile(s3_key))
                        {
                        attachment.fileNumber =
                            !string.IsNullOrEmpty(attachment.contentId) //Upload hack: embedded attachment have to be saved in 0 folder
                                ? 0
                                : attachment.fileNumber;
                        
                        var new_s3_key = MailStoragePathCombiner.GetFileKey(id_user, stream_id, attachment.fileNumber,
                                                                            attachment.storedName);

                            var copy_s3_url = data_client.Copy(s3_key, string.Empty, new_s3_key);

                        attachment.storedFileUrl = MailStoragePathCombiner.GetStoredUrl(copy_s3_url);

                        attachment.streamId = stream_id;
                        }
                    }
                }
            catch (Exception ex)
            {
                _log.Error("CopyAttachment(). filename: {0}, ctype: {1} Exception:\r\n{2}\r\n",
                           attachment.fileName,
                           attachment.contentType,
                    ex.ToString());

                throw;
            }
        }
示例#15
0
        private static MimePart CreateAttachment(MailAttachment attachment, bool load_attachments)
        {
            var ret_val = new MimePart();

            var s3_key = attachment.GerStoredFilePath();
            var file_name = attachment.fileName ?? Path.GetFileName(s3_key);

            if (load_attachments)
            {
                var byte_array = attachment.data;

                if (byte_array == null || byte_array.Length == 0)
                {
                    using (var stream = GetDataStoreForAttachments(attachment.tenant).GetReadStream(s3_key))
                    {
                        byte_array = stream.GetCorrectBuffer();
                    }
                }

                ret_val = new MimePart(byte_array, file_name);

                if (attachment.contentId != null) ret_val.ContentId = attachment.contentId;
            }
            else
            {
                var conent_type = Common.Web.MimeMapping.GetMimeMapping(s3_key);
                ret_val.ContentType = new ContentType {Type = conent_type};
                ret_val.Filename = file_name;
                if (attachment.contentId != null) ret_val.ContentId = attachment.contentId;
                ret_val.TextContent = "";
            }

            return ret_val;
        }
        public MailAttachment AttachFile(int id_tenant, string id_user, int id_message,
                                         string name, Stream input_stream, string id_stream)
        {
            if (id_message < 0)
            {
                throw new AttachmentsException(AttachmentsException.Types.BAD_PARAMS, "Field 'id_message' must have non-negative value.");
            }

            if (id_tenant < 0)
            {
                throw new AttachmentsException(AttachmentsException.Types.BAD_PARAMS, "Field 'id_tenant' must have non-negative value.");
            }

            if (String.IsNullOrEmpty(id_user))
            {
                throw new AttachmentsException(AttachmentsException.Types.BAD_PARAMS, "Field 'id_user' is empty.");
            }

            if (input_stream.Length == 0)
            {
                throw new AttachmentsException(AttachmentsException.Types.EMPTY_FILE, "Empty files not supported.");
            }


            if (string.IsNullOrEmpty(id_stream))
            {
                throw new AttachmentsException(AttachmentsException.Types.MESSAGE_NOT_FOUND, "Message not found.");
            }

            var total_size = GetAttachmentsTotalSize(id_message) + input_stream.Length;

            if (total_size > ATTACHMENTS_TOTAL_SIZE_LIMIT)
            {
                throw new AttachmentsException(AttachmentsException.Types.TOTAL_SIZE_EXCEEDED, "Total size of all files exceeds limit!");
            }

            var file_number = GetMaxAttachmentNumber(id_message);

            var attachment = new MailAttachment
            {
                fileName    = name,
                contentType = MimeMapping.GetMimeMapping(name),
                fileNumber  = file_number,
                size        = input_stream.Length,
                data        = input_stream.GetCorrectBuffer(),
                streamId    = id_stream,
                tenant      = id_tenant,
                user        = id_user
            };

            QuotaUsedAdd(id_tenant, input_stream.Length);
            try
            {
                StoreAttachmentWithoutQuota(id_tenant, id_user, attachment);
            }
            catch
            {
                QuotaUsedDelete(id_tenant, input_stream.Length);
                throw;
            }

            try
            {
                using (var db = GetDb())
                {
                    using (var tx = db.BeginTransaction())
                    {
                        attachment.fileId = SaveAttachment(db, id_tenant, id_message, attachment);
                        UpdateMessageChainAttachmentsFlag(db, id_tenant, id_user, id_message);

                        tx.Commit();
                    }
                }
            }
            catch
            {
                //TODO: If exception has happened, need to remove stored files from s3 and remove quota
                throw;
            }

            return(attachment);
        }
        public int SaveAttachment(DbManager db, int id_tenant, int id_mail, MailAttachment attachment, bool need_recount)
        {
            var id = db.ExecuteScalar<int>(
                        new SqlInsert(AttachmentTable.name)
                            .InColumnValue(AttachmentTable.Columns.id, 0)
                            .InColumnValue(AttachmentTable.Columns.id_mail, id_mail)
                            .InColumnValue(AttachmentTable.Columns.name, attachment.fileName)
                            .InColumnValue(AttachmentTable.Columns.stored_name, attachment.storedName)
                            .InColumnValue(AttachmentTable.Columns.type, attachment.contentType)
                            .InColumnValue(AttachmentTable.Columns.size, attachment.size)
                            .InColumnValue(AttachmentTable.Columns.file_number, attachment.fileNumber)
                            .InColumnValue(AttachmentTable.Columns.need_remove, false)
                            .InColumnValue(AttachmentTable.Columns.content_id, attachment.contentId)
                            .InColumnValue(AttachmentTable.Columns.id_tenant, id_tenant)
                            .Identity(0, 0, true));

            if (need_recount)
                ReCountAttachments(db, id_mail);

            return id;
        }
 public int SaveAttachment(DbManager db, int id_tenant, int id_mail, MailAttachment attachment)
 {
     return(SaveAttachment(db, id_tenant, id_mail, attachment, true));
 }
 public AttachmentStream GetAttachmentStream(MailAttachment attachment)
 {
     if (attachment != null)
     {
         var storage = GetDataStore(attachment.tenant);
         var attachment_path = attachment.GerStoredFilePath();
         var result = new AttachmentStream
         {
             FileStream = storage.GetReadStream("", attachment_path),
             FileName = attachment.fileName
         };
         return result;
     }
     throw new InvalidOperationException("Attachment not found");
 }
示例#20
0
 public int SaveAttachment(DbManager db, int tenant, int messageId, MailAttachment attachment)
 {
     return(SaveAttachment(db, tenant, messageId, attachment, true));
 }
示例#21
0
        private void PreprocessHtml(int tennantid, List<MailAttachment> internalAttachments)
        {
            //Parse html attachments
            var storage = GetDataStoreForEmbeddedAttachments(tennantid);
            string baseValue = storage.GetUri(EmbeddedDomain, "").ToString();
            //Load html doc
            HtmlDocument doc = new HtmlDocument();
            doc.LoadHtml(HtmlBody);
            var linkNodes = doc.DocumentNode.SelectNodes("//img[@src and (contains(@src,'" + baseValue + "'))]");
            if (linkNodes != null)
            {
                foreach (var linkNode in linkNodes)
                {
                    var link = linkNode.Attributes["src"].Value;
                    var file_link = link.Substring(baseValue.Length);

                    //Change
                    var attach = new MailAttachment()
                    {
                        Url = EmbeddedDomain + "|" + file_link,
                        ContentID = GenerateContentId()
                    };
                    internalAttachments.Add(attach);
                    linkNode.SetAttributeValue("src", "cid:" + attach.ContentID);
                }
            }
            HtmlBody = doc.DocumentNode.OuterHtml;
        }
示例#22
0
        private static MimePart CreateAttachment(int tennantid, MailAttachment attachment, bool loadAttachments)
        {
            ActiveUp.Net.Mail.MimePart retVal = new ActiveUp.Net.Mail.MimePart();
            var fileName = Path.GetFileName(HttpUtility.UrlDecode(attachment.Url.Split('|')[1]));

            if (loadAttachments)
            {
                var pathInfo = attachment.Url.Split('|');

                var is_embedded = !string.IsNullOrEmpty(attachment.ContentID);

                using (var s = is_embedded ?
                    GetDataStoreForEmbeddedAttachments(tennantid).GetReadStream(EmbeddedDomain, pathInfo[1]) :
                    GetDataStoreForAttachments(tennantid, pathInfo[0]).GetReadStream(HttpUtility.UrlDecode(pathInfo[1])))
                {
                    retVal = new MimePart(s.GetCorrectBuffer(), fileName);
                    retVal.ContentDisposition.Disposition = "attachment";
                }
                if (attachment.ContentID != null) retVal.ContentId = attachment.ContentID;
            }
            else
            {
                var conentType = ASC.Common.Web.MimeMapping.GetMimeMapping(attachment.Url);
                retVal.ContentType = new ActiveUp.Net.Mail.ContentType() { Type = conentType };
                retVal.Filename = Path.GetFileName(HttpUtility.UrlDecode(fileName));
                if (attachment.ContentID != null) retVal.ContentId = attachment.ContentID;
                retVal.TextContent = "";
            }

            return retVal;
        }
示例#23
0
        public override FileUploadResult ProcessUpload(HttpContext context)
        {
            var file_name = string.Empty;
            MailAttachment attachment = null;
            try
            {
                if (!SecurityContext.AuthenticateMe(CookiesManager.GetCookies(CookiesType.AuthKey)))
                    throw new UnauthorizedAccessException(MailResource.AttachemntsUnauthorizedError);

                if (ProgressFileUploader.HasFilesToUpload(context))
                {
                    try
                    {
                        var stream_id = context.Request["stream"];
                        var mail_id = Convert.ToInt32(context.Request["messageId"]);

                        if (mail_id < 1)
                            throw new AttachmentsException(AttachmentsException.Types.MESSAGE_NOT_FOUND,
                                                           "Message not yet saved!");

                        if (String.IsNullOrEmpty(stream_id))
                            throw new AttachmentsException(AttachmentsException.Types.BAD_PARAMS, "Have no stream");

                        var posted_file = new ProgressFileUploader.FileToUpload(context);

                        file_name = context.Request["name"];

                        attachment = new MailAttachment
                            {
                                fileId = -1,
                                size = posted_file.ContentLength,
                                fileName = file_name,
                                streamId = stream_id,
                                tenant = TenantId,
                                user = Username
                            };

                        attachment = _mailBoxManager.AttachFile(TenantId, Username, mail_id,
                                                                    file_name, posted_file.InputStream, stream_id);

                        return new FileUploadResult
                            {
                                Success = true,
                                FileName = attachment.fileName,
                                FileURL = attachment.storedFileUrl,
                                Data = attachment
                            };
                    }
                    catch (AttachmentsException e)
                    {
                        string error_message;

                        switch (e.ErrorType)
                        {
                            case AttachmentsException.Types.BAD_PARAMS:
                                error_message = MailScriptResource.AttachmentsBadInputParamsError;
                                break;
                            case AttachmentsException.Types.EMPTY_FILE:
                                error_message = MailScriptResource.AttachmentsEmptyFileNotSupportedError;
                                break;
                            case AttachmentsException.Types.MESSAGE_NOT_FOUND:
                                error_message = MailScriptResource.AttachmentsMessageNotFoundError;
                                break;
                            case AttachmentsException.Types.TOTAL_SIZE_EXCEEDED:
                                error_message = MailScriptResource.AttachmentsTotalLimitError;
                                break;
                            case AttachmentsException.Types.DOCUMENT_NOT_FOUND:
                                error_message = MailScriptResource.AttachmentsDocumentNotFoundError;
                                break;
                            case AttachmentsException.Types.DOCUMENT_ACCESS_DENIED:
                                error_message = MailScriptResource.AttachmentsDocumentAccessDeniedError;
                                break;
                            default:
                                error_message = MailScriptResource.AttachmentsUnknownError;
                                break;
                        }
                        throw new Exception(error_message);
                    }
                    catch (ASC.Core.Tenants.TenantQuotaException)
                    {
                        throw;
                    }
                    catch (Exception)
                    {
                        throw new Exception(MailScriptResource.AttachmentsUnknownError);
                    }
                }
                throw new Exception(MailScriptResource.AttachmentsBadInputParamsError);
            }
            catch (Exception ex)
            {
                return new FileUploadResult
                    {
                        Success = false,
                        FileName = file_name,
                        Data = attachment,
                        Message = ex.Message,
                    };
            }
        }