protected override void BecauseOnce()
        {
            base.BecauseOnce();
            _mocks.Get<IRepository<Video>>().Stub(c => c.Get(_video.Id)).Return(_video);

            _outModel = Controller.Details(new GetVideoRequest() {Id = _video.Id});
        }
        public async void AddVideo_CalledAndRoleIsNotAdmin_ReturnsBadRequestWithError()
        {
            IUnitOfWork    unitOfWork    = Substitute.For <IUnitOfWork>();
            IVideoManager  videoManager  = Substitute.For <IVideoManager>();
            ICookieManager cookieManager = Substitute.For <ICookieManager>();
            var            context       = Substitute.For <HttpContext>();

            long          testId            = 1;
            var           testVideo         = new VideoViewModel();
            ModuleContent nullModuleContent = null;
            string        testUrl           = "testurl";
            string        convertedUrl      = "converted";
            string        testyoutubeId     = "youtubeid";
            string        error             = "Only Admins can add videos.";

            unitOfWork.ModuleContents.GetById(testId).Returns(nullModuleContent);
            videoManager.ConvertUrl(testUrl).Returns(convertedUrl);
            videoManager.GetYoutubeId(convertedUrl).Returns(testyoutubeId);
            cookieManager.GetRoleFromToken(Arg.Any <string>()).Returns(Role.Student.ToString());

            var videosController = new VideosController(unitOfWork, videoManager, cookieManager);

            videosController.ControllerContext = new ControllerContext()
            {
                HttpContext = context
            };

            var result = await videosController.AddVideo(testVideo);

            var badRequestObjectResult = Assert.IsType <BadRequestObjectResult>(result);
            var returnValue            = Assert.IsType <string>(badRequestObjectResult.Value);

            Assert.Equal(error, returnValue);
        }
Example #3
0
        public async Task <IActionResult> Create(VideoViewModel videoViewModel)
        {
            if (ModelState.IsValid)
            {
                string thumbnail = "No File";
                if (videoViewModel.Thumbnail != null)
                {
                    string uniqueFileName = null;
                    string stringCutted   = videoViewModel.Thumbnail.FileName.Split('.').Last();
                    uniqueFileName = Guid.NewGuid().ToString() + "." + stringCutted;
                    thumbnail      = uniqueFileName;
                    InputFile fileUpload = new InputFile(_hostingEnvironment);
                    fileUpload.Uploadfile("files/video_thumbnails", videoViewModel.Thumbnail, thumbnail);
                }

                var video = new Video
                {
                    Name          = videoViewModel.Name,
                    Location      = videoViewModel.Location,
                    Link          = videoViewModel.Link,
                    ThumbnailName = thumbnail
                };

                _context.Add(video);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(videoViewModel));
        }
Example #4
0
 public ActionResult Edit(VideoViewModel video)
 {
     ViewBag.SelectedPage = Navigator.Items.VIDEOS;
     if (ModelState.IsValid)
     {
         video.URL = URLValidator.CleanURL(video.URL);
         if (!URLValidator.IsValidURLPart(video.URL))
         {
             TempData["ErrorMessage"] = "Video Failed To Add, URL Not Valid";
         }
         else if (servicesManager.VideoService.IsVideoURLExist(video.URL, video.VideoId))
         {
             TempData["ErrorMessage"] = "Video Failed To Add, URL already exist";
         }
         else
         {
             int new_id = servicesManager.VideoService.UpdateVideo(video);
             if (new_id > 0)
             {
                 TempData["SuccessMessage"] = "Video Updated Successfully";
                 return(RedirectToAction("Edit", video.VideoId));
             }
             else
             {
                 TempData["ErrorMessage"] = "Video Failed To Update";
             }
         }
     }
     //FillArticleCategories(article.CategoryId);
     FillVideoAuthor(video.AuthorId);
     FillVideoCategories(video.CategoryId);
     FillAvailableTags();
     return(View(video));
 }
Example #5
0
        public IActionResult Video(int id)
        {
            var video = _db.GetVideo(id);

            // Create a VideoComingUpDto object
            var videos    = _db.GetVideos(video.AlbumId).ToList();
            var index     = videos.IndexOf(video);
            var prevVideo = videos.ElementAtOrDefault(index - 1);
            var nextVideo = videos.ElementAtOrDefault(index + 1);
            var nextTitle = nextVideo == null ? string.Empty : nextVideo.Title;
            var nextThumb = nextVideo == null ? string.Empty : nextVideo.Thumbnail;

            var videoModel = new VideoViewModel
            {
                Genre         = _mapper.Map <GenreDto>(_db.GetGenre(_userId, video.Album.GenreId)),
                Band          = _mapper.Map <BandDto>(_db.GetBand(video.Album.BandId)),
                Video         = _mapper.Map <VideoDto>(video),
                VideoComingUp = new VideoComingUpDto
                {
                    VideoNumber           = index + 1,
                    NumberOfVideos        = videos.Count(),
                    NextVideoId           = nextVideo?.Id ?? 0,
                    PreviousVideoId       = prevVideo?.Id ?? 0,
                    CurrentVideoTitle     = video.Title,
                    CurrentVideoThumbnail = video.Thumbnail,
                    NextVideoTitle        = nextTitle,
                    NextVideoThumbnail    = nextThumb
                }
            };

            return(View(videoModel));
        }
