public async override Task BuildIndexAsync(MediaField field, BuildFieldIndexContext context)
        {
            var options  = context.Settings.ToOptions();
            var settings = context.ContentPartFieldDefinition.GetSettings <MediaFieldSettings>();

            if (field.Paths?.Length > 0)
            {
                if (settings.AllowMediaText)
                {
                    foreach (var key in context.Keys)
                    {
                        if (field.MediaTexts != null)
                        {
                            foreach (var mediaText in field.MediaTexts)
                            {
                                context.DocumentIndex.Set(key + MediaTextKeySuffix, mediaText, options);
                            }
                        }
                        else
                        {
                            context.DocumentIndex.Set(key + MediaTextKeySuffix, "NULL", options);
                        }
                    }
                }

                // It doesn't really makes sense to store file contents without analyzing them for search as well.
                var fileIndexingOptions = options | DocumentIndexOptions.Analyze;

                foreach (var path in field.Paths)
                {
                    var providerType = _mediaFileIndexingOptions.GetRegisteredMediaFileTextProvider(Path.GetExtension(path));

                    if (providerType != null)
                    {
                        using var fileStream = await _mediaFileStore.GetFileStreamAsync(path);

                        if (fileStream != null)
                        {
                            var fileText = await _serviceProvider
                                           .CreateInstance <IMediaFileTextProvider>(providerType)
                                           .GetTextAsync(path, fileStream);

                            foreach (var key in context.Keys)
                            {
                                context.DocumentIndex.Set(key + FileTextKeySuffix, fileText, fileIndexingOptions);
                            }
                        }
                    }
                }
            }
            else
            {
                foreach (var key in context.Keys)
                {
                    context.DocumentIndex.Set(key + MediaTextKeySuffix, "NULL", options);
                    context.DocumentIndex.Set(key + FileTextKeySuffix, "NULL", options);
                }
            }
        }
 private async Task <string> GetFileHashAsync(string filePath)
 {
     using (var fs = await _fileStore.GetFileStreamAsync(filePath))
         using (HashAlgorithm hashAlgorithm = MD5.Create())
         {
             var hash = hashAlgorithm.ComputeHash(fs);
             return(ByteArrayToHexString(hash));
         }
 }
        public async Task ProcessDeploymentStepAsync(DeploymentStep step, DeploymentPlanResult result)
        {
            if (!(step is MediaDeploymentStep mediaStep))
            {
                return;
            }

            List <string> paths;

            if (mediaStep.IncludeAll)
            {
                var fileStoreEntries = await _mediaFileStore.GetDirectoryContentAsync(null, true);

                paths =
                    (
                        from fileStoreEntry in fileStoreEntries
                        where !fileStoreEntry.IsDirectory
                        select fileStoreEntry.Path
                    ).ToList();
            }
            else
            {
                paths = new List <string>(mediaStep.FilePaths ?? Array.Empty <string>());

                foreach (var directoryPath in mediaStep.DirectoryPaths ?? Array.Empty <string>())
                {
                    var fileStoreEntries = await _mediaFileStore.GetDirectoryContentAsync(directoryPath, true);

                    paths.AddRange(
                        from fileStoreEntry in fileStoreEntries
                        where !fileStoreEntry.IsDirectory
                        select fileStoreEntry.Path);
                }

                paths.Sort();
            }

            foreach (var path in paths)
            {
                var stream = await _mediaFileStore.GetFileStreamAsync(path);

                await result.FileBuilder.SetFileAsync(path, stream);
            }

            // Adding media files
            result.Steps.Add(new JObject(
                                 new JProperty("name", "media"),
                                 new JProperty("Files", JArray.FromObject(
                                                   (from path in paths
                                                    select new
            {
                SourcePath = path,
                TargetPath = path
            }).ToArray()
                                                   ))
                                 ));
        }
        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}");
        }
        // If you've created the file just go to the Dashboard and check if you can see it under Assets. You can also
        // find it in the App_Data/Sites/{TenantName}/Media/TrainingDemo folder.

        // This action will read the file you've created earlier.
        public async Task <string> ReadFileFromMediaFolder()
        {
            // This way you can check if the given file exists.
            if (await _mediaFileStore.GetFileInfoAsync(TestFileRelativePath) == null)
            {
                return("Create the file first!");
            }

            // If you want to extract the content of the file use a StreamReader to read the stream.
            using (var stream = await _mediaFileStore.GetFileStreamAsync(TestFileRelativePath))
                using (var streamReader = new StreamReader(stream))
                {
                    var content = streamReader.ReadToEnd();

                    return($"File content: {content}");
                }
        }
Example #6
0
        public async Task <IActionResult> AppleTouchIcon()
        {
            var settings = await GetSettings();

            if (settings == null || !settings.HasAppleTouchIcon)
            {
                return(NotFound());
            }

            _contentTypeProvider.TryGetContentType(settings.AppleTouchIconPath, out var contentType);
            return(File(await _mediaFileStore.GetFileStreamAsync(settings.FaviconPath), contentType ?? DefaultMimeTypes.AppleTouchIcon));
        }
        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));
            }
        }
Example #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);
        }
Example #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 <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());
        }
        /// <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;
        }