// Newly added files
        private async Task MoveNewFilesToContentItemDirAndUpdatePathsAsync(List <EditMediaFieldItemInfo> items, ContentItem contentItem)
        {
            foreach (var item in items.Where(i => !i.IsRemoved && !String.IsNullOrEmpty(i.Path)))
            {
                var fileInfo = await _fileStore.GetFileInfoAsync(item.Path);

                if (fileInfo == null)
                {
                    _logger.LogError("A file with the path '{Path}' does not exist.", item.Path);
                    return;
                }

                var targetDir     = GetContentItemFolder(contentItem);
                var finalFileName = (await GetFileHashAsync(item.Path)) + GetFileExtension(item.Path);
                var finalFilePath = _fileStore.Combine(targetDir, finalFileName);

                await _fileStore.TryCreateDirectoryAsync(targetDir);

                // When there is a validation error before creating the content item we can end up with an empty folder
                // because the content item is different on each form submit . We need to remove that empty folder.
                var previousDirPath = fileInfo.DirectoryPath;

                // fileName is a hash of the file. We preserve disk space by reusing the file.
                if (await _fileStore.GetFileInfoAsync(finalFilePath) == null)
                {
                    await _fileStore.MoveFileAsync(item.Path, finalFilePath);
                }

                item.Path = finalFilePath;

                await DeleteDirIfEmptyAsync(previousDirPath);
            }
        }
        // This action will demonstrate how to create a file in the Media folder and read it from there.
        public async Task <string> CreateFileInMediaFolder()
        {
            // You need to initialize a stream if you have a specific text you want to write into the file. If you
            // already have a stream for that just use it (you'll see it later)!
            using (var stream = new MemoryStream(Encoding.UTF8.GetBytes("Hi there!")))
            {
                // The third parameter here is optional - if true, it will override the file if already exists.
                await _mediaFileStore.CreateFileFromStreamAsync(TestFileRelativePath, stream, true);
            }

            // Use this method to check if the file exists (it will be null if the file doesn't exist). It's similar to
            // the built-in FileInfo class but not that robust.
            var fileInfo = await _mediaFileStore.GetFileInfoAsync(TestFileRelativePath);

            // The IMediaFileStore has its own specific methods such as mapping the file path to a public URL. Since
            // the files in the Media folder are accessible from the outside this can be handy.
            var publicUrl = _mediaFileStore.MapPathToPublicUrl(TestFileRelativePath);

            return($"Successfully created file! File size: {fileInfo.Length} bytes. Public URL: {publicUrl}");
        }
Beispiel #3
0
        public async Task <ActionResult <object> > GetMediaItem(string path)
        {
            if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageMedia))
            {
                return(Forbid());
            }

            if (string.IsNullOrEmpty(path))
            {
                return(NotFound());
            }

            var f = await _mediaFileStore.GetFileInfoAsync(path);

            if (f == null)
            {
                return(NotFound());
            }

            return(CreateFileResult(f));
        }
Beispiel #4
0
        /// <inheritdoc/>
        public async Task <IImageResolver> GetAsync(HttpContext context)
        {
            // Path has already been correctly parsed before here.
            var filePath = _mediaStore.MapPublicUrlToPath(context.Request.PathBase + context.Request.Path.Value);

            // Check to see if the file exists.
            var file = await _mediaStore.GetFileInfoAsync(filePath);

            if (file == null)
            {
                return(null);
            }
            var metadata = new ImageMetaData(file.LastModifiedUtc);

            return(new MediaFileResolver(_mediaStore, filePath, metadata));
        }
        public async Task <string> ReadFile()
        {
            var fileInfo = await _mediaFileStore.GetFileInfoAsync("Demo.txt");

            if (fileInfo == null)
            {
                return("Not found :(");
            }

            using var stream = await _mediaFileStore.GetFileStreamAsync("Demo.txt");

            using var streamReader = new StreamReader(stream);
            var content = await streamReader.ReadToEndAsync();

            return($"File info: size: {fileInfo.Length}, last modification UTC: {fileInfo.LastModifiedUtc}. Content: {content}");
        }
        public async Task <IContent> ImportMediaAsync(string path, string mimeType, string contentType)
        {
            var file = await _mediaFileStore.GetFileInfoAsync(path);

            if (file == null)
            {
                return(null);
            }

            using (var stream = await _mediaFileStore.GetFileStreamAsync(path))
            {
                var mediaFactory = GetMediaFactory(stream, file.Name, mimeType, contentType);

                if (mediaFactory == null)
                {
                    return(null);
                }

                return(mediaFactory.CreateMedia(stream, file.Path, mimeType, file.Length, contentType));
            }
        }
