/// <summary>
        /// To add a new Video
        /// </summary>
        /// <param name="video"></param>
        public void AddVideo(VideoVM video)
        {
            var movie = new Video {
                VideoDescription = video.VideoDescription, VideoName = video.VideoName, CategoryId = video.CategoryId, VideoPath = video.VideoPath, VideoSize = video.VideoSize
            };

            _videoRepository.AddVideo(movie);
        }
        public async Task <ActionResult <Video> > PostVideo([FromBody] URLDTO data)
        {
            Video  video;
            String videoURL;
            String videoId;
            Video  checkVideo = await _videoRepository.GetVideoByURL(data.URL);

            if (checkVideo != null)
            {
                return(CreatedAtAction("GetVideo", new { id = checkVideo.VideoId }, checkVideo));
            }
            try
            {
                // Constructing the video object from our helper function
                videoURL = data.URL;
                videoId  = YouTubeHelper.GetVideoIdFromURL(videoURL);
                video    = YouTubeHelper.GetVideoInfo(videoId);
            }
            catch
            {
                return(BadRequest("Invalid YouTube URL"));
            }

            // Add this video object to the database
            await _videoRepository.AddVideo(video);

            // Get video for videoId
            Video newVideo = await _videoRepository.GetVideoByURL(data.URL);

            // Get the primary key of the newly created video record
            //video = _videoRepository.GetVideoByID
            int id = newVideo.VideoId;


            ITranscriptionsRepository transcriptionsRepository = new TranscriptionsRepository();
            TranscriptionsController  transcriptionsController = new TranscriptionsController(transcriptionsRepository);

            // This will be executed in the background.
            Task addCaptions = Task.Run(async() =>
            {
                // Get a list of captions from YouTubeHelper
                List <Transcription> transcriptions = new List <Transcription>();
                transcriptions = YouTubeHelper.GetTranscriptions(videoId);

                for (int i = 0; i < transcriptions.Count; i++)
                {
                    // Get the transcription objects form transcriptions and assign VideoId to id, the primary key of the newly inserted video
                    Transcription transcription = transcriptions.ElementAt(i);
                    transcription.VideoId       = id;
                    // Add this transcription to the database
                    await transcriptionsController.PostTranscription(transcription);
                }
            });

            // Return success code and the info on the video object
            return(CreatedAtAction("GetVideo", new { id = video.VideoId }, video));
        }
        public async Task <IActionResult> AddVideo(int courseId, int teacherId)
        {
            string auth = Request.Headers["Authorization"]; // get bearer string

            if (AuthHelper.BasicAuth(auth, teacherId, "Teacher") == false)
            {
                return(Unauthorized());
            }

            var files = Request.Form.Files;

            if (files == null)
            {
                return(BadRequest("Request must contain video file"));
            }

            FormFileChecker fileChecker = new FormFileChecker();

            foreach (var file in files)
            {
                if (!fileChecker.CheckFileType(file, "video"))
                {
                    return(BadRequest("Course Video must be type of video"));
                }
            }

            // return Ok(files);

            var videoToReturn = new List <VideoForDetailedDto>();
            FileUploadHelper fileUploadHelper = new FileUploadHelper(_cloudinary);

            foreach (var file in files)
            {
                var uploadResult  = fileUploadHelper.UploadVideo(file);
                var videoToCreate = new VideoForCreateDto
                {
                    CourseId = courseId,
                    VideoUrl = uploadResult.Uri.ToString(),
                    PublicId = uploadResult.PublicId
                };
                var videoToAdd = _mapper.Map <Models.Video>(videoToCreate);
                var videoAdded = await _repo.AddVideo(videoToAdd, courseId);

                await _repo.SaveAll();

                videoToReturn.Add(_mapper.Map <VideoForDetailedDto>(videoAdded));
            }

            return(Ok(videoToReturn));
        }
Exemplo n.º 4
0
        public async Task <IActionResult> Post([FromBody] VideoAddOrUpdateResource video)
        {
            if (video == null)
            {
                return(BadRequest());
            }

            var videoEntity = _mapper.Map <Video>(video);

            _videoRepository.AddVideo(videoEntity);

            if (await _unitOfWork.CompleteWorkAsync())
            {
                throw new Exception("Error occurred when adding");
            }

            return(CreatedAtAction(nameof(Get), new { videoId = videoEntity.VideoId }, videoEntity));
        }
Exemplo n.º 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());
                }
            }
        }
Exemplo n.º 6
0
        public IActionResult UploadNews(ICollection <IFormFile> files, int User_Id, NewsDataViewModels newsData)
        {
            //long size = files.Sum(f => f.Length);
            string mainFolder = _environment.ContentRootPath;
            int    n          = 0;
            string msg        = "";
            bool   success    = false;

            foreach (var file in files)
            {
                string filePath = "";

                string[] videos   = new string[] { "mp4", "mp3" };
                string[] images   = new string[] { "jpg", "png" };
                string   fileName = file?.FileName?.Replace(" ", "_").Replace("-", "_");
                if (file?.FileName != null)
                {
                    int ii = fileName.LastIndexOf("\\");
                    if (ii != -1)
                    {
                        fileName = fileName.Substring(ii + 1);
                    }
                }

                int i = file.FileName.LastIndexOf(".");
                if (i == -1)
                {
                    continue;
                }
                string ext = file.FileName.Substring(i + 1);


                if (videos.Contains(ext))
                {
                    filePath = _environment.WebRootPath + @"/VideoFiles/Videos/" + fileName;
                }
                if (images.Contains(ext))
                {
                    filePath = _environment.WebRootPath + @"\VideoFiles\Images\" + fileName;
                }

                if (file.Length > 0)
                {
                    using (var stream = new FileStream(filePath, FileMode.Create))
                    {
                        try
                        {
                            file.CopyToAsync(stream);
                            bool res = videoRepository.AddVideo(newsData, filePath);
                            n += 1;
                        }
                        catch (Exception ex)
                        {
                            msg += " There was problem to save file :  " + file?.FileName;
                        }
                    }
                }
            }

            if (n > 0)
            {
                msg    += " Files saved successfully are: " + n.ToString();
                success = true;
                return(Json(new { success = success, message = msg }));
            }
            else
            {
                newsData.message = "There was not selected file!";
                //return Ok(new { count = files.Count, size, filePath });
                return(View("NewsUpload", newsData));
            }
        }