Ejemplo n.º 1
0
        /// <summary>
        /// 获取不同尺寸大小的图片
        /// </summary>
        /// <param name="fileRelativePath">文件的相对路径</param>
        /// <param name="filename">文件名称</param>
        /// <param name="size">图片尺寸</param>
        /// <param name="resizeMethod">图像缩放方式</param>
        /// <returns>若原图不存在,则会返回null,否则会返回缩放后的图片</returns>
        public IStoreFile GetResizedImage(string fileRelativePath, string filename, Size size, ResizeMethod resizeMethod)
        {
            string str = fileRelativePath;

            if (filename.ToLower().EndsWith(".gif"))
            {
                return(this.GetFile(str, filename));
            }
            string     sizeImageName = this.GetSizeImageName(filename, size, resizeMethod);
            IStoreFile file          = this.GetFile(str, sizeImageName);

            if (file == null)
            {
                IStoreFile storeFile = this.GetFile(str, filename);
                if (storeFile == null)
                {
                    return(null);
                }
                using (Stream stream = storeFile.OpenReadStream())
                {
                    if (stream != null)
                    {
                        using (Stream stream1 = ImageProcessor.Resize(stream, size.Width, size.Height, resizeMethod))
                        {
                            file = this.AddOrUpdateFile(str, sizeImageName, stream1);
                        }
                    }
                }
            }
            return(file);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// 获取不同尺寸大小的图片
        /// </summary>
        /// <param name="fileRelativePath">文件的相对路径</param>
        /// <param name="filename">文件名称</param>
        /// <param name="size">图片尺寸</param>
        /// <param name="resizeMethod">图像缩放方式</param>
        /// <returns>若原图不存在,则会返回null,否则会返回缩放后的图片</returns>
        public IStoreFile GetResizedImage(string fileRelativePath, string filename, Size size, ResizeMethod resizeMethod)
        {
            string relativePath = fileRelativePath;

            if (filename.ToLower().EndsWith(".gif"))
            {
                return(GetFile(relativePath, filename));;
            }

            string     sizedFileName = GetSizeImageName(filename, size, resizeMethod);
            IStoreFile file          = GetFile(relativePath, sizedFileName);

            if (file == null)
            {
                IStoreFile originalFile = GetFile(relativePath, filename);
                if (originalFile == null)
                {
                    return(null);
                }

                using (Stream originalStream = originalFile.OpenReadStream())
                {
                    if (originalStream != null)
                    {
                        using (Stream resizedStream = ImageProcessor.Resize(originalStream, size.Width, size.Height, resizeMethod))
                        {
                            file = AddOrUpdateFile(relativePath, sizedFileName, resizedStream);
                        }
                    }
                }
            }
            return(file);
        }
Ejemplo n.º 3
0
        /// <summary>
        /// 为指定用户生成指定附件的拷贝
        /// </summary>
        /// <param name="attachment">指定附件实体</param>
        /// <param name="userId">指定用户的id</param>
        /// <returns>新附件实体</returns>
        public T CloneForUser(T attachment, long userId)
        {
            //复制数据库记录
            T newAttachment = (T) new Attachment();

            newAttachment.ContentType      = attachment.ContentType;
            newAttachment.FileLength       = attachment.FileLength;
            newAttachment.FriendlyFileName = attachment.FriendlyFileName;
            newAttachment.Height           = attachment.Height;
            newAttachment.MediaType        = attachment.MediaType;
            newAttachment.OwnerId          = userId;
            newAttachment.TenantTypeId     = attachment.TenantTypeId;
            newAttachment.UserDisplayName  = userService.GetUser(userId).DisplayName;
            newAttachment.UserId           = userId;
            newAttachment.Width            = attachment.Width;
            newAttachment.FileName         = newAttachment.GenerateFileName();

            EventBus <T> .Instance().OnBefore(newAttachment, new CommonEventArgs(EventOperationType.Instance().Create()));

            attachmentRepository.Insert(newAttachment);
            EventBus <T> .Instance().OnAfter(newAttachment, new CommonEventArgs(EventOperationType.Instance().Create()));

            //复制文件
            Stream stream = null;

            try
            {
                IStoreFile file = StoreProvider.GetFile(attachment.GetRelativePath(), attachment.FileName);
                stream = file.OpenReadStream();
                StoreProvider.AddOrUpdateFile(newAttachment.GetRelativePath(), newAttachment.FileName, stream);
            }
            catch
            {
            }
            finally
            {
                if (stream != null)
                {
                    stream.Close();
                    stream.Dispose();
                }
            }

            //根据不同租户类型的设置生成不同尺寸的图片,用于图片直连访问
            if (newAttachment.MediaType == MediaType.Image)
            {
                TenantAttachmentSettings tenantAttachmentSettings = TenantAttachmentSettings.GetRegisteredSettings(newAttachment.TenantTypeId);
                if (tenantAttachmentSettings != null && tenantAttachmentSettings.ImageSizeTypes != null && tenantAttachmentSettings.ImageSizeTypes.Count > 0)
                {
                    foreach (var imageSizeType in tenantAttachmentSettings.ImageSizeTypes)
                    {
                        IStoreFile file = StoreProvider.GetResizedImage(newAttachment.GetRelativePath(), newAttachment.FileName, imageSizeType.Size, imageSizeType.ResizeMethod);
                    }
                }
            }

            return(newAttachment);
        }
Ejemplo n.º 4
0
        /// <summary>
        /// 设置不同尺寸的图片(附件中)
        /// </summary>
        /// <param name="attachment">附件</param>
        private void SetResizedAttachmentImage(Attachment attachment)
        {
            TenantAttachmentSettings tenantAttachmentSettings = TenantAttachmentSettings.GetRegisteredSettings(attachment.TenantTypeId);

            if (tenantAttachmentSettings != null && tenantAttachmentSettings.ImageSizeTypes != null && tenantAttachmentSettings.ImageSizeTypes.Count > 0)
            {
                foreach (var imageSizeType in tenantAttachmentSettings.ImageSizeTypes)
                {
                    IStoreFile file = storeProvider.GetResizedImage(attachment.GetRelativePath(), attachment.FileName, imageSizeType.Size, imageSizeType.ResizeMethod);
                }
            }
        }
Ejemplo n.º 5
0
        /// <summary>
        /// 设置不同尺寸的Logo
        /// </summary>
        /// <param name="tenantTypeId"></param>
        /// <param name="fileName"></param>
        /// <param name="relativePath"></param>
        private void SetResizedLogo(string tenantTypeId, string fileName, string relativePath)
        {
            TenantLogoSettings tenantLogoSettings = TenantLogoSettings.GetRegisteredSettings(tenantTypeId);

            if (tenantLogoSettings != null && tenantLogoSettings.ImageSizeTypes != null && tenantLogoSettings.ImageSizeTypes.Count > 0)
            {
                foreach (var imageSizeType in tenantLogoSettings.ImageSizeTypes.Values)
                {
                    string sizedFileName = storeProvider.GetSizeImageName(fileName, imageSizeType.Key, imageSizeType.Value);
                    storeProvider.DeleteFile(relativePath, sizedFileName);
                    IStoreFile file = storeProvider.GetResizedImage(relativePath, fileName, imageSizeType.Key, imageSizeType.Value);
                }
            }
        }
Ejemplo n.º 6
0
        /// <summary>
        /// 根据用户自己选择的尺寸及位置进行头像裁剪
        /// </summary>
        /// <param name="userId">用户Id</param>
        /// <param name="srcWidth">需裁剪的宽度</param>
        /// <param name="srcHeight">需裁剪的高度</param>
        /// <param name="srcX">需裁剪的左上角点坐标</param>
        /// <param name="srcY">需裁剪的左上角点坐标</param>
        public static void CropAvatar(this IUserService userService, long userId, float srcWidth, float srcHeight, float srcX, float srcY)
        {
            IStoreProvider storeProvider = DIContainer.Resolve <IStoreProvider>();
            IStoreFile     iStoreFile    = storeProvider.GetFile(GetAvatarRelativePath(userId), GetAvatarFileName(userId, AvatarSizeType.Original));

            if (iStoreFile == null)
            {
                return;
            }
            User user = GetFullUser(userService, userId);

            if (user == null)
            {
                return;
            }

            bool   isFirst            = !(user.Profile.IsUploadedAvatar);
            string avatarRelativePath = GetAvatarRelativePath(userId).Replace(Path.DirectorySeparatorChar, '/');

            avatarRelativePath = avatarRelativePath.Substring(AvatarDirectory.Length + 1);
            user.Avatar        = avatarRelativePath + "/" + userId;

            IUserRepository userRepository = userService.GetUserRepository();

            userRepository.UpdateAvatar(user, user.Avatar);

            UserProfileSettings userProfileSettings = DIContainer.Resolve <ISettingsManager <UserProfileSettings> >().Get();

            using (Stream fileStream = iStoreFile.OpenReadStream())
            {
                Stream bigImage = ImageProcessor.Crop(fileStream, new Rectangle((int)srcX, (int)srcY, (int)srcWidth, (int)srcHeight), userProfileSettings.AvatarWidth, userProfileSettings.AvatarHeight);

                Stream smallImage = ImageProcessor.Resize(bigImage, userProfileSettings.SmallAvatarWidth, userProfileSettings.SmallAvatarHeight, ResizeMethod.KeepAspectRatio);
                storeProvider.AddOrUpdateFile(GetAvatarRelativePath(userId), GetAvatarFileName(userId, AvatarSizeType.Big), bigImage);
                storeProvider.AddOrUpdateFile(GetAvatarRelativePath(userId), GetAvatarFileName(userId, AvatarSizeType.Small), smallImage);

                bigImage.Dispose();
                smallImage.Dispose();
                fileStream.Close();
            }

            //触发用户更新头像事件
            EventBus <User, CropAvatarEventArgs> .Instance().OnAfter(user, new CropAvatarEventArgs(isFirst));

            if (isFirst)
            {
                user.Profile.IsUploadedAvatar = true;
                new UserProfileService().Update(user.Profile);
            }
        }
Ejemplo n.º 7
0
        /// <summary>
        /// 获取不同尺寸的Logo
        /// </summary>
        /// <param name="associateId"></param>
        /// <param name="imageSizeTypeKey"></param>
        /// <returns></returns>
        public IStoreFile GetResizedLogo(object associateId, string imageSizeTypeKey)
        {
            IStoreFile logoFile = null;

            if (TenantLogoSettings.ImageSizeTypes == null || !TenantLogoSettings.ImageSizeTypes.ContainsKey(imageSizeTypeKey))
            {
                logoFile = GetLogo(associateId);
            }
            else
            {
                var pair = TenantLogoSettings.ImageSizeTypes[imageSizeTypeKey];
                logoFile = StoreProvider.GetResizedImage(GetLogoRelativePath(associateId), GetLogoFileName(associateId), pair.Key, pair.Value);
            }
            return(logoFile);
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Initializes a new instance of the <see cref="DataRepositoryManager"/> class.
        /// </summary>
        /// <param name="iocCommonLogging">
        /// The ioc common logging.
        /// </param>
        /// <param name="iocEventAggregator">
        /// The ioc event aggregator.
        /// </param>
        /// <param name="iocExternalStorage">
        /// The ioc external storage.
        /// </param>
        /// <param name="iocGrampsStorePostLoad">
        /// The ioc gramps store post load.
        /// </param>
        /// <param name="iocGrampsStoreSerial">
        /// The ioc gramps store serial.
        /// </param>
        /// <param name="iocStoreFile">
        /// The ioc store file.
        /// </param>
        public DataRepositoryManager(ICommonLogging iocCommonLogging, IEventAggregator iocEventAggregator, IGrampsStoreXML iocExternalStorage, IStorePostLoad iocGrampsStorePostLoad, IGrampsStoreSerial iocGrampsStoreSerial, IStoreFile iocStoreFile)
        {
            _CL = iocCommonLogging ?? throw new ArgumentNullException(nameof(iocCommonLogging));
            localExternalStorage = iocExternalStorage ?? throw new ArgumentNullException(nameof(iocExternalStorage));
            localPostLoad        = iocGrampsStorePostLoad;
            localStoreSerial     = iocGrampsStoreSerial;
            localStoreFile       = iocStoreFile;
            _EventAggregator     = iocEventAggregator;

            // Event Handlers
            //_EventAggregator.GetEvent<AppStartLoadDataEvent>().Subscribe(StartDataLoad, ThreadOption.BackgroundThread);
            _EventAggregator.GetEvent <DataLoadStartEvent>().Subscribe(StartDataLoad, ThreadOption.BackgroundThread);
            _EventAggregator.GetEvent <DataSaveSerialEvent>().Subscribe(SerializeRepositoriesAsync, ThreadOption.BackgroundThread);
            _EventAggregator.GetEvent <DataLoadCompleteEvent>().Subscribe(DataLoadedSetTrue, ThreadOption.BackgroundThread);
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Initializes a new instance of the <see cref="DataRepositoryManager"/> class.
        /// </summary>
        /// <param name="iocCommonLogging">
        /// The ioc common logging.
        /// </param>
        /// <param name="iocEventAggregator">
        /// The ioc event aggregator.
        /// </param>
        /// <param name="iocExternalStorage">
        /// The ioc external storage.
        /// </param>
        /// <param name="iocGrampsStorePostLoad">
        /// The ioc gramps store post load.
        /// </param>
        /// <param name="iocGrampsStoreSerial">
        /// The ioc gramps store serial.
        /// </param>
        /// <param name="iocStoreFile">
        /// The ioc store file.
        /// </param>
        public DataRepositoryManager(ISharedLogging iocCommonLogging, IErrorNotifications iocCommonNotifications, IMessenger iocEventAggregator, IStoreXML iocExternalStorage, IStorePostLoad iocGrampsStorePostLoad, IGrampsStoreSerial iocGrampsStoreSerial, IStoreFile iocStoreFile)
        {
            _CL = iocCommonLogging ?? throw new ArgumentNullException(nameof(iocCommonLogging));

            _ExternalStorage = iocExternalStorage ?? throw new ArgumentNullException(nameof(iocExternalStorage));

            _PostLoad            = iocGrampsStorePostLoad;
            _StoreSerial         = iocGrampsStoreSerial;
            _StoreFile           = iocStoreFile;
            _EventAggregator     = iocEventAggregator;
            _commonNotifications = iocCommonNotifications;

            // Event Handlers
            Contract.Assert(_EventAggregator != null);

            App.Current.Services.GetService <IMessenger>().Register <DataLoadStartEvent>(this, (r, m) =>
            {
                if (!m.Value)
                {
                    return;
                }

                StartDataLoad();
            });

            App.Current.Services.GetService <IMessenger>().Register <DataSaveSerialEvent>(this, (r, m) =>
            {
                if (!m.Value)
                {
                    return;
                }

                SerializeRepositoriesAsync(true);
            });

            App.Current.Services.GetService <IMessenger>().Register <DataLoadCompleteEvent>(this, (r, m) =>
            {
                if (!m.Value)
                {
                    return;
                }

                DataLoadedSetTrue();
            });
        }
Ejemplo n.º 10
0
        /// <summary>
        /// 设置不同尺寸的用户头像
        /// </summary>
        /// <param name="userId"></param>
        private void SetUserAvatars(long userId)
        {
            IStoreFile iStoreFile = storeProvider.GetFile(GetRelativePathById(userId, "Avatars"), userId + "_big.jpg");

            if (iStoreFile == null)
            {
                return;
            }
            using (Stream fileStream = iStoreFile.OpenReadStream())
            {
                Stream bigImage   = ImageProcessor.Crop(fileStream, new Rectangle(0, 0, 160, 160), 160, 160);
                Stream smallImage = ImageProcessor.Resize(bigImage, 50, 50, ResizeMethod.KeepAspectRatio);
                storeProvider.AddOrUpdateFile(GetRelativePathById(userId, "Avatars"), userId + ".jpg", smallImage);

                bigImage.Dispose();
                smallImage.Dispose();
                fileStream.Close();
            }
        }
Ejemplo n.º 11
0
        /// <summary>
        /// 获取照片的EXIF数据
        /// </summary>
        /// <param name="photoId">照片id</param>
        /// <returns>返回照片的EXIF数据</returns>
        public Dictionary <int, string> GetPhotoEXIFMetaData(long photoId)
        {
            Dictionary <int, string> EXIFMetaData = new Dictionary <int, string>();
            Photo photo = this.GetPhoto(photoId);

            if (photo == null || string.IsNullOrEmpty(photo.RelativePath) || (!photo.RelativePath.ToLower().EndsWith(".jpg") && !photo.RelativePath.ToLower().EndsWith(".jpeg")))
            {
                return(EXIFMetaData);
            }
            TenantAttachmentSettings tenantAttachmentSettings = TenantAttachmentSettings.GetRegisteredSettings(TenantTypeIds.Instance().Photo());
            IStoreProvider           storeProvider            = DIContainer.ResolveNamed <IStoreProvider>(tenantAttachmentSettings.StoreProviderName);
            IStoreFile file = storeProvider.GetFile(photo.RelativePath, "");

            if (file != null)
            {
                using (Stream stream = file.OpenReadStream())
                {
                    EXIFMetaData = new EXIFMetaDataService().Read(stream);
                }
            }

            return(EXIFMetaData);
        }
Ejemplo n.º 12
0
        /// <summary>
        /// 上传Logo
        /// </summary>
        /// <param name="associateId"></param>
        /// <param name="stream"></param>
        /// <returns>上传文件的相对路径(包含文件名)</returns>
        public string UploadLogo(object associateId, Stream stream)
        {
            string relativeFileName = string.Empty;

            if (stream != null)
            {
                ILogoSettingsManager logoSettingsManager = DIContainer.Resolve <ILogoSettingsManager>();
                LogoSettings         logoSettings        = logoSettingsManager.Get();

                //检查是否需要缩放原图
                Image image = Image.FromStream(stream);
                if (image.Height > this.TenantLogoSettings.MaxHeight || image.Width > this.TenantLogoSettings.MaxWidth)
                {
                    stream = ImageProcessor.Resize(stream, this.TenantLogoSettings.MaxWidth, this.TenantLogoSettings.MaxHeight, logoSettings.ResizeMethod);
                }

                string relativePath = GetLogoRelativePath(associateId);
                string fileName     = GetLogoFileName(associateId);
                relativeFileName = relativePath + "\\" + fileName;

                StoreProvider.AddOrUpdateFile(relativePath, fileName, stream);
                stream.Dispose();

                //根据不同租户类型的设置生成不同尺寸的图片,用于图片直连访问
                if (this.TenantLogoSettings.ImageSizeTypes != null && this.TenantLogoSettings.ImageSizeTypes.Count > 0)
                {
                    foreach (var imageSizeType in this.TenantLogoSettings.ImageSizeTypes.Values)
                    {
                        string sizedFileName = StoreProvider.GetSizeImageName(fileName, imageSizeType.Key, imageSizeType.Value);
                        StoreProvider.DeleteFile(relativePath, sizedFileName);
                        IStoreFile file = StoreProvider.GetResizedImage(relativePath, fileName, imageSizeType.Key, imageSizeType.Value);
                    }
                }
            }

            return(relativeFileName);
        }
Ejemplo n.º 13
0
        /// <summary>
        /// 升级照片附件
        /// </summary>
        /// <returns></returns>
        private bool UpdatePhotoBySQL(out string message)
        {
            SqlConnection sqlConnection = GetConnection();
            List <long>   photoIds      = new List <long>();
            List <long>   albumIds      = new List <long>();
            Dictionary <long, List <long> > photosInAlbum = new Dictionary <long, List <long> >();

            Directory.SetCurrentDirectory(currentDirectory);
            int           allCount       = 0;
            int           moveCount      = 0;
            bool          result         = false;
            StringBuilder messageBuilder = new StringBuilder();

            try
            {
                sqlConnection.Open();
                SqlCommand    selectCommand = new SqlCommand("select PhotoId,AlbumId from spb_Photos", sqlConnection);
                SqlDataReader dr            = selectCommand.ExecuteReader(CommandBehavior.CloseConnection);
                while (dr.Read())
                {
                    photoIds.Add(dr.GetInt64(0));
                    albumIds.Add(dr.GetInt64(1));
                    if (!photosInAlbum.ContainsKey(dr.GetInt64(1)))
                    {
                        photosInAlbum[dr.GetInt64(1)] = new List <long>();
                    }
                    photosInAlbum[dr.GetInt64(1)].Add(dr.GetInt64(0));
                }
                dr.Close();
                sqlConnection.Close();

                foreach (var albumId in albumIds)
                {
                    string newPhotoRelatedPath = GetRelativePathById(albumId, "Photo");
                    if (!Directory.Exists(newPhotoRelatedPath))
                    {
                        Directory.CreateDirectory(newPhotoRelatedPath);
                    }

                    foreach (var photoId in photosInAlbum[albumId])
                    {
                        string oldPhotoRelatedPath = Path.Combine(currentDirectory, GetOldRelativePath("Galleries", photoId));
                        if (!Directory.Exists(oldPhotoRelatedPath))
                        {
                            continue;
                        }
                        foreach (var photoFilePath in Directory.GetFiles(oldPhotoRelatedPath))
                        {
                            allCount++;
                            FileInfo oldFileInfo      = new FileInfo(photoFilePath);
                            string   newPhotoFilePath = Path.Combine(currentDirectory, newPhotoRelatedPath, oldFileInfo.Name);
                            if (!System.IO.File.Exists(newPhotoFilePath))
                            {
                                System.IO.File.Move(photoFilePath, newPhotoFilePath);
                                moveCount++;
                                string tenantTypeId = "100302";
                                TenantAttachmentSettings tenantAttachmentSettings = TenantAttachmentSettings.GetRegisteredSettings(tenantTypeId);
                                if (tenantAttachmentSettings != null && tenantAttachmentSettings.ImageSizeTypes != null && tenantAttachmentSettings.ImageSizeTypes.Count > 0)
                                {
                                    foreach (var imageSizeType in tenantAttachmentSettings.ImageSizeTypes)
                                    {
                                        IStoreFile file = storeProvider.GetResizedImage(newPhotoRelatedPath, oldFileInfo.Name, imageSizeType.Size, imageSizeType.ResizeMethod);
                                    }
                                }
                            }
                            break;
                        }
                    }
                }
            }
            catch (Exception e)
            {
                sqlConnection.Close();
            }

            messageBuilder.AppendFormat("{0}:一共找到{1}个可以升级的照片", storeProvider.JoinDirectory("Old", "Galleries"), allCount);
            if (moveCount > 0)
            {
                result = true;
                messageBuilder.AppendFormat(",成功升级了{0}个照片", moveCount);
            }
            message = messageBuilder.ToString();
            return(result);
        }
Ejemplo n.º 14
0
        public override void ProcessRequest(HttpContext context)
        {
            long attachmentId = context.Request.QueryString.Get <long>("attachmentId", 0);

            if (attachmentId <= 0)
            {
                WebUtility.Return404(context);
                return;
            }

            string tenantTypeId = context.Request.QueryString.GetString("tenantTypeId", string.Empty);

            if (string.IsNullOrEmpty(tenantTypeId))
            {
                WebUtility.Return404(context);
                return;
            }

            //检查链接是否过期
            string token               = context.Request.QueryString.GetString("token", string.Empty);
            bool   isTimeout           = true;
            long   attachmentIdInToken = Utility.DecryptTokenForAttachmentDownload(token, out isTimeout);

            if (isTimeout || attachmentIdInToken != attachmentId)
            {
                WebUtility.Return403(context);
                return;
            }

            AttachmentService <Attachment> attachmentService = new AttachmentService <Attachment>(tenantTypeId);
            Attachment attachment = attachmentService.Get(attachmentId);

            if (attachment == null)
            {
                WebUtility.Return404(context);
                return;
            }

            bool     enableCaching = context.Request.QueryString.GetBool("enableCaching", true);
            DateTime lastModified  = attachment.DateCreated.ToUniversalTime();

            if (enableCaching && IsCacheOK(context, lastModified))
            {
                WebUtility.Return304(context);
                return;
            }

            //输出文件流
            IStoreFile storeFile = storeProvider.GetFile(attachment.GetRelativePath(), attachment.FileName);

            if (storeFile == null)
            {
                WebUtility.Return404(context);
                return;
            }

            context.Response.Clear();
            //context.Response.ClearHeaders();
            //context.Response.Cache.VaryByParams["attachmentId"] = true;
            string fileExtension    = attachment.FileName.Substring(attachment.FileName.LastIndexOf('.') + 1);
            string friendlyFileName = attachment.FriendlyFileName + (attachment.FriendlyFileName.EndsWith(fileExtension) ? "" : "." + fileExtension);

            SetResponsesDetails(context, attachment.ContentType, friendlyFileName, lastModified);

            DefaultStoreFile fileSystemFile = storeFile as DefaultStoreFile;

            if (!fileSystemFile.FullLocalPath.StartsWith(@"\"))
            {
                //本地文件下载
                context.Response.TransmitFile(fileSystemFile.FullLocalPath);
                context.Response.End();
            }
            else
            {
                context.Response.AddHeader("Content-Length", storeFile.Size.ToString("0"));
                context.Response.Buffer       = false;
                context.Response.BufferOutput = false;

                using (Stream stream = fileSystemFile.OpenReadStream())
                {
                    if (stream == null)
                    {
                        WebUtility.Return404(context);
                        return;
                    }
                    long   bufferLength = fileSystemFile.Size <= DownloadFileHandlerBase.BufferLength ? fileSystemFile.Size : DownloadFileHandlerBase.BufferLength;
                    byte[] buffer       = new byte[bufferLength];

                    int readedSize;
                    while ((readedSize = stream.Read(buffer, 0, (int)bufferLength)) > 0 && context.Response.IsClientConnected)
                    {
                        context.Response.OutputStream.Write(buffer, 0, readedSize);
                        context.Response.Flush();
                    }

                    //context.Response.OutputStream.Flush();
                    //context.Response.Flush();
                    stream.Close();
                }
                context.Response.End();
            }
        }
Ejemplo n.º 15
0
        public static void setupMocks()
        {
            /*
             * Mock Common Logging
             */
            ISharedLogging iocCommonLogging = new SharedLogging();

            /*
             * Mock Common Notifications
             */
            Mock <IErrorNotifications> mockCommonNotifications = new Mock <IErrorNotifications>();

            mockCommonNotifications
            .Setup(x => x.DataLogEntryAdd(It.IsAny <string>()));

            iocCommonNotifications = mockCommonNotifications.Object;

            /*
             * Mock Image Loading
             */
            Mock <IFFImageLoading> mocFFImageLoading = new Mock <IFFImageLoading>();
            IFFImageLoading        iocFFImageLoading = mocFFImageLoading.Object;

            /*
             * Mock Xamarin Essentials
             */
            Mock <IXamarinEssentials> mocXamarinEssentials = new Mock <IXamarinEssentials>();

            mocXamarinEssentials
            .Setup(x => x.FileSystemCacheDirectory)
            .Returns(Path.GetTempPath());

            IXamarinEssentials iocXamarinEssentials = mocXamarinEssentials.Object;

            /*
             * Mock Event Aggregator
             */
            Mock <DataLoadXMLEvent> mockedEventDataLoadXMLEvent = new Mock <DataLoadXMLEvent>();

            // TODO fix this

            //mocEventAggregator
            //      .Setup(x => x.Register<DataLoadXMLEvent>())
            //          .Returns(mockedEventDataLoadXMLEvent.Object);

            //Mock<DataLoadStartEvent> mockedEventDataLoadStartEvent = new Mock<DataLoadStartEvent>();
            //mocEventAggregator
            //      .Setup(x => x.GetEvent<DataLoadStartEvent>())
            //          .Returns(mockedEventDataLoadStartEvent.Object);

            //Mock<DataSaveSerialEvent> mockedEventDataSaveSerialEvent = new Mock<DataSaveSerialEvent>();
            //mocEventAggregator
            //    .Setup(x => x.GetEvent<DataSaveSerialEvent>())
            //        .Returns(mockedEventDataSaveSerialEvent.Object);

            //Mock<DataLoadCompleteEvent> mockedEventDataLoadCompleteEvent = new Mock<DataLoadCompleteEvent>();
            //mocEventAggregator
            //    .Setup(x => x.GetEvent<DataLoadCompleteEvent>())
            //        .Returns(mockedEventDataLoadCompleteEvent.Object);

            IMessenger iocEventAggregator = mocEventAggregator.Object;

            /*
             * Mock Platform specific
             */
            iocPlatformSpecific = mocPlatformSpecific.Object;

            /*
             * Configure DataStore
             */
            DataStore.Instance.ES   = iocXamarinEssentials;
            DataStore.Instance.FFIL = iocFFImageLoading;

            /*
             * Other setup
             */
            iocExternalStorage = new StoreXML(iocCommonLogging, iocCommonNotifications);

            iocGrampsStorePostLoad = new StorePostLoad(iocCommonLogging, iocCommonNotifications, iocEventAggregator);

            iocGrampsStoreSerial = new GrampsStoreSerial(iocCommonLogging);

            iocStoreFile = new StoreFile();

            newManager = new DataRepositoryManager(iocCommonLogging, iocCommonNotifications, iocEventAggregator, iocExternalStorage, iocGrampsStorePostLoad, iocGrampsStoreSerial, iocStoreFile);
        }
        public ActionResult Create(string spaceKey, string microblogBody, string tenantTypeId = null, long ownerId = 0, string imageUrl = null)
        {
            if (string.IsNullOrEmpty(microblogBody))
            {
                return(Json(new { MessageType = StatusMessageType.Error, MessageContent = "内容不能为空!" }));
            }
            if (!ValidateContentLength(microblogBody))
            {
                return(Json(new { MessageType = StatusMessageType.Error, MessageContent = "内容不能超过140个字!" }));
            }

            //当前用户登录
            IUser currentUser = UserContext.CurrentUser;

            bool            isBanned = ModelState.HasBannedWord();
            MicroblogEntity entity   = MicroblogEntity.New();

            entity.Author       = currentUser.DisplayName;
            entity.Body         = Tunynet.Utilities.WebUtility.HtmlEncode(microblogBody);
            entity.PostWay      = PostWay.Web;
            entity.TenantTypeId = !string.IsNullOrEmpty(tenantTypeId) ? tenantTypeId : TenantTypeIds.Instance().User();
            entity.UserId       = currentUser.UserId;
            entity.OwnerId      = ownerId > 0 ? ownerId : currentUser.UserId;

            if (!authorizer.Microblog_Create(entity.TenantTypeId, entity.OwnerId))
            {
                return(HttpNotFound());
            }

            //判断是否当前有,图片附件
            HttpCookie cookie = Request.Cookies["microblog_PhotoExists"];

            if (cookie != null && cookie.Value.Trim().ToLower().Equals("true"))
            {
                entity.HasPhoto = true;
                cookie.Value    = "";
                Response.Cookies.Set(cookie);
            }

            if (!string.IsNullOrEmpty(imageUrl))
            {
                //by zhaoyx:获取到的图片地址如果带有“-”字符的话,会被ModelBinder屏蔽掉,导致图片无法加载
                imageUrl        = Request["imageUrl"];
                entity.HasPhoto = true;
            }

            bool isSuccess = false;

            if (!isBanned)
            {
                isSuccess = microblogService.Create(entity) > 0;
            }

            //by zhengw:
            if (isSuccess)
            {
                //处理imageUrl
                if (!string.IsNullOrEmpty(imageUrl))
                {
                    DownloadRemoteImage(imageUrl, entity.MicroblogId);
                }

                //同步微博
                var accountBindingService = new AccountBindingService();
                foreach (var accountType in accountBindingService.GetAccountTypes(true, true))
                {
                    bool isSync = Request.Form.GetBool("sync_" + accountType.AccountTypeKey, false);
                    if (isSync)
                    {
                        var account = accountBindingService.GetAccountBinding(currentUser.UserId, accountType.AccountTypeKey);
                        if (account != null)
                        {
                            var thirdAccountGetter = ThirdAccountGetterFactory.GetThirdAccountGetter(accountType.AccountTypeKey);
                            if (entity.HasPhoto)
                            {
                                byte[] bytes       = null;
                                var    attachments = attachmentService.GetsByAssociateId(entity.MicroblogId);
                                string fileName    = null;
                                if (attachments.Count() > 0)
                                {
                                    var            attachment    = attachments.First();
                                    IStoreProvider storeProvider = DIContainer.Resolve <IStoreProvider>();
                                    IStoreFile     storeFile     = storeProvider.GetResizedImage(attachment.GetRelativePath(), attachment.FileName, new Size(405, 600), Tunynet.Imaging.ResizeMethod.KeepAspectRatio);
                                    using (Stream stream = storeFile.OpenReadStream())
                                    {
                                        bytes = StreamToBytes(stream);
                                        stream.Dispose();
                                        stream.Close();
                                    }
                                    fileName = attachment.FriendlyFileName;
                                }
                                thirdAccountGetter.CreatePhotoMicroBlog(account.AccessToken, microblogBody, bytes, fileName, account.Identification);
                            }
                            else
                            {
                                thirdAccountGetter.CreateMicroBlog(account.AccessToken, microblogBody, account.Identification);
                            }
                        }
                    }
                }
                if ((int)entity.AuditStatus > (int)(new AuditService().GetPubliclyAuditStatus(MicroblogConfig.Instance().ApplicationId)))
                {
                    return(Json(new { MessageType = StatusMessageType.Success, MessageContent = "发布成功", id = entity.MicroblogId }));
                }
                else
                {
                    return(Json(new { MessageType = StatusMessageType.Hint, MessageContent = "尚未通过审核,请耐心等待", id = entity.MicroblogId }));
                }
            }

            if (isBanned)
            {
                return(Json(new { MessageType = StatusMessageType.Error, MessageContent = "内容中有非法词语!" }));
            }
            else
            {
                return(Json(new { MessageType = StatusMessageType.Error, MessageContent = "创建失败请联系管理员!" }));
            }
        }
Ejemplo n.º 17
0
 public static void Register(IStoreFile file, IFolder folder)
 {
     StoreFile = file;
     Folder    = folder;
 }