Beispiel #7
0
        public async Task <IActionResult> TemporaryUpload(string path, IFormFile file)
        {
            if (path == null)
            {
                path = "";
            }

            try
            {
                using (var stream = file.OpenReadStream())
                {
                    var mediaFilePath = _mediaFileStore.Combine("temp", path, file.FileName);
                    mediaFilePath = await _mediaFileStore.CreateFileAsync(mediaFilePath, stream);

                    var mediaFile = await _mediaFileStore.GetFileInfoAsync(mediaFilePath);

                    return(Json(new
                    {
                        name = mediaFile.Name,
                        size = mediaFile.Length,
                        folder = mediaFile.DirectoryPath,
                        url = _mediaFileStore.MapPathToPublicUrl(mediaFile.Path),
                        mediaPath = mediaFile.Path,
                        mime = file.ContentType
                    }));
                }
            }
            catch (Exception ex)
            {
                return(Json(new
                {
                    name = file.FileName,
                    size = file.Length,
                    folder = path,
                    error = ex.Message
                }));
            }
        }
Beispiel #8
0
        /// <inheritdoc/>
        public async Task <IByteBuffer> ResolveImageAsync(HttpContext context, ILogger logger)
        {
            // Path has already been correctly parsed before here.

            var filePath = _mediaStore.MapPublicUrlToPath(context.Request.PathBase + context.Request.Path.Value);
            var file     = await _mediaStore.GetFileInfoAsync(filePath);

            // Check to see if the file exists.
            if (file == null)
            {
                return(null);
            }

            IByteBuffer buffer;

            using (var stream = await _mediaStore.GetFileStreamAsync(filePath))
            {
                // Buffer is returned to the pool in the middleware
                buffer = this.bufferManager.Allocate((int)stream.Length);
                await stream.ReadAsync(buffer.Array, 0, buffer.Length);
            }

            return(buffer);
        }
