// Token: 0x06000D05 RID: 3333 RVA: 0x00036658 File Offset: 0x00034858
 private void ReadAttachmentIntoStreamAndValidateHash(IStreamAttachment attachment, Stream outputStream, Action abortFileOperation)
 {
     using (IOCostStream iocostStream = new IOCostStream(outputStream))
     {
         using (new FileSystemPerformanceTracker("MailboxDownload", iocostStream, this.logger))
         {
             using (HashAlgorithm hashAlgorithm = new SHA1CryptoServiceProvider())
             {
                 using (new StorePerformanceTracker("MailboxDownload", this.logger))
                 {
                     CopyStreamResult arg;
                     using (IOCostStream iocostStream2 = new IOCostStream(attachment.GetContentStream()))
                     {
                         using (new FileSystemPerformanceTracker("MailboxDownload", iocostStream2, this.logger))
                         {
                             arg = MailboxFileStore.streamCopier.CopyStream(iocostStream2, iocostStream, hashAlgorithm, abortFileOperation);
                         }
                     }
                     this.tracer.TraceDebug <CopyStreamResult>((long)this.GetHashCode(), "Downloaded file attachment from mailbox. {0}", arg);
                     byte[] array = attachment[AttachmentSchema.AttachHash] as byte[];
                     this.tracer.TraceDebug <ArrayTracer <byte> >((long)this.GetHashCode(), "Expected hash in attachment downloaded from mailbox is: {0}.", new ArrayTracer <byte>(array));
                     if (!ArrayComparer <byte> .Comparer.Equals(hashAlgorithm.Hash, array))
                     {
                         throw new InvalidDataException(string.Format("Hash of data content doesn't match hash of original uploaded file. Expected: {0}, actual: {1}.", BitConverter.ToString(array), BitConverter.ToString(hashAlgorithm.Hash)));
                     }
                 }
             }
         }
     }
 }
        // Token: 0x06000D04 RID: 3332 RVA: 0x00036598 File Offset: 0x00034798
        private string DownloadSingleFile(IStreamAttachment attachment, string tempDirectory, bool ignoreDuplicateFiles, Action abortFileOperation)
        {
            abortFileOperation();
            string text = attachment[AttachmentSchema.AttachLongFileName] as string;

            if (string.IsNullOrWhiteSpace(text))
            {
                this.tracer.TraceError((long)this.GetHashCode(), "Unable to get AttachLongFileName property from attachment");
                return(null);
            }
            string text2 = Path.Combine(tempDirectory, text);

            if (ignoreDuplicateFiles && File.Exists(text2))
            {
                this.tracer.TraceError <string>((long)this.GetHashCode(), "File {0} already exists, so skipping download", text2);
                return(null);
            }
            bool flag = false;

            try
            {
                this.ReadAttachmentIntoStreamAndValidateHash(attachment, new FileStream(text2, FileMode.CreateNew), abortFileOperation);
                flag = true;
            }
            finally
            {
                if (!flag)
                {
                    this.tracer.TraceDebug <string>((long)this.GetHashCode(), "Download failed and temporary file '{0}' needs to be removed", text2);
                    this.DeleteFile(text2);
                }
            }
            return(text2);
        }
        // Token: 0x06000D03 RID: 3331 RVA: 0x0003642C File Offset: 0x0003462C
        private void UploadSingleFile(string fileName, IAttachmentCollection attachmentCollection, Action abortFileOperation)
        {
            abortFileOperation();
            string fileName2 = Path.GetFileName(fileName);

            using (IOCostStream iocostStream = new IOCostStream(new FileStream(fileName, FileMode.Open)))
            {
                using (new FileSystemPerformanceTracker("MailboxUpload", iocostStream, this.logger))
                {
                    using (HashAlgorithm hashAlgorithm = new SHA1CryptoServiceProvider())
                    {
                        using (IStreamAttachment streamAttachment = (IStreamAttachment)attachmentCollection.CreateIAttachment(AttachmentType.Stream))
                        {
                            using (new StorePerformanceTracker("MailboxUpload", this.logger))
                            {
                                CopyStreamResult arg;
                                using (IOCostStream iocostStream2 = new IOCostStream(streamAttachment.GetContentStream()))
                                {
                                    arg = MailboxFileStore.streamCopier.CopyStream(iocostStream, iocostStream2, hashAlgorithm, abortFileOperation);
                                    iocostStream2.Flush();
                                }
                                streamAttachment[AttachmentSchema.DisplayName]        = fileName2;
                                streamAttachment[AttachmentSchema.AttachLongFileName] = fileName2;
                                streamAttachment[AttachmentSchema.AttachHash]         = hashAlgorithm.Hash;
                                streamAttachment.Save();
                                this.tracer.TraceDebug <string, CopyStreamResult>((long)this.GetHashCode(), "Uploaded file '{0}' to mailbox. {1}", fileName, arg);
                            }
                        }
                    }
                }
            }
        }
        // Token: 0x06000CFE RID: 3326 RVA: 0x00035F6C File Offset: 0x0003416C
        public Stream GetSingleFile(FileSetItem fileSetItem, string fileName, MailboxSession mailboxSession)
        {
            MemoryStream memoryStream = null;

            try
            {
                using (Item item = Item.Bind(mailboxSession, fileSetItem.Id))
                {
                    foreach (AttachmentHandle handle in item.IAttachmentCollection)
                    {
                        using (IAttachment attachment = item.IAttachmentCollection.OpenIAttachment(handle))
                        {
                            if (string.Equals(fileName, attachment[AttachmentSchema.AttachLongFileName] as string, StringComparison.OrdinalIgnoreCase))
                            {
                                IStreamAttachment attachment2 = attachment as IStreamAttachment;
                                memoryStream = new MemoryStream();
                                this.ReadAttachmentIntoStreamAndValidateHash(attachment2, new NoCloseStream(memoryStream), new Action(MailboxFileStore.NeverAbort));
                                memoryStream.Seek(0L, SeekOrigin.Begin);
                                break;
                            }
                        }
                    }
                }
            }
            catch (Exception)
            {
                if (memoryStream != null)
                {
                    memoryStream.Dispose();
                    memoryStream = null;
                }
                throw;
            }
            return(memoryStream);
        }
        // Token: 0x06000CFB RID: 3323 RVA: 0x00035C68 File Offset: 0x00033E68
        public List <string> Download(FileSetItem fileSetItem, MailboxSession mailboxSession, string tempFolderPath, bool ignoreDuplicateFiles, Action abortFileOperation)
        {
            bool   flag = false;
            string text = Path.Combine(tempFolderPath, this.folderName + Path.GetRandomFileName());

            Directory.CreateDirectory(text);
            List <string> list = new List <string>(100);
            List <string> result;

            try
            {
                this.tracer.TraceDebug <string, string, string>((long)this.GetHashCode(), "Downloading files for fileSetId='{0}' from mailbox folder '{1}' in filesystem folder {2}", fileSetItem.Name, this.folderName, text);
                Stopwatch stopwatch = Stopwatch.StartNew();
                using (Item item = Item.Bind(mailboxSession, fileSetItem.Id))
                {
                    foreach (AttachmentHandle attachmentHandle in item.IAttachmentCollection)
                    {
                        this.tracer.TraceDebug <int>((long)this.GetHashCode(), "Handling attachment id:'{0}'", attachmentHandle.AttachNumber);
                        using (IAttachment attachment = item.IAttachmentCollection.OpenIAttachment(attachmentHandle))
                        {
                            IStreamAttachment streamAttachment = attachment as IStreamAttachment;
                            if (streamAttachment != null)
                            {
                                string text2 = this.DownloadSingleFile(streamAttachment, text, ignoreDuplicateFiles, abortFileOperation);
                                if (text2 != null)
                                {
                                    this.tracer.TraceDebug <int, string>((long)this.GetHashCode(), "Successfully downloaded attachment '{0}' into file {1}", attachmentHandle.AttachNumber, text2);
                                    list.Add(text2);
                                }
                                else
                                {
                                    this.tracer.TraceError <int>((long)this.GetHashCode(), "Ignoring attachment '{0}' because could not download its content", attachmentHandle.AttachNumber);
                                }
                            }
                            else
                            {
                                this.tracer.TraceError <int>((long)this.GetHashCode(), "Ignoring attachment '{0}' because it is not stream attachment", attachmentHandle.AttachNumber);
                            }
                        }
                    }
                }
                stopwatch.Stop();
                this.tracer.TraceDebug <int, long>((long)this.GetHashCode(), "Downloaded '{0}' files. Downloaded elapsed time: {1}ms", list.Count, stopwatch.ElapsedMilliseconds);
                flag   = true;
                result = list;
            }
            finally
            {
                if (!flag || list == null || list.Count == 0)
                {
                    this.tracer.TraceDebug <string>((long)this.GetHashCode(), "Download failed and temporary folder '{0}' needs to be removed", text);
                    this.DeleteFolder(text);
                }
            }
            return(result);
        }
 internal static void CreateAttachment(IItem parentItem, Attachment16Data attachmentData)
 {
     AirSyncDiagnostics.TraceDebug <byte>(ExTraceGlobals.RequestsTracer, null, "CreateAttachment with AttachMethod:{0}", attachmentData.Method);
     if (attachmentData.Method == 1)
     {
         if (attachmentData.Content == null)
         {
             throw new ConversionException(string.Format(" Attachment content can not be null.", new object[0]));
         }
         IStreamAttachment streamAttachment = parentItem.IAttachmentCollection.CreateIAttachment(AttachmentType.Stream) as IStreamAttachment;
         AttachmentHelper.CopyCommonAttachmentProperties(streamAttachment, attachmentData);
         using (Stream contentStream = streamAttachment.GetContentStream())
         {
             contentStream.Write(attachmentData.Content, 0, attachmentData.Content.Length);
         }
         streamAttachment.Save();
     }
     else
     {
         if (attachmentData.Method != 5)
         {
             throw new ConversionException(string.Format("UnSupported Value '{0}' for Attachment Method. Only 1 & 5 is supported AttachemntType", attachmentData.Method));
         }
         ItemAttachment itemAttachment = parentItem.IAttachmentCollection.CreateIAttachment(AttachmentType.EmbeddedMessage) as ItemAttachment;
         AttachmentHelper.CopyCommonAttachmentProperties(itemAttachment, attachmentData);
         using (Stream stream = new MemoryStream(attachmentData.Content))
         {
             stream.Seek(0L, SeekOrigin.Begin);
             InboundConversionOptions inboundConversionOptions = AirSyncUtility.GetInboundConversionOptions();
             inboundConversionOptions.ClearCategories = false;
             try
             {
                 using (Item item = itemAttachment.GetItem())
                 {
                     ItemConversion.ConvertAnyMimeToItem(item, stream, inboundConversionOptions);
                     item.Save(SaveMode.NoConflictResolution);
                 }
             }
             catch (ExchangeDataException innerException)
             {
                 throw new AirSyncPermanentException(HttpStatusCode.BadRequest, StatusCode.InvalidMIME, innerException, false);
             }
             catch (ConversionFailedException innerException2)
             {
                 throw new AirSyncPermanentException(HttpStatusCode.BadRequest, StatusCode.InvalidMIME, innerException2, false);
             }
         }
         itemAttachment.Save();
     }
     AirSyncDiagnostics.TraceDebug <int>(ExTraceGlobals.RequestsTracer, null, "AttachmentHelper:CreateAttachments:: AttachmentCreated successful. AttachmentCount:{0}", parentItem.IAttachmentCollection.Count);
 }
            // Token: 0x06001AFF RID: 6911 RVA: 0x0006673C File Offset: 0x0006493C
            private void UploadAttachment(IAttachment attachment, IItem draftItem, out IAttachment newAttachment, out AttachmentId newAttachmentId)
            {
                IStreamAttachment streamAttachment = attachment as IStreamAttachment;

                if (streamAttachment == null)
                {
                    throw new InvalidOperationException("UploadAttachment requires a stream attachment, but was given a " + attachment.GetType().Name);
                }
                UploadItemAsyncResult uploadItemAsyncResult;

                using (Stream contentStream = streamAttachment.GetContentStream())
                {
                    byte[] array = new byte[contentStream.Length];
                    while (contentStream.Position != contentStream.Length)
                    {
                        int count = (int)Math.Min(4000L, contentStream.Length - contentStream.Position);
                        contentStream.Read(array, (int)contentStream.Position, count);
                    }
                    CancellationToken cancellationToken = default(CancellationToken);
                    uploadItemAsyncResult = this.provider.UploadItemSync(array, attachment.FileName, cancellationToken);
                }
                if (uploadItemAsyncResult.ResultCode != AttachmentResultCode.Success)
                {
                    throw new GetWacAttachmentInfo.AttachmentUploadException(uploadItemAsyncResult.ResultCode.ToString());
                }
                UserContext userContext = UserContextManager.GetUserContext(CallContext.Current.HttpContext, CallContext.Current.EffectiveCaller, true);

                this.ResultAttachmentWebServiceUrl = uploadItemAsyncResult.Item.ProviderEndpointUrl;
                this.ResultAttachmentProviderType  = uploadItemAsyncResult.Item.ProviderType.ToString();
                this.ResultAttachmentContentUrl    = this.provider.GetItemAbsoulteUrl(userContext, uploadItemAsyncResult.Item.Location, uploadItemAsyncResult.Item.ProviderEndpointUrl, null, null);
                this.ResultAttachmentExtension     = attachment.FileExtension;
                IReferenceAttachment referenceAttachment = (IReferenceAttachment)this.factory.CreateAttachment(draftItem, AttachmentType.Reference);

                newAttachment   = referenceAttachment;
                newAttachmentId = newAttachment.Id;
                referenceAttachment.AttachLongPathName  = this.ResultAttachmentContentUrl;
                referenceAttachment.ProviderEndpointUrl = this.ResultAttachmentWebServiceUrl;
                referenceAttachment.ProviderType        = this.ResultAttachmentProviderType;
                referenceAttachment.FileName            = attachment.FileName;
                newAttachment.IsInline = false;
                newAttachment.Save();
                draftItem.Save(SaveMode.NoConflictResolutionForceSave);
            }
        // Token: 0x06001AD7 RID: 6871 RVA: 0x00065FAC File Offset: 0x000641AC
        private static WacAttachmentType GetResultForStreamAttachment(CallContext callContext, UserContext userContext, ConfigurationContext configurationContext, AttachmentPolicy attachmentPolicy, bool isPublicLogon, string cultureName, bool isEdit, IStreamAttachment attachment, string attachmentExtension, AttachmentIdType attachmentIdType, bool isInDraft, IStoreSession storeSession, string mailboxSmtpAddress, bool isArchive)
        {
            WacFileRep  wacFileRep = GetWacAttachmentInfo.CreateWacFileRep(callContext, configurationContext, attachmentPolicy, isPublicLogon, isEdit, isArchive);
            HttpRequest request    = callContext.HttpContext.Request;
            string      text;
            string      arg;

            GetWacAttachmentInfo.GenerateWopiSrcUrl(request, wacFileRep, mailboxSmtpAddress, out text, out arg);
            if (text == null)
            {
                throw new OwaInvalidOperationException("WOPI URL is null.");
            }
            string      id                = attachmentIdType.Id;
            TokenResult oauthToken        = GetWacAttachmentInfo.GetOAuthToken(id, userContext, mailboxSmtpAddress, text);
            string      exchangeSessionId = WacUtilities.GetExchangeSessionId(oauthToken.TokenString);

            callContext.ProtocolLog.Set(GetWacAttachmentInfoMetadata.ExchangeSessionId, exchangeSessionId);
            SecurityIdentifier effectiveCallerSid = callContext.EffectiveCallerSid;

            CachedAttachmentInfo.GetInstance(mailboxSmtpAddress, id, exchangeSessionId, effectiveCallerSid, cultureName);
            string wacUrl = GetWacAttachmentInfo.GetWacUrl(isEdit, cultureName, attachmentExtension);

            if (string.IsNullOrEmpty(wacUrl))
            {
                throw new OwaInvalidRequestException(string.Format("Wac Base Url is null for this given extension {0} and culture {1}", attachmentExtension, cultureName));
            }
            new Uri(wacUrl);
            string format = "{0}WOPISrc={1}&access_token={2}";
            string arg2   = HttpUtility.UrlEncode(oauthToken.TokenString);
            string text2  = string.Format(format, wacUrl, HttpUtility.UrlEncode(text), arg2);
            string value  = string.Format(format, wacUrl, arg, arg2);

            callContext.ProtocolLog.Set(GetWacAttachmentInfoMetadata.WacUrl, value);
            if (!Uri.IsWellFormedUriString(text2, UriKind.Absolute))
            {
                throw new OwaInvalidOperationException("The WAC Iframe URL that was generated is not a well formed URI: " + text2);
            }
            return(new WacAttachmentType
            {
                AttachmentId = attachmentIdType,
                IsEdit = isEdit,
                IsInDraft = isInDraft,
                WacUrl = text2,
                Status = WacAttachmentStatus.Success
            });
        }