Example #6
0
        //URLから適当なViewを開く
        public static TabItemViewModel Open(string url)
        {
            if (Keyboard.IsKeyDown(Key.LeftShift) || Keyboard.IsKeyDown(Key.RightShift))
            {
                System.Diagnostics.Process.Start(url);
                return(null);
            }

            if (url.StartsWith("http://www.nicovideo.jp/watch/"))
            {
                var vm = new VideoViewModel(url);
                App.ViewModelRoot.AddTabAndSetCurrent(vm);
                vm.Initialize();
                return(vm);
            }
            else if (url.StartsWith("http://www.nicovideo.jp/user/"))
            {
                return(new UserViewModel(url));
            }
            else if (url.StartsWith("http://www.nicovideo.jp/mylist/"))
            {
                return(new PublicMylistViewModel(url));
            }
            else if (url.StartsWith("http://com.nicovideo.jp/community/"))
            {
                return(new CommunityViewModel(url));
            }
            else
            {
                System.Diagnostics.Process.Start(url);
                return(null);
            }
        }
        public ActionResult SubIndex(string category)
        {
            int count;
            var result = _videoService.GetVideosWithCategory(category, 0, 12, out count);
            var model  = new VideoViewModel()
            {
                Category = category,
                Count    = count,
                Contents = result
            };

            switch (category)
            {
            case ("心理短片"): { model.DivId = "psychology"; break; }

            case ("感悟人生"): { model.DivId = "life"; break; }

            case ("TED专场"): { model.DivId = "ted"; break; }

            case ("心理DV剧"): { model.DivId = "dvju"; break; }

            case ("其他精彩"): { model.DivId = "other"; break; }
            }
            return(PartialView("_VideoPartial", model));
        }
        public IActionResult Video(int id)
        {
            // Call the _db.GetVideo method to fetch the video matching the id passed in to the Video action, and the logged in user’s id.
            var video = _db.GetVideo(_userId, id);

            // Call the _db.GetCourse method to fetch the course matching the CourseId property in the video object, and the logged in user’s id.
            var course = _db.GetCourse(_userId, video.CourseId);

            // convert the Video object into a VideoDTO object
            var mappedVideoDTO = _mapper.Map <VideoDTO>(video);

            // convert the course object into a CourseDTO object.
            var mappedCourseDTO = _mapper.Map <CourseDTO>(course);

            // convert the Instructor object in the course object into an InstructorDTO object.
            var mappedInstructorDTO = _mapper.Map <InstructorDTO>(course.Instructor);

            // _db.GetVideos method to fetch all the videos matching the current module id.
            // You need this data to get the number of videos in the module, and to get the index of the current video
            var videos = _db.GetVideos(_userId, video.ModuleId).ToList();

            // Store number of videos
            var count = videos.Count();

            // Find index of the current video in the module video list. Display index and the video count to the user, in the view.
            var index = videos.IndexOf(video);

            // Fetch the id for the previous video in the module by calling the ElementAtOrDefault method on the videos collection.
            var previous   = videos.ElementAtOrDefault(index - 1);
            var previousId = previous == null ? 0 : previous.Id;

            // Fetch the id, title, and thumbnail for the next video in the module by calling the ElementAtOrDefault method on the videos collection.
            var next      = videos.ElementAtOrDefault(index + 1);
            var nextId    = next == null ? 0 : next.Id;
            var nextTitle = next == null ? string.Empty : next.Title;
            var nextThumb = next == null ? string.Empty : next.Thumbnail;

            var videoModel = new VideoViewModel
            {
                // Assign the three mapped collections: mappedCourseDTOs, mappedInstructorDTO, and mappedVideoDTOs to the videoModel object’s Course, Instructor, and Video properties
                Video      = mappedVideoDTO,
                Instructor = mappedInstructorDTO,
                Course     = mappedCourseDTO,
                // Create an instance of the LessonInfoDTO for the LessonInfo property in the videoModel object and assign the variable values to its properties.
                // The LessonInfoDTO will be used with the previous and next buttons, and to display the index of the current video
                LessonInfo = new LessonInfoDTO
                {
                    LessonNumber          = index + 1,
                    NumberOfLessons       = count,
                    NextVideoId           = nextId,
                    PreviousVideoId       = previousId,
                    NextVideoTitle        = nextTitle,
                    NextVideoThumbnail    = nextThumb,
                    CurrentVideoTitle     = video.Title,
                    CurrentVideoThumbnail = video.Thumbnail
                }
            };

            return(View());
        }
        public async Task <IActionResult> Video(VideoViewModel mediaFile)
        {
            if (mediaFile != null)
            {
                var    file          = HttpContext.Request.Form.Files;
                bool   uploadSuccess = false;
                string uploadedUri   = null;
                if (file.Count != 0)
                {
                    string imgName   = Guid.NewGuid().ToString();
                    string extension = Path.GetExtension(file[0].FileName).ToLower();
                    if (extension == ".jpg" || extension == ".gif" || extension == ".webm" || extension == ".jpeg" || extension == ".png")
                    {
                        extension                    = extension.Substring(1);
                        mediaFile.ImageURL           = imgName + '.' + extension;
                        using var stream             = file[0].OpenReadStream();
                        (uploadSuccess, uploadedUri) = await UploadToBlob(mediaFile.ImageURL, stream, extension);

                        TempData["uploadedUri"] = uploadedUri;
                    }
                    else
                    {
                        mediaFile.ImageURL = null;
                    }
                }
                mediaDbContext.Portfolios.Add(mediaFile);
                mediaDbContext.SaveChanges();
            }
            return(RedirectToAction("video", "portfolio"));
        }
        public JsonResult JsonData()
        {
            var viewModel = new VideoViewModel();

            viewModel.LoadData();
            return(Json(viewModel, JsonRequestBehavior.AllowGet));
        }