Beispiel #9
0
        /// <inheritdoc/>
        public async Task <byte[]> ResolveImageAsync(HttpContext context, ILogger logger)
        {
            // Path has already been correctly parsed before here.

            var filePath = _mediaStore.MapPublicUrlToPath(context.Request.Path);
            var file     = await _mediaStore.GetFileInfoAsync(filePath);

            // Check to see if the file exists.
            if (file == null)
            {
                return(null);
            }

            byte[] buffer;

            using (var stream = await _mediaStore.GetFileStreamAsync(filePath))
            {
                // Buffer is returned to the pool in the middleware
                buffer = BufferDataPool.Rent((int)stream.Length);
                await stream.ReadAsync(buffer, 0, (int)stream.Length);
            }

            return(buffer);
        }
        public async Task <ActionResult <object> > Upload(
            string path,
            ICollection <IFormFile> files)
        {
            if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageMedia))
            {
                return(Forbid());
            }

            if (string.IsNullOrEmpty(path))
            {
                path = "";
            }

            var result = new List <object>();

            // Loop through each file in the request
            foreach (var file in files)
            {
                // TODO: support clipboard

                if (!_allowedFileExtensions.Contains(Path.GetExtension(file.FileName), StringComparer.OrdinalIgnoreCase))
                {
                    result.Add(new
                    {
                        name   = file.FileName,
                        size   = file.Length,
                        folder = path,
                        error  = S["This file extension is not allowed: {0}", Path.GetExtension(file.FileName)].ToString()
                    });

                    _logger.LogInformation("File extension not allowed: '{File}'", file.FileName);

                    continue;
                }

                var fileName = _mediaNameNormalizerService.NormalizeFileName(file.FileName);

                Stream stream = null;
                try
                {
                    var mediaFilePath = _mediaFileStore.Combine(path, fileName);
                    stream        = file.OpenReadStream();
                    mediaFilePath = await _mediaFileStore.CreateFileFromStreamAsync(mediaFilePath, await _tinyPngService.OptimiseAsync(stream, file.FileName));

                    var mediaFile = await _mediaFileStore.GetFileInfoAsync(mediaFilePath);

                    result.Add(CreateFileResult(mediaFile));
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "An error occurred while uploading a media");

                    result.Add(new
                    {
                        name   = fileName,
                        size   = file.Length,
                        folder = path,
                        error  = ex.Message
                    });
                }
                finally
                {
                    stream?.Dispose();
                }
            }

            return(new { files = result.ToArray() });
        }
        public async Task <IActionResult> GetUserProfilePhotoSmall(string id)
        {
            var user = await _userManager.FindByNameAsync(id) as User;

            if (user != null)
            {
                // byte[] file = null;
                var userProfileMetadata = user.As <UserMetadata>();
                if (userProfileMetadata != null)
                {
                    var urlProfileImageUrl = userProfileMetadata.Avatar;


                    if (_mediaFileStore == null)
                    {
                        return(Content(urlProfileImageUrl));
                    }

                    // This way you can check if the given file exists.
                    if (await _mediaFileStore.GetFileInfoAsync(urlProfileImageUrl) != null)
                    {
                        await using (var stream = await _mediaFileStore.GetFileStreamAsync(urlProfileImageUrl))

                        {
                            // var resolvedAssetPath = mediaFileStore.MapPathToPublicUrl(urlProfileImageUrl);
                            using (var image = SixLabors.ImageSharp.Image.Load(stream))
                            {
                                // Resize the image in place and return it for chaining.
                                // 'x' signifies the current image processing context.
                                image.Mutate(x => x.Resize(50, 50));

                                await using (var ms = new MemoryStream())
                                {
                                    image.Save(ms, new PngEncoder());
                                    return(File(ms.ToArray(), MediaTypeNames.Application.Octet, true));
                                }
                                // The library automatically picks an encoder based on the file extensions then encodes and write the data to disk.
                                // return File(image.ToByteArray(), MediaTypeNames.Application.Octet, true);
                            }
                        }


                        // If you want to extract the content of the file use a StreamReader to read the stream.

                        /*using (var stream = await mediaFileStore.GetFileStreamAsync(urlProfileImageUrl))
                         *
                         * {
                         *
                         *  file = new byte[stream.Length];
                         *  int numBytesToRead = (int) stream.Length;
                         *  int numBytesRead = 0;
                         *  while (numBytesToRead > 0)
                         *  {
                         *      int n = stream.Read(file, numBytesRead, numBytesToRead);
                         *      if (n == 0)
                         *      {
                         *          break;
                         *      }
                         *
                         *      numBytesRead += n;
                         *      numBytesToRead -= n;
                         *  }
                         *
                         * }
                         * return File(file, MediaTypeNames.Application.Octet, true);*/
                    }



                    // return Content( _orchardHelper.ImageResizeUrl(resolvedAssetPath, 40, 40,ResizeMode.Crop));
                    // var fileVersionProvider = _orchardHelper.HttpContext.RequestServices.GetService<IFileVersionProvider>();

                    // resizedUrl = fileVersionProvider.AddFileVersionToPath(orchardHelper.HttpContext.Request.PathBase, resizedUrl);
                }
            }

            //   var file = user.Avatar;
            //  if (file != null)

            /*using (var image = new MagickImage(file))
             * {
             *  image.Resize(40, 40);
             *
             *  return File(image.ToByteArray(), MediaTypeNames.Application.Octet, true);
             * }*/
            return(NoContent());
        }
