Beispiel #1
0
        public ActionResult Upload(int id, string content, int width, int height)
        {
            var media = Services.ContentManager.Get(id).As <MediaPart>();

            if (media == null)
            {
                return(HttpNotFound());
            }

            const string signature = "data:image/jpeg;base64,";

            if (!content.StartsWith(signature, StringComparison.OrdinalIgnoreCase))
            {
                return(HttpNotFound());
            }

            var image = media.As <ImagePart>();

            content = content.Substring(signature.Length);

            var buffer = Convert.FromBase64String(content);

            _mediaLibraryService.DeleteFile(media.FolderPath, media.FileName);

            using (var stream = new MemoryStream(buffer)) {
                _mediaLibraryService.UploadMediaFile(media.FolderPath, media.FileName, stream);
            }

            image.Width    = width;
            image.Height   = height;
            media.MimeType = "image/png";

            return(Json(true));
        }
        public ActionResult Upload(int id, string content, int width, int height)
        {
            if (!Services.Authorizer.Authorize(Permissions.ManageOwnMedia))
            {
                return(new HttpUnauthorizedResult());
            }

            var media = Services.ContentManager.Get(id).As <MediaPart>();

            if (media == null)
            {
                return(HttpNotFound());
            }

            // Check permission.
            var rootMediaFolder = _mediaLibraryService.GetRootMediaFolder();

            if (!Services.Authorizer.Authorize(Permissions.ImportMediaContent) && !_mediaLibraryService.CanManageMediaFolder(media.FolderPath))
            {
                return(new HttpUnauthorizedResult());
            }

            const string signature = "data:image/jpeg;base64,";

            if (!content.StartsWith(signature, StringComparison.OrdinalIgnoreCase))
            {
                return(HttpNotFound());
            }

            var settings = Services.WorkContext.CurrentSite.As <MediaLibrarySettingsPart>();

            // skip file if the allowed extensions is defined and doesn't match
            if (!settings.IsFileAllowed(Path.GetFileName(media.FileName)))
            {
                return(Json(false));
            }

            var image = media.As <ImagePart>();

            content = content.Substring(signature.Length);

            var buffer = Convert.FromBase64String(content);

            _mediaLibraryService.DeleteFile(media.FolderPath, media.FileName);

            using (var stream = new MemoryStream(buffer)) {
                _mediaLibraryService.UploadMediaFile(media.FolderPath, media.FileName, stream);
            }

            image.Width    = width;
            image.Height   = height;
            media.MimeType = "image/png";

            return(Json(true));
        }
        private XRpcStruct MetaWeblogNewMediaObject(
            string userName,
            string password,
            XRpcStruct file,
            UrlHelper url)
        {
            List <LocalizedString> validationErrors;
            var user = _membershipService.ValidateUser(userName, password, out validationErrors);

            if (!_authorizationService.TryCheckAccess(Permissions.ManageOwnMedia, user, null) &&
                !_authorizationService.TryCheckAccess(Permissions.EditMediaContent, user, null))
            {
                throw new OrchardCoreException(T("Access denied"));
            }

            var name = file.Optional <string>("name");
            var bits = file.Optional <byte[]>("bits");

            string directoryName = Path.GetDirectoryName(name);

            if (string.IsNullOrWhiteSpace(directoryName))   // Some clients only pass in a name path that does not contain a directory component.
            {
                directoryName = "media";
            }

            // If the user only has access to his own folder, rewrite the folder name
            if (!_authorizationService.TryCheckAccess(Permissions.EditMediaContent, user, null))
            {
                directoryName = Path.Combine(_mediaLibraryService.GetRootedFolderPath(directoryName));
            }

            try {
                // delete the file if it already exists, e.g. an updated image in a blog post
                // it's safe to delete the file as each content item gets a specific folder
                _mediaLibraryService.DeleteFile(directoryName, Path.GetFileName(name));
            }
            catch {
                // current way to delete a file if it exists
            }

            string publicUrl = _mediaLibraryService.UploadMediaFile(directoryName, Path.GetFileName(name), bits);
            var    mediaPart = _mediaLibraryService.ImportMedia(directoryName, Path.GetFileName(name));

            try {
                _contentManager.Create(mediaPart);
            }
            catch {
            }

            return(new XRpcStruct() // Some clients require all optional attributes to be declared Wordpress responds in this way as well.
                   .Set("file", publicUrl)
                   .Set("url", url.MakeAbsolute(publicUrl))
                   .Set("type", file.Optional <string>("type")));
        }