Example #11
0
        private async Task <VideoViewModel> ParseVideoInformation(string html)
        {
            VideoViewModel videoViewModel = new VideoViewModel()
            {
                MediaType = MediaType.VIDEO
            };
            var config = Configuration.Default;

            //Create a new context for evaluating webpages with the given config
            var context = BrowsingContext.New(config);

            //Just get the DOM representation
            var document = await context.OpenAsync(req => req.Content(html));

            // Get video url from source
            var sourceAttr  = document.QuerySelector("source").GetAttribute("src");
            var sourceParts = sourceAttr.Split('/');
            var videoId     = sourceParts[3];

            // Get video title
            var title = document.QuerySelector("title").InnerHtml;

            var        videoBaseUrl         = "https://v.redd.it/" + videoId;
            List <int> availableResolutions = await GetAvailableResolutions(videoBaseUrl);

            string thumbnailUrl = GetThumbnailUrl(html);

            videoViewModel.Id                   = videoId;
            videoViewModel.Title                = title;
            videoViewModel.BaseDownloadUrl      = videoBaseUrl;
            videoViewModel.AvailableResolutions = availableResolutions;
            videoViewModel.ThumbnailUrl         = thumbnailUrl;

            return(videoViewModel);
        }
Example #12
0
        private void RewindVideo(VideoViewModel vm)
        {
            double fps = vm.Capture.GetCaptureProperty(CapProp.Fps);

            if (vm.Capture.GetGrabberThreadState() == GrabStates.Running)
            {
                vm.Capture.Pause();
                while (vm.Capture.GetGrabberThreadState() == GrabStates.Running)
                {
                    ;
                }
                Thread.Sleep(10); //I don't know why but Emgu.CV.World.dll crashes without any delay
                vm.Capture.SetCaptureProperty(CapProp.PosFrames, this.Value * fps);
                vm.Capture.Start();
            }
            else
            {
                vm.Capture.SetCaptureProperty(CapProp.PosFrames, this.Value * fps);
            }

            double value = this.Value;

            SetSliderValueBinding(vm);
            vm.Timestamp = value * 1000;
        }
Example #13
0
        protected override void OnPreviewMouseUp(MouseButtonEventArgs e)
        {
            VideoViewModel vm = ((VideoSlider)e.Source).DataContext as VideoViewModel;

            RewindVideo(vm);
            base.OnPreviewMouseUp(e);
        }
Example #14
0
        private Grid CreateRankImageView(double width, ChannelTemplate template, double height)
        {
            VideoViewModel videoData = new VideoViewModel
            {
                name      = template.name,
                jumpType  = template.jumpType,
                subjectId = template.subjectId,
                picUrl    = template.picUrl,
                playUrl   = template.playUrl,
                tag       = template.tag,
                desc      = template.desc,
                videoId   = template.videoId,
                hotDegree = template.hotDegree,
                webUrl    = template.webUrl,
                rank      = template.rank
            };

            if (string.IsNullOrEmpty(rankXaml))
            {
                using (Stream stream = Application.GetResourceStream(new Uri("/MangGuoTv;component/Views/RankImageView.xaml", UriKind.Relative)).Stream)
                {
                    using (StreamReader reader = new StreamReader(stream))
                    {
                        rankXaml = reader.ReadToEnd();
                    }
                }
            }
            Grid imageGrid = (Grid)XamlReader.Load(rankXaml);

            imageGrid.Width       = width;
            imageGrid.Height      = height;
            imageGrid.DataContext = videoData;
            imageGrid.Tap        += new EventHandler <System.Windows.Input.GestureEventArgs>(GridImage_Tap);
            return(imageGrid);
        }