Beispiel #12
0
        public async Task <IActionResult> UploadMediaFromFroalaEditor()
        {
            // if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageOwnMedia))
            // {
            //     return Forbid();
            // }


            var path = _attachedMediaToContentItemService.MediaFieldsTempSubFolder;

            var fileToUpload = GetFileToUpload(null);
            var result       = new object();

            // Loop through each file in the request
            // foreach (var file in files)
            //{
            if (fileToUpload != null)
            {
                // TODO: support clipboard

                if (!_allowedFileExtensions.Contains(Path.GetExtension(fileToUpload.FileName), StringComparer.OrdinalIgnoreCase))
                {
                    result = new
                    {
                        name   = fileToUpload.FileName,
                        size   = fileToUpload.Length,
                        folder = path,
                        error  = S["This file extension is not allowed: {0}", Path.GetExtension(fileToUpload.FileName)]
                                 .ToString()
                    };

                    _logger.LogInformation("File extension not allowed: '{0}'", fileToUpload.FileName);

                    //  continue;
                }
                else
                {
                    Stream stream = null;
                    try
                    {
                        var mediaFilePath = _mediaFileStore.Combine(path, fileToUpload.FileName);
                        stream        = fileToUpload.OpenReadStream();
                        mediaFilePath = await _mediaFileStore.CreateFileFromStreamAsync(mediaFilePath, stream);

                        var mediaFile = await _mediaFileStore.GetFileInfoAsync(mediaFilePath);

                        result = CreateFileResult(mediaFile);
                    }
                    catch (Exception ex)
                    {
                        _logger.LogError(ex, "An error occurred while uploading a media");

                        result = new { name = fileToUpload.FileName, size = fileToUpload.Length, folder = path, error = ex.Message };
                    }
                    finally
                    {
                        stream?.Dispose();
                    }
                }



                //}
            }

            return(Json(result));
        }
        /// <summary>
        /// Processes a request to determine if it matches a known file from the media file store, and cache it locally.
        /// </summary>
        /// <param name="context"></param>
        public async Task Invoke(HttpContext context)
        {
            // Support only Head requests or Get Requests.
            if (!HttpMethods.IsGet(context.Request.Method) && !HttpMethods.IsHead(context.Request.Method))
            {
                await _next(context);

                return;
            }

            var validatePath = context.Request.Path.StartsWithNormalizedSegments(_assetsRequestPath, StringComparison.OrdinalIgnoreCase, out var subPath);

            if (!validatePath)
            {
                _logger.LogDebug("Request path {Path} does not match the assets request path {RequestPath}", subPath, _assetsRequestPath);
                await _next(context);

                return;
            }

            // subpath.Value returns an unescaped path value, subPath returns an escaped path value.
            var subPathValue = subPath.Value;

            var isFileCached = await _mediaFileStoreCache.IsCachedAsync(subPathValue);

            if (isFileCached)
            {
                // When multiple requests occur for the same file the download
                // may already be in progress so we wait for it to complete.
                if (Workers.TryGetValue(subPathValue, out var writeTask))
                {
                    await writeTask.Value;
                }

                await _next(context);

                return;
            }

            // When multiple requests occur for the same file we use a Lazy<Task>
            // to initialize the file store request once.
            await Workers.GetOrAdd(subPathValue, x => new Lazy <Task>(async() =>
            {
                try
                {
                    var fileStoreEntry = await _mediaFileStore.GetFileInfoAsync(subPathValue);

                    if (fileStoreEntry != null)
                    {
                        using (var stream = await _mediaFileStore.GetFileStreamAsync(fileStoreEntry))
                        {
                            await _mediaFileStoreCache.SetCacheAsync(stream, fileStoreEntry, context.RequestAborted);
                        }
                    }
                }
                catch (Exception ex)
                {
                    // Log the error, and pass to pipeline to handle as 404.
                    // Multiple requests at the same time will all recieve the same 404
                    // as we use LazyThreadSafetyMode.ExecutionAndPublication.
                    _logger.LogError(ex, "Error retrieving file from media file store for request path {Path}", subPathValue);
                }
                finally
                {
                    Workers.TryRemove(subPathValue, out var writeTask);
                }
            }, LazyThreadSafetyMode.ExecutionAndPublication)).Value;

            // Always call next, this middleware always passes.
            await _next(context);

            return;
        }