Beispiel #4
0
        public void AddImage(string imageGalleryName, string fileName, Stream imageFile)
        {
            if (!IsFileAllowed(fileName, true))
            {
                throw new InvalidOperationException(string.Format("{0} is not a valid file.", fileName));
            }

            // Zip file processing is different from Media module since we want the folders structure to be flattened
            if (IsZipFile(Path.GetExtension(fileName)))
            {
                UnzipMediaFileArchive(imageGalleryName, imageFile);
            }
            else
            {
                _mediaService.UploadMediaFile(GetMediaPath(imageGalleryName), fileName, imageFile);
            }
        }
Beispiel #5
0
        public override void Validating(FormValidatingEventContext context)
        {
            foreach (var element in context.Form.Elements.Flatten())
            {
                var fileFieldElement = element as FileField;
                if (fileFieldElement == null)
                {
                    continue;
                }

                var postedFileValue = context.ValueProvider.GetValue(fileFieldElement.Name);
                if (postedFileValue == null)
                {
                    continue;
                }

                var postedFiles = (HttpPostedFileBase[])postedFileValue.RawValue;
                if (postedFiles == null && postedFiles.Length != 1)
                {
                    continue;
                }

                var filePath = context.Values[fileFieldElement.Name];
                if (string.IsNullOrWhiteSpace(filePath))
                {
                    continue;
                }

                try
                {
                    _mediaLibraryService.UploadMediaFile(
                        Path.GetDirectoryName(filePath),
                        Path.GetFileName(filePath),
                        postedFiles[0].InputStream);
                }
                catch
                {
                    context.ModelState.AddModelError(fileFieldElement.Name, "Error Saving File");
                }
            }
        }