Example #15
0
        //URLから適当なViewを開く
        public static TabItemViewModel Open(string url, bool addtab = true)
        {
            /*if(Keyboard.IsKeyDown(Key.LeftShift) || Keyboard.IsKeyDown(Key.RightShift)) {
             *
             *  System.Diagnostics.Process.Start(url);
             *  return null;
             * }*/

            if (url.StartsWith("http://www.nicovideo.jp/watch/"))
            {
                var vm = new VideoViewModel(url);

                if (addtab)
                {
                    App.ViewModelRoot.AddTabAndSetCurrent(vm);
                }
                vm.Initialize();
                return(vm);
            }
            else if (url.StartsWith("http://www.nicovideo.jp/user/"))
            {
                var vm = new UserViewModel(url);

                if (addtab)
                {
                    App.ViewModelRoot.AddTabAndSetCurrent(vm);
                }
                return(vm);
            }
            else if (url.StartsWith("http://www.nicovideo.jp/mylist/"))
            {
                var vm = new PublicMylistViewModel(url);

                if (addtab)
                {
                    App.ViewModelRoot.AddTabAndSetCurrent(vm);
                }
                return(vm);
            }
            else if (url.StartsWith("http://com.nicovideo.jp/community/"))
            {
                var vm = new CommunityViewModel(url);

                if (addtab)
                {
                    App.ViewModelRoot.AddTabAndSetCurrent(vm);
                }
                return(vm);
            } /*else if(url.StartsWith("http://live.nicovideo.jp/watch/")) {
               *
               * var vm = new LiveViewModel(url);
               * App.ViewModelRoot.AddTabAndSetCurrent(vm);
               * return vm;
               * }*/
            else
            {
                System.Diagnostics.Process.Start(url);
                return(null);
            }
        }
Example #16
0
        public VideoViewModel GetVideoById(int video_id)
        {
            var video = DAManager.VideosRepository.Get(v => v.VideoId == video_id, null, "VideoTags").FirstOrDefault();

            if (video != null)
            {
                VideoViewModel video_viewmodel = new VideoViewModel()
                {
                    VideoId = video.VideoId, Title = video.Title, Description = video.Description, IsPublished = video.IsPublished, MetaDescription = video.MetaDescription, MetaTitle = video.MetaTitle, AuthorId = video.AuthorId, PublishDate = video.PublishDate, CountOfViews = video.NumberOfViews, URL = video.URL, YoutubeId = video.YoutubeId
                };
                video_viewmodel.DurationMinutes = (int)((video.Duration ?? 0) / 60);
                video_viewmodel.DurationSeconds = (int)((video.Duration ?? 0) % 60);


                video_viewmodel.CategoryId = video.CategoryId;

                video_viewmodel.Tags = new List <string>();
                if (video.VideoTags.Count > 0)
                {
                    foreach (VideoTag AT in video.VideoTags)
                    {
                        video_viewmodel.Tags.Add(AT.Tag);
                    }
                }

                return(video_viewmodel);
            }
            else
            {
                return(null);
            }
        }
Example #17
0
 public ActionResult VideoConcrete(int videoId)
 {
     using (IVideoService videoService = ServiceCreator.CreateVideoService(Connection))
     {
         VideoDTO videoDto = videoService.GetVideo(videoId);
         if (videoDto != null)
         {
             var config = new MapperConfiguration(cfg =>
             {
                 cfg.CreateMap <VideoDTO, VideoViewModel>();
             });
             var            mapper  = config.CreateMapper();
             VideoViewModel videoVM = new VideoViewModel();
             videoVM = mapper.Map <VideoDTO, VideoViewModel>(videoDto);
             UserDTO user = videoDto.UsersLiked.Where(u => u.UserName == User.Identity.Name).FirstOrDefault();
             if (user != null)
             {
                 videoVM.Liked = true;
             }
             else
             {
                 videoVM.Liked = false;
             }
             videoVM.LikesCount = videoDto.UsersLiked.Count();
             return(View(videoVM));
         }
     }
     return(HttpNotFound());
 }
Example #18
0
        public static Video ToBaseModel(this VideoViewModel videoModel)
        {
            if (videoModel == null)
            {
                return(null);
            }

            return(new Video()
            {
                Id = videoModel.id,
                Author = videoModel.author,
                CodeHTML = videoModel.codeHTML,
                Description = videoModel.description,
                DateChanged = videoModel.dateChanged,
                DateCreated = videoModel.dateCreated,
                DateDisplayed = videoModel.dateDisplayed,
                Enable = videoModel.enable,
                ExternalId = videoModel.externalId,
                Header = videoModel.header,
                Priority = videoModel.priority,
                Title = videoModel.title,
                URLKey = videoModel.urlKey,
                Visibility = videoModel.visibility
            });
        }
