Summary

Class:ProjectX.PublicApi.Actions.Images.ImagesController
Assembly:ProjectX.PublicApi
File(s):C:\private\projects\projectx\backend\src\ProjectX.PublicApi\Actions\Images\ImagesController.cs
Covered lines:0
Uncovered lines:63
Coverable lines:63
Total lines:149
Line coverage:0%
Branch coverage:0%

History

Metrics

MethodCyclomatic complexity  NPath complexity  Sequence coverage  Branch coverage  
.ctor(...)1000
Get()3200
Put()8400

File(s)

C:\private\projects\projectx\backend\src\ProjectX.PublicApi\Actions\Images\ImagesController.cs

#LineLine coverage
 1using System;
 2using System.IO;
 3using System.Threading.Tasks;
 4using Microsoft.AspNetCore.Mvc;
 5using Microsoft.Extensions.Logging;
 6using ProjectX.PublicApi.Configuration;
 7using ProjectX.PublicApi.Filters;
 8using ProjectX.PublicApi.MagicBytes;
 9
 10namespace ProjectX.PublicApi.Actions.Images
 11{
 12    [Route("/images")]
 13    public class ImagesController : Controller
 14    {
 15        private readonly ApplicationOptions _options;
 16        private readonly ILogger<ImagesController> _logger;
 17
 018        public ImagesController(
 019            ApplicationOptions options,
 020            ILogger<ImagesController> logger)
 21        {
 022            this._options = options;
 023            this._logger = logger;
 024        }
 25
 26        /// <summary>
 27        /// Retrieves the file with the specified id.
 28        /// </summary>
 29        /// <param name="imageId">
 30        /// The id of the file to be retrieved.
 31        /// </param>
 32        [HttpGet("{imageId}")]
 33        public async Task<IActionResult> Get(Guid imageId)
 34        {
 035            this._logger.LogTrace("Start image get request");
 36
 037            var path = Path.Combine(_options.ImagesPath, imageId.ToString());
 38
 039            if (!System.IO.File.Exists(path))
 40            {
 041                this._logger.LogTrace(
 042                    $"No file found with id `{imageId}`");
 43
 044                return new NotFoundObjectResult(
 045                    $"No file found with id `{imageId}`");
 46            }
 47
 048            var stream = System.IO.File.OpenRead(path);
 049            var mimeType = "application/octet-stream";
 050            var fileName = imageId.ToString();
 51
 52            try
 53            {
 054                var pattern = Wizard.Identify(stream);
 055                 if (pattern != null)
 56                {
 057                    mimeType = pattern.MimeType;
 058                    fileName += $".{pattern.FileExtension}";
 059                }
 60                else
 61                {
 062                    this._logger.LogTrace(
 063                        $"No matching pattern found, {imageId}");
 64                }
 65            }
 066            catch (Exception)
 67            {
 068                stream.Dispose();
 69
 70                // Just throw it will be handled by global exception handler
 071                throw;
 72            }
 73
 74            /*this.Response.Headers["Content-Transfer-Encoding"] = "binary";
 75            this.Response.ContentType = mimeType;
 76            this.Response.Headers["Content-Disposition"] =
 77                $"Content-Disposition: attachment; filename='{fileName}'";*/
 78
 079            this._logger.LogTrace(
 080                $"End image get request. Found image {fileName}");
 81
 082            return File(stream, mimeType, fileName);
 83        }
 84
 85        /// <summary>
 86        /// Uploasd the posted file and saves it.
 87        /// </summary>
 88        /// <returns>
 89        /// A success object or an exception.
 90        /// </returns>
 91        [ServiceFilter(typeof(AuthContextAttribute))]
 92        [HttpPut]
 93        public async Task<IActionResult> Put()
 94        {
 095            this._logger.LogTrace("Stasrt image upload request");
 96
 097            var id = Guid.NewGuid();
 098            var path = Path.Combine(this._options.ImagesPath, id.ToString());
 99
 0100            while (System.IO.File.Exists(path))
 101            {
 0102                id = Guid.NewGuid();
 103            }
 104
 0105            var size = Environment.SystemPageSize;
 0106            var inputStream = this.Request.Body;
 107
 0108             if (this.Request.ContentLength > this._options.MaxFileSize)
 109            {
 0110                this._logger.LogTrace("File too big");
 0111                return new BadRequestObjectResult("File too big");
 112            }
 113
 0114            var outputStream = System.IO.File.Create(path, size);
 0115            Action flushStream = () =>
 0116            {
 0117                var totalLength = this.Request.ContentLength;
 0118                var alreadyWritten = 0;
 0119                var buf = new byte[size];
 0120
 0121                 while (alreadyWritten < totalLength)
 0122                {
 0123                    var actuallyRead = inputStream.Read(buf, 0, size);
 0124                    outputStream.Write(buf, 0, actuallyRead);
 0125                    alreadyWritten += actuallyRead;
 0126                }
 0127
 0128                outputStream.Flush();
 0129            };
 130
 131            try
 132            {
 0133                flushStream();
 134            }
 135            finally
 136            {
 0137                inputStream.Dispose();
 0138                outputStream.Dispose();
 139            }
 140
 0141            this._logger.LogTrace("End image upload request");
 142
 0143            return this.Json(new
 0144            {
 0145                ImageId = id
 0146            });
 147        }
 148    }
 149}