public static async Task <AddVideoModel> HandleAddVideoRequest(HttpRequest request, string outputDir, ModelStateDictionary modelState, string[] _allowedExtensions)
        {
            var boundary = request.GetMultipartBoundary();
            var reader   = new MultipartReader(boundary, request.Body);
            var section  = await reader.ReadNextSectionAsync();

            var model = new AddVideoModel();

            while (section != null)
            {
                var fileSection = section.AsFileSection();
                if (fileSection == null)
                {
                    await MapToRequestModelProperty(section, model);
                }
                else
                {
                    if (string.IsNullOrWhiteSpace(fileSection.FileName))
                    {
                        modelState.AddModelError("File", "No file name was provided");
                        return(null);
                    }
                    var ext = Path.GetExtension(fileSection.FileName);

                    if (ext == null || !_allowedExtensions.Contains(ext.Trim('.'), StringComparer.InvariantCultureIgnoreCase))
                    {
                        modelState.AddModelError("File", $"File type of {ext} is not alowed");
                        return(null);
                    }
                    model.FilePath = await SaveFile(fileSection, outputDir);
                }
                section = reader.ReadNextSectionAsync().Result;
            }
            return(model);
        }
예제 #2
0
        public IActionResult Post([FromBody] AddVideoModel model)
        {
            Video video = new Video(model);

            _videorepo.Add(video);
            if (_videorepo.SaveChanges() == 0)
            {
                throw new ApplicationException("failed to create Video");
            }
            //var BeverageDto = _beverageMapper.MapBeverageDto(Beverage);
            return(Ok(video));
        }
예제 #3
0
 private IEnumerable <Task> CreateThumbnails(AddVideoModel videoRequest, string videoOutputDir, ConcurrentBag <string> thumbnails)
 {
     foreach (var thumbTime in _thumbnailsBySeconds)
     {
         var createThumbnailTask = Task.Run(async() =>
         {
             var thumbPath = Path.Combine(videoOutputDir, $"thumbnail{thumbTime}.png");
             await _videoConverter.SaveVideoThumbnail(videoRequest.FilePath, thumbPath, thumbTime);
             thumbnails.Add(thumbPath);
         });
         yield return(createThumbnailTask);
     }
 }
예제 #4
0
 public Video(AddVideoModel model)
 {
     this.Name            = model.Name;
     this.Category        = model.Category;
     this.Description     = model.Description;
     this.Discount        = model.Discount;
     this.Duration        = model.Duration;
     this.ObjectStorageId = model.ObjectStorageId;
     this.FileExtension   = model.FileExtension;
     this.FileSize        = model.FileSize;
     this.Rating          = model.Rating;
     this.Price           = model.Price;
     this.PaymentOption   = model.PaymentOption;
 }
예제 #5
0
        /// <summary>
        /// Convert and save the video in the requested format,
        /// extract thumbnails, save in DB and delete the oriinal file
        /// </summary>
        /// <param name="videoRequest"></param>
        /// <returns></returns>
        public async Task <VideoModel> AddVideo(AddVideoModel videoRequest)
        {
            try
            {
                //create a folder for the video
                var videoOutputDir = Path.Combine(_outputDir, videoRequest.Name);
                Directory.CreateDirectory(videoOutputDir);
                //list to hold all the video conversion tasks and execute them in parallel
                var    tasks = new List <Task>();
                string convertedVideoPath = null;
                var    thumbnails         = new ConcurrentBag <string>();
                var    convertVideoTask   = Task.Run(async() => convertedVideoPath = await ConverVideo(videoRequest, videoOutputDir));
                tasks.Add(convertVideoTask);
                tasks.AddRange(CreateThumbnails(videoRequest, videoOutputDir, thumbnails));
                await Task.WhenAll(tasks.ToArray());

                //create a model from all the collected data
                var model = new VideoModel
                {
                    Name           = videoRequest.Name,
                    Link           = UrlCombine(_videosBaseUrl, videoRequest.Name, Path.GetFileName(convertedVideoPath)),
                    ThumbnailLinks = thumbnails
                                     .Select(t => UrlCombine(_videosBaseUrl, videoRequest.Name, Path.GetFileName(t)))
                                     .ToArray(),
                    VideoFormat = videoRequest.VideoFormat
                };
                //save the data in db
                var added = await _videoRepository.AddVideo(model);

                return(added);
            }
            finally
            {
                try
                {
                    //delete the original file that was uploaded
                    File.Delete(videoRequest.FilePath);
                }
                catch (Exception e)
                {
                    _logger.LogError(videoRequest.FilePath + Environment.NewLine + e.ToString());
                }
            }
        }
예제 #6
0
 private Task <string> ConverVideo(AddVideoModel videoRequest, string videoOutputDir)
 {
     return(_videoConverter.ConvertMedia(videoRequest.FilePath, videoRequest.Name, videoOutputDir, videoRequest.VideoFormat));
 }
        private static async Task MapToRequestModelProperty(MultipartSection section, AddVideoModel requestModel)
        {
            var data   = section.AsFormDataSection();
            var csName = char.ToUpper(data.Name[0]) + data.Name.Substring(1);

            switch (csName)
            {
            case nameof(requestModel.Name):
                var name = await section.ReadAsStringAsync();

                requestModel.Name = Uri.EscapeUriString(name);
                break;

            case nameof(requestModel.VideoFormat):
                var str = await section.ReadAsStringAsync();

                requestModel.VideoFormat = Enum.Parse <VideoFormatEnum>(str);
                break;
            }
        }