Example #19
0
        public ActionResult AddVideo(int playlistId)
        {
            VideoViewModel videoVM = new VideoViewModel();

            videoVM.PlaylistId = playlistId;
            return(View(videoVM));
        }
Example #20
0
        //[ValidateAntiForgeryToken]
        public ActionResult UploadVideo([Bind(Exclude = "UserVideos")] VideoViewModel model)
        {
            List <Video> all = new List <Video>();

            var video = new Video {
            };

            byte[] imageData = null;
            if (Request.Files.Count > 0)
            {
                HttpPostedFileBase poImgFile = Request.Files["UserVideo"];

                using (var binary = new BinaryReader(poImgFile.InputStream))
                {
                    imageData = binary.ReadBytes(poImgFile.ContentLength);
                }
            }
            using (ApplicationDbContext db = new ApplicationDbContext())

            {
                var UserId = User.Identity.GetUserId();
                video.UserVideo  = imageData;
                video.FromUserId = UserId;
                db.Video.Add(video);
                db.SaveChanges();
            }

            return(View());
        }
Example #21
0
        public static Status AddFavorite(VideoViewModel vm, string userId, string token)
        {
            vm.Status = "お気に入りに登録中";


            var add = "http://www.nicovideo.jp/api/watchitem/add";

            var formData = new Dictionary <string, string>();

            formData["item_type"] = "1";
            formData["item_id"]   = userId;
            formData["token"]     = token;
            try {
                var request = new HttpRequestMessage(HttpMethod.Post, add);

                request.Content = new FormUrlEncodedContent(formData);


                var a = NicoNicoWrapperMain.Session.GetAsync(request).Result;

                vm.VideoData.ApiData.UploaderIsFavorited = true;

                vm.Status = "";

                return(Status.Success);
            } catch (RequestTimeout) {
                vm.Status = "お気に入り登録に失敗しました。";
                return(Status.Failed);
            }
        }
        public async Task <IActionResult> Create([FromBody] VideoViewModel body)
        {
            try
            {
                var entity = await _unitOfWork.Videos.GetAsync(u => u.Id == body.Id);

                if (entity != null)
                {
                    return(Payloader.Fail(PayloadCode.Duplication));
                }

                var newEntity = new Video
                {
                    Title = body.Title,
                    Uri   = body.Uri,
                };

                await _unitOfWork.Videos.AddAsync(newEntity);

                await _unitOfWork.CommitAsync();

                return(Payloader.Success(_mapper.Map <VideoViewModel>(newEntity)));
            }
            catch (Exception ex)
            {
                return(Payloader.Error(ex));
            }
        }
Example #23
0
        public static Status DeleteFavorite(VideoViewModel vm, string userId, string token)
        {
            vm.Status = "お気に入り解除中";


            var del = "http://www.nicovideo.jp/api/watchitem/delete";

            var formData = new Dictionary <string, string>();

            formData["id_list[1][]"] = userId;
            formData["token"]        = token;

            try {
                var request = new HttpRequestMessage(HttpMethod.Post, del);

                request.Content = new FormUrlEncodedContent(formData);

                var a = NicoNicoWrapperMain.Session.GetAsync(request).Result;

                vm.VideoData.ApiData.UploaderIsFavorited = false;
                vm.Status = "";

                return(Status.Success);
            } catch (RequestTimeout) {
                vm.Status = "お気に入り解除に失敗しました。";
                return(Status.Failed);
            }
        }