Beispiel #6
0
        public ActionResult Replace(int replaceId, string type, string url)
        {
            if (!Services.Authorizer.Authorize(Permissions.ManageOwnMedia))
            {
                return(new HttpUnauthorizedResult());
            }

            var replaceMedia = Services.ContentManager.Get <MediaPart>(replaceId);

            if (replaceMedia == null)
            {
                return(HttpNotFound());
            }

            // Check permission
            if (!Services.Authorizer.Authorize(Permissions.ManageMediaContent) && !_mediaLibraryService.CanManageMediaFolder(replaceMedia.FolderPath))
            {
                return(new HttpUnauthorizedResult());
            }

            var settings          = Services.WorkContext.CurrentSite.As <MediaLibrarySettingsPart>();
            var allowedExtensions = (settings.UploadAllowedFileTypeWhitelist ?? "")
                                    .Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
                                    .Where(x => x.StartsWith("."));

            try {
                var filename = Path.GetFileName(url);

                // skip file if the allowed extensions is defined and doesn't match
                if (allowedExtensions.Any())
                {
                    if (!allowedExtensions.Any(e => filename.EndsWith(e, StringComparison.OrdinalIgnoreCase)))
                    {
                        throw new Exception(T("This file type is not allowed: {0}", Path.GetExtension(filename)).Text);
                    }
                }

                var buffer = new WebClient().DownloadData(url);
                var stream = new MemoryStream(buffer);

                var mimeType = _mimeTypeProvider.GetMimeType(filename);

                string replaceContentType = _mediaLibraryService.MimeTypeToContentType(stream, mimeType, type) ?? type;
                if (!replaceContentType.Equals(replaceMedia.TypeDefinition.Name, StringComparison.OrdinalIgnoreCase))
                {
                    throw new Exception(T("Cannot replace {0} with {1}", replaceMedia.TypeDefinition.Name, replaceContentType).Text);
                }

                _mediaLibraryService.DeleteFile(replaceMedia.FolderPath, replaceMedia.FileName);
                _mediaLibraryService.UploadMediaFile(replaceMedia.FolderPath, replaceMedia.FileName, stream);
                replaceMedia.MimeType = mimeType;

                // Force a publish event which will update relevant Media properties
                replaceMedia.ContentItem.VersionRecord.Published = false;
                Services.ContentManager.Publish(replaceMedia.ContentItem);

                return(new JsonResult {
                    Data = new { replaceMedia.FolderPath, MediaPath = replaceMedia.FileName }
                });
            }
            catch (Exception e) {
                return(new JsonResult {
                    Data = new { Success = false, error = e.Message }
                });
            }
        }
        public ActionResult Replace(int replaceId, string type)
        {
            if (!Services.Authorizer.Authorize(om.Permissions.ManageOwnMedia))
            {
                return(new HttpUnauthorizedResult());
            }

            var replaceMedia = Services.ContentManager.Get <MediaPart>(replaceId);

            if (replaceMedia == null)
            {
                return(HttpNotFound());
            }

            // Check permission
            if (!(_mediaLibraryService.CheckMediaFolderPermission(om.Permissions.EditMediaContent, replaceMedia.FolderPath) && _mediaLibraryService.CheckMediaFolderPermission(om.Permissions.ImportMediaContent, replaceMedia.FolderPath)) &&
                !_mediaLibraryService.CanManageMediaFolder(replaceMedia.FolderPath))
            {
                return(new HttpUnauthorizedResult());
            }

            var statuses = new List <object>();

            var settings = Services.WorkContext.CurrentSite.As <MediaLibrarySettingsPart>();

            // Loop through each file in the request
            for (int i = 0; i < HttpContext.Request.Files.Count; i++)
            {
                // Pointer to file
                var file     = HttpContext.Request.Files[i];
                var filename = Path.GetFileName(file.FileName);

                // if the file has been pasted, provide a default name
                if (file.ContentType.Equals("image/png", StringComparison.InvariantCultureIgnoreCase) && !filename.EndsWith(".png", StringComparison.InvariantCultureIgnoreCase))
                {
                    filename = "clipboard.png";
                }

                // skip file if the allowed extensions is defined and doesn't match
                if (!settings.IsFileAllowed(filename))
                {
                    statuses.Add(new
                    {
                        error    = T("This file is not allowed: {0}", filename).Text,
                        progress = 1.0,
                    });
                    continue;
                }

                try
                {
                    var mimeType = _mimeTypeProvider.GetMimeType(filename);

                    string replaceContentType = _mediaLibraryService.MimeTypeToContentType(file.InputStream, mimeType, type) ?? type;
                    if (!replaceContentType.Equals(replaceMedia.TypeDefinition.Name, StringComparison.OrdinalIgnoreCase))
                    {
                        throw new Exception(T("Cannot replace {0} with {1}", replaceMedia.TypeDefinition.Name, replaceContentType).Text);
                    }

                    var mediaItemsUsingTheFile = Services.ContentManager.Query <MediaPart, MediaPartRecord>()
                                                 .ForVersion(VersionOptions.Latest)
                                                 .Where(x => x.FolderPath == replaceMedia.FolderPath && x.FileName == replaceMedia.FileName)
                                                 .Count();
                    if (mediaItemsUsingTheFile == 1)
                    { // if the file is referenced only by the deleted media content, the file too can be removed.
                        _mediaLibraryService.DeleteFile(replaceMedia.FolderPath, replaceMedia.FileName);
                    }
                    else
                    {
                        // it changes the media file name
                        replaceMedia.FileName = filename;
                    }
                    _mediaLibraryService.UploadMediaFile(replaceMedia.FolderPath, replaceMedia.FileName, file.InputStream);
                    replaceMedia.MimeType = mimeType;

                    // Force a publish event which will update relevant Media properties
                    replaceMedia.ContentItem.VersionRecord.Published = false;
                    Services.ContentManager.Publish(replaceMedia.ContentItem);

                    statuses.Add(new
                    {
                        id       = replaceMedia.Id,
                        name     = replaceMedia.Title,
                        type     = replaceMedia.MimeType,
                        size     = file.ContentLength,
                        progress = 1.0,
                        url      = replaceMedia.FileName,
                    });
                }
                catch (Exception ex)
                {
                    Logger.Error(ex, "Unexpected exception when uploading a media.");

                    statuses.Add(new
                    {
                        error    = T(ex.Message).Text,
                        progress = 1.0,
                    });
                }
            }

            return(Json(statuses, JsonRequestBehavior.AllowGet));
        }
        public ActionResult Replace(int replaceId, string type)
        {
            if (!Services.Authorizer.Authorize(Permissions.ManageOwnMedia))
            {
                return(new HttpUnauthorizedResult());
            }

            var replaceMedia = Services.ContentManager.Get <MediaPart>(replaceId);

            if (replaceMedia == null)
            {
                return(HttpNotFound());
            }

            // Check permission
            if (!Services.Authorizer.Authorize(Permissions.ManageMediaContent) && !_mediaLibraryService.CanManageMediaFolder(replaceMedia.FolderPath))
            {
                return(new HttpUnauthorizedResult());
            }

            var statuses = new List <object>();

            var settings          = Services.WorkContext.CurrentSite.As <MediaLibrarySettingsPart>();
            var allowedExtensions = (settings.UploadAllowedFileTypeWhitelist ?? "")
                                    .Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
                                    .Where(x => x.StartsWith("."));

            // Loop through each file in the request
            for (int i = 0; i < HttpContext.Request.Files.Count; i++)
            {
                // Pointer to file
                var file     = HttpContext.Request.Files[i];
                var filename = Path.GetFileName(file.FileName);

                // if the file has been pasted, provide a default name
                if (file.ContentType.Equals("image/png", StringComparison.InvariantCultureIgnoreCase) && !filename.EndsWith(".png", StringComparison.InvariantCultureIgnoreCase))
                {
                    filename = "clipboard.png";
                }

                // skip file if the allowed extensions is defined and doesn't match
                if (allowedExtensions.Any())
                {
                    if (!allowedExtensions.Any(e => filename.EndsWith(e, StringComparison.OrdinalIgnoreCase)))
                    {
                        statuses.Add(new {
                            error    = T("This file type is not allowed: {0}", Path.GetExtension(filename)).Text,
                            progress = 1.0,
                        });
                        continue;
                    }
                }

                try {
                    var mimeType = _mimeTypeProvider.GetMimeType(filename);

                    string replaceContentType = _mediaLibraryService.MimeTypeToContentType(file.InputStream, mimeType, type) ?? type;
                    if (!replaceContentType.Equals(replaceMedia.TypeDefinition.Name, StringComparison.OrdinalIgnoreCase))
                    {
                        throw new Exception(T("Cannot replace {0} with {1}", replaceMedia.TypeDefinition.Name, replaceContentType).Text);
                    }

                    _mediaLibraryService.DeleteFile(replaceMedia.FolderPath, replaceMedia.FileName);
                    _mediaLibraryService.UploadMediaFile(replaceMedia.FolderPath, replaceMedia.FileName, file.InputStream);
                    replaceMedia.MimeType = mimeType;

                    // Force a publish event which will update relevant Media properties
                    replaceMedia.ContentItem.VersionRecord.Published = false;
                    Services.ContentManager.Publish(replaceMedia.ContentItem);

                    statuses.Add(new {
                        id       = replaceMedia.Id,
                        name     = replaceMedia.Title,
                        type     = replaceMedia.MimeType,
                        size     = file.ContentLength,
                        progress = 1.0,
                        url      = replaceMedia.FileName,
                    });
                }
                catch (Exception ex) {
                    Logger.Error(ex, "Unexpected exception when uploading a media.");

                    statuses.Add(new {
                        error    = T(ex.Message).Text,
                        progress = 1.0,
                    });
                }
            }

            return(Json(statuses, JsonRequestBehavior.AllowGet));
        }