Example #24
0
        // GET: Videos/Edit/5
        public async Task <IActionResult> Edit(int?id)
        {
            if (id == null)
            {
                return(NotFound());
            }

            var video = await _context.Videos.FirstOrDefaultAsync(m => m.Id == id);

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

            var videoViewModel = new VideoViewModel
            {
                Id               = video.Id,
                Name             = video.Name,
                Location         = video.Location,
                Link             = video.Link,
                OldThumbnailName = video.ThumbnailName
            };

            return(View(videoViewModel));
        }
        public async void AddVideo_CalledWithValidVideo_ReturnsOk()
        {
            IUnitOfWork    unitOfWork    = Substitute.For <IUnitOfWork>();
            IVideoManager  videoManager  = Substitute.For <IVideoManager>();
            ICookieManager cookieManager = Substitute.For <ICookieManager>();
            var            context       = Substitute.For <HttpContext>();

            long testId    = 1;
            var  testVideo = new VideoViewModel()
            {
                ModuleContentId = testId
            };
            var    testModuleContent = new ModuleContent();
            string testUrl           = "testurl";
            string convertedUrl      = "converted";
            string testyoutubeId     = "youtubeid";

            unitOfWork.ModuleContents.GetById(testId).Returns(testModuleContent);
            videoManager.ConvertUrl(testUrl).Returns(convertedUrl);
            videoManager.GetYoutubeId(convertedUrl).Returns(testyoutubeId);
            cookieManager.GetRoleFromToken(Arg.Any <string>()).Returns(Role.Admin.ToString());

            var videosController = new VideosController(unitOfWork, videoManager, cookieManager);

            videosController.ControllerContext = new ControllerContext()
            {
                HttpContext = context
            };

            var result = await videosController.AddVideo(testVideo);

            var okResult = Assert.IsType <OkResult>(result);

            Assert.Equal(200, okResult.StatusCode);
        }
        public ActionResult Index()
        {
            var model = new List <VideoViewModel>();

            var videos = db.Videos.OrderByDescending(o => o.Id).ToList();

            foreach (var video in videos)
            {
                var viewModel = new VideoViewModel();
                viewModel.Id             = video.Id;
                viewModel.EncodedAssetId = video.EncodedAssetId;
                viewModel.IsEncrypted    = video.IsEncrypted;
                viewModel.LocatorUri     = video.LocatorUri;
                viewModel.Status         = AzureMediaAsset.GetEncodingJobStatus(video.EncodingJobId);

                // If encrypted content, then get token to play
                if (video.IsEncrypted)
                {
                    IAsset asset = GetAssetById(video.EncodedAssetId);
                    viewModel.Token = AzureMediaAsset.GetTestToken(asset.Id, asset);
                }

                model.Add(viewModel);
            }

            return(View(model));
        }
Example #27
0
        public async Task <IActionResult> OnPostConvertAsync(string youtubeUrl)
        {
            try
            {
                var video = await _youtubeService.GetVideoAsync(youtubeUrl);

                var mp3FileName = string.Format(_mp3StringFileNameFormat, video.Title);

                var videoBytes = await video.GetBytesAsync();

                Video = new VideoViewModel
                {
                    VideoIsConverted = true,
                    Title            = video.Title,
                };

                var cacheKey = string.Format(_videoContentCacheKeyFormat, video.Title);

                _cache.Set(cacheKey, videoBytes);
                _cache.Set(_titleCacheKey, video.Title);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.Message);
            }

            return(null);
        }
Example #28
0
 public RememberByName(Settings Settings,
                       VideoViewModel VideoViewModel,
                       AudioSource AudioSource,
                       IRegionProvider RegionProvider,
                       IWebCamProvider WebCamProvider,
                       ScreenShotViewModel ScreenShotViewModel,
                       // ReSharper disable SuggestBaseTypeForParameter
                       ScreenSourceProvider ScreenSourceProvider,
                       WindowSourceProvider WindowSourceProvider,
                       RegionSourceProvider RegionSourceProvider,
                       NoVideoSourceProvider NoVideoSourceProvider,
                       DeskDuplSourceProvider DeskDuplSourceProvider
                       // ReSharper restore SuggestBaseTypeForParameter
                       )
 {
     _settings               = Settings;
     _videoViewModel         = VideoViewModel;
     _audioSource            = AudioSource;
     _regionProvider         = RegionProvider;
     _webCamProvider         = WebCamProvider;
     _screenShotViewModel    = ScreenShotViewModel;
     _screenSourceProvider   = ScreenSourceProvider;
     _windowSourceProvider   = WindowSourceProvider;
     _regionSourceProvider   = RegionSourceProvider;
     _noVideoSourceProvider  = NoVideoSourceProvider;
     _deskDuplSourceProvider = DeskDuplSourceProvider;
 }
        public Task <HttpResponseMessage> Get(Guid videoId)
        {
            HttpStatusCode httpStatusCode;
            VideoViewModel video = null;

            try
            {
                video = _videoAppService.GetById(videoId);

                if (video == null)
                {
                    httpStatusCode = HttpStatusCode.NotFound;
                }
                else
                {
                    httpStatusCode = HttpStatusCode.OK;
                }
            }
            catch (Exception e)
            {
                httpStatusCode = HttpStatusCode.InternalServerError;
            }

            HttpResponseMessage httpResponseMessage        = Request.CreateResponse(httpStatusCode, video);
            TaskCompletionSource <HttpResponseMessage> tsc = new TaskCompletionSource <HttpResponseMessage>();

            tsc.SetResult(httpResponseMessage);
            return(tsc.Task);
        }
Example #30
0
        private void RankListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ChannelTemplate template = RankListBox.SelectedItem as ChannelTemplate;

            if (template != null)
            {
                VideoViewModel videoData = new VideoViewModel
                {
                    width     = 150,
                    hight     = 130,
                    name      = template.name,
                    jumpType  = template.jumpType,
                    subjectId = template.subjectId,
                    picUrl    = template.picUrl,
                    playUrl   = template.playUrl,
                    tag       = template.tag,
                    desc      = template.desc,
                    videoId   = template.videoId,
                    hotDegree = template.hotDegree,
                    webUrl    = template.webUrl,
                    rank      = template.rank
                };
                OperationImageTap(videoData);
            }
        }
Example #31
0
 public ActionResult AddVideo(VideoViewModel model, string[] names)
 {
     if (ModelState.IsValid)
     {
         List <Skill> skills = new List <Skill>();
         foreach (var item in names.Where(x => x != "false"))
         {
             skills.Add(skillService.Get(item));
         }
         try
         {
             materialService.CreateVideo(model.Name,
                                         model.Link,
                                         model.Length,
                                         model.Quality,
                                         skills);
             return(RedirectToAction("Index", "Home"));
         }
         catch (ArgumentException ex)
         {
             ViewBag.Error = ex.Message;
             return(View("Error"));
         }
     }
     else
     {
         ViewBag.Skills = skillService.Get();
         return(View(model));
     }
 }
        public async Task ReloadVideoAsync()
        {
            var manager = JryVideoCore.Current.CurrentDataCenter.VideoManager;

            var video = await manager.FindAsync(this.InfoView.Source.Id);

            if (video == null)
            {
                this.Video = null;
            }
            else
            {
                this.Video = new VideoViewModel(video);

                this.EntitesView.Collection.Clear();
                this.EntitesView.Collection.AddRange(video.Entities
                    .Select(z => new EntityViewModel(z))
                    .GroupBy(v => v.Source.Resolution ?? "unknown")
                    .OrderBy(z => z.Key)
                    .Select(g => new ObservableCollectionGroup<string, EntityViewModel>(g.Key, g.OrderBy(this.CompareEntityViewModel))));
            }

            this.ReloadEpisodes();
        }
Example #33
0
        public override void OnApplyTemplate() {
            //csCommon.Resources.FloatingStyles fs = new FloatingStyles();
            //var ct = fs.FindName("SimpleFloatingStyle") as ControlTemplate;

            base.OnApplyTemplate();
            if (DesignerProperties.GetIsInDesignMode(this)) return;

            AppStateSettings.Instance.FullScreenFloatingElementChanged += InstanceFullScreenFloatingElementChanged;


            if (_fe.Style != null) {
                SetBinding(StyleProperty,
                    new Binding {
                        Source = _fe,
                        Path = new PropertyPath("Style"),
                        Mode = BindingMode.TwoWay,
                        UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
                    });
            }

            //this.Style = this.FindResource("SimpleContainer") as Style;

            _svi.BorderThickness = new Thickness(0, 0, 0, 0);

            _svi.SingleInputRotationMode = (_fe.RotateWithFinger)
                ? SingleInputRotationMode.Default
                : SingleInputRotationMode.Disabled;

            _svi.ContainerManipulationDelta += _svi_ScatterManipulationDelta;


            _fe.ScatterViewItem = _svi;

            if (!_fe.ShowShadow) {
                SurfaceShadowChrome ssc;
                ssc = _svi.Template.FindName("shadow", _svi) as SurfaceShadowChrome;
                _svi.BorderBrush = null;
                _svi.Background = null;
                if (ssc != null) ssc.Visibility = Visibility.Hidden;
            }

            var closeButton = GetTemplateChild("PART_Close") as Button;
            if (closeButton != null)
                closeButton.Click += CloseButtonClick;

            _partAssociation = GetTemplateChild("PART_Association") as Line;
            _partContent = GetTemplateChild("PART_Content") as Grid;
            _partPreview = GetTemplateChild("PART_Preview") as FrameworkElement;
            _partStream = GetTemplateChild("PART_Stream") as SurfaceButton;
            _cpView = GetTemplateChild("cpView") as FrameworkElement;
            if (_fe == null) return;
            DataContext = _fe;

            _fe.CloseRequest += FeCloseRequest;
            _fe.ResetRequest += _fe_ResetRequest;


            _svi.SetBinding(WidthProperty,
                new Binding {Source = _fe, Path = new PropertyPath("Width"), Mode = BindingMode.Default});
            _svi.SetBinding(HeightProperty,
                new Binding {Source = _fe, Path = new PropertyPath("Height"), Mode = BindingMode.Default});

            _resize = GetTemplateChild("bResize") as Border;
            if (_resize != null) {
                SetResize(_resize);
            }

            UpdateAssociatedLine();

            var resizeBack = GetTemplateChild("bResize1") as Border;
            if (resizeBack != null) {
                SetResize(resizeBack);
            }

            _cc = GetTemplateChild("cpView") as ContentControl;

            // check for document, if not exist use ModelInstance
            if (_fe.Document != null) {
                IDocument vm = null;
                _fe.ConnectChannel = _fe.Document.Channel;
                _fe.ConnectMessage = _fe.Document.ToString();
                switch (_fe.Document.FileType) {
                    case FileTypes.image:
                        vm = new ImageViewModel {Doc = _fe.Document};
                        break;
                    case FileTypes.imageFolder:
                        vm = new ImageFolderViewModel {Doc = _fe.Document};
                        break;
                    case FileTypes.xps:
                        vm = new XpsViewModel {Doc = _fe.Document};
                        break;
                    case FileTypes.video:
                        vm = new VideoViewModel {Doc = _fe.Document};
                        break;
                    case FileTypes.web:
                        vm = new WebViewModel {Doc = _fe.Document};
                        break;
                    case FileTypes.html:
                        vm = new HtmlViewModel {Doc = _fe.Document};
                        break;
                }
                if (vm != null) {
                    var b = ViewLocator.LocateForModel(vm, null, null) as FrameworkElement;
                    if (b != null) {
                        b.Width = double.NaN;
                        b.Height = double.NaN;
                        b.HorizontalAlignment = HorizontalAlignment.Stretch;
                        b.VerticalAlignment = VerticalAlignment.Stretch;
                        ViewModelBinder.Bind(vm, b, null);
                        if (_cc != null) _cc.Content = b;
                    }
                }
            }
            else if (_fe.ModelInstance != null) {
                try {
                    var b = ViewLocator.LocateForModel(_fe.ModelInstance, null, null) as FrameworkElement;
                    if (b != null) {
                        b.HorizontalAlignment = HorizontalAlignment.Stretch;
                        b.VerticalAlignment = VerticalAlignment.Stretch;
                        ViewModelBinder.Bind(_fe.ModelInstance, b, null);
                        if (_cc != null) _cc.Content = b;
                    }
                }
                catch (Exception e) {
                    Logger.Log("Floating Container", "Error adding floating element", e.Message, Logger.Level.Error);
                }
            }

            UpdateBackInstance();

            if (_fe.DockingStyle == DockingStyles.None)
                if (_partPreview != null) _partPreview.Visibility = Visibility.Collapsed;

            _svi.PreviewTouchDown += (e, s) => {
                if (_svi.TouchesOver.Count() == 4) {
                    SwitchFullscreen();
                    s.Handled = true;
                    _svi.ReleaseAllTouchCaptures();
                }
                //return;
                // FIXME TODO: Unreachable code
//                if (!InteractiveSurface.PrimarySurfaceDevice.IsFingerRecognitionSupported)
//                    return;
//
//
//                _touchDown = DateTime.Now;
//                if (s.TouchDevice.GetIsFingerRecognized()) {
//                    _fe.OriginalOrientation = s.Device.GetOrientation(this);
//                    //double angle = s.TouchDevice.GetOrientation(Application.Current.MainWindow);
//                    //_reverse = (angle < 180);
//                }
//
//                if (!s.TouchDevice.GetIsFingerRecognized() &&
//                    !s.TouchDevice.GetIsTagRecognized()) {
//                    if (!string.IsNullOrEmpty(_fe.ConnectChannel) &&
//                        DateTime.Now > _lastBlobEvent.AddSeconds(1)) {
//                        AppStateSettings.Instance.Imb.SendMessage(_fe.ConnectChannel,
//                            _fe.ConnectMessage);
//                        s.Handled = true;
//                        _lastBlobEvent = DateTime.Now;
//                    }
//                }


                //Console.WriteLine(d.ToString());
            };
            //_svi.PreviewTouchUp += (e, s) =>
            //            {
            //              if (!_fe.Large && _touchDown.AddMilliseconds(300) > DateTime.Now && _fe.LastContainerPosition!=null)
            //              {
            //                ResetLastPosition();
            //              }
            //            };

            _svi.PreviewMouseDown += (e, s) => { _touchDown = DateTime.Now; };
            _svi.PreviewMouseUp += (e, s) => {
                if (!_fe.Large && _touchDown.AddMilliseconds(300) > DateTime.Now &&
                    _fe.LastContainerPosition != null) {
                    ResetLastPosition();
                }
            };

            if (_fe.IsFullScreen) {
                FrameworkElement fe = Application.Current.MainWindow;
                _svi.Center = new Point(fe.Width/2, fe.Height/2);
                _svi.Width = fe.Width;
                _svi.Height = fe.Height;
                _svi.Opacity = _fe.OpacityNormal;
            }

            if (_partStream != null) {
                _partStream.Click += _partStream_Click;
            }

            //b.HorizontalAlignment = HorizontalAlignment.Stretch;
            //b.VerticalAlignment = VerticalAlignment.Stretch;
        }