internal static void Main()
        {
            // Create book
            var book = new Book("Microsoft", "CLR via C# 4", 10);
            book.Display();
            Console.WriteLine(new string('-', 60));

            // Create video
            var video = new Video("Stanley Kubrick", "A Clockwork Orange", 23, 92);
            video.Display();
            Console.WriteLine(new string('-', 60));

            // Make book borroable, then borrow and display
            Console.WriteLine("Making book borrowable:");
            var borrowableBook = new Borrowable(book);
            borrowableBook.BorrowItem("Nikolay Kostov");
            borrowableBook.BorrowItem("Ivaylo Kenov");
            borrowableBook.Display();
            Console.WriteLine(new string('-', 60));

            // Make video borrowable, then borrow and display
            Console.WriteLine("Making video borrowable:");
            var borrowableVideo = new Borrowable(video);
            borrowableVideo.BorrowItem("Nikolay Kostov");
            borrowableVideo.BorrowItem("Ivaylo Kenov");
            borrowableVideo.Display();
            Console.WriteLine(new string('-', 60));

            // Make only video buyable
            Console.WriteLine("Making video buyable:");
            var buyableAndBorrowableVideo = new Buyable(borrowableVideo, 15);
            buyableAndBorrowableVideo.Display();
            Console.WriteLine(new string('-', 60));
        }
    private static void HandleDownloadSubtitle(Video video)
    {
        var subtitleProcess = new BackgroundProcessor<Action>(2, action => action(), "Subtitle provider");

        var subtitleController = new SubtitleProviderProcessor(Logger.LoggerInstance, SubtitleProviderProcessor.ProvideRequestSourceEnum.Ui);
        subtitleProcess.Inject(() => subtitleController.ProvideSubtitleForVideo(video));
    }
 public HttpResponseMessage Get(string fileExtension = "mp4")
 {
     var video = new Video(fileExtension);
     var response = Request.CreateResponse();
     response.Content = new PushStreamContent(async (Stream outputStream, HttpContent content, TransportContext context) => { await video.StreamVideo(outputStream, content, context); }, new MediaTypeHeaderValue(String.Format("video/{0}", fileExtension)));
     return response;
 }
Пример #4
0
        public void Encode(Video video)
        {
            Console.WriteLine("Encoding Video....");
            Thread.Sleep(3000);

            OnVideoEncoded(video);
        }
        public WebDriverRecorder(int fps) 
        {
            this.fps = fps;
            if (WebDriverTestBase.browser == WebDriverBrowser.Browser.Android)
            {
                this.screensize = new Size(300, 500);
            }
            else
            {
                this.screensize = new Size(1024,768);
            }
            
            this.frameDelayMs = 1000/fps;
            //Common.Log("The current dimensions are : " + screensize.Width + " x " + screensize.Height);
            video = new FlashScreenVideo(new FlashScreenVideoParameters(screensize.Width, screensize.Height, fps));

            screenshotGetter = new BackgroundWorker();
            screenshotGetter.DoWork += screenshotGetter_DoWork;
            screenshotGetter.WorkerSupportsCancellation = true;
            screenshotGetter.RunWorkerAsync();

            videoBuilder = new BackgroundWorker();
            videoBuilder.DoWork += videoBuilder_DoWork;
            videoBuilder.WorkerSupportsCancellation = true;
            videoBuilder.RunWorkerAsync();

        }
Пример #6
0
 protected virtual void OnVideoEncoded(Video video)
 {
     if (VideoEncoded != null)
     {
         VideoEncoded(this, new VideoEventArgs() {Video = video});//EventArgs.Empty);
     }
 }
Пример #7
0
        /// <summary>
        /// Determines whether [is eligible for chapter image extraction] [the specified video].
        /// </summary>
        /// <param name="video">The video.</param>
        /// <returns><c>true</c> if [is eligible for chapter image extraction] [the specified video]; otherwise, <c>false</c>.</returns>
        private bool IsEligibleForChapterImageExtraction(Video video)
        {
            if (video.IsPlaceHolder)
            {
                return false;
            }

            if (video is Movie)
            {
                if (!_config.Configuration.EnableMovieChapterImageExtraction)
                {
                    return false;
                }
            }
            else if (video is Episode)
            {
                if (!_config.Configuration.EnableEpisodeChapterImageExtraction)
                {
                    return false;
                }
            }
            else
            {
                if (!_config.Configuration.EnableOtherVideoChapterImageExtraction)
                {
                    return false;
                }
            }

            // Can't extract images if there are no video streams
            return video.DefaultVideoStreamIndex.HasValue;
        }
Пример #8
0
		private void init(string filename, Stream stream, ShaderVersions shaderVersion, ShaderFloatingPointQuality vsQuality, ShaderFloatingPointQuality psQuality, Loader.LoadedCallbackMethod loadedCallback)
		#endif
		{
			try
			{
				video = Parent.FindParentOrSelfWithException<Video>();

				#if WIN32
				shaderVersion = (shaderVersion == ShaderVersions.Max) ? video.Cap.MaxShaderVersion : shaderVersion;
				var code = getShaders(stream);
				vertex = new VertexShader(this, code[0], shaderVersion);
				pixel = new PixelShader(this, code[1], shaderVersion);
				#else
				await getReflections(filename);
				var code = getShaders(stream);
				vertex = new VertexShader(this, code[0]);
				pixel = new PixelShader(this, code[1]);
				#endif

				variables = new List<ShaderVariable>();
				resources = new List<ShaderResource>();
			}
			catch (Exception e)
			{
				FailedToLoad = true;
				Loader.AddLoadableException(e);
				Dispose();
				if (loadedCallback != null) loadedCallback(this, false);
				return;
			}

			Loaded = true;
			if (loadedCallback != null) loadedCallback(this, true);
		}
Пример #9
0
        protected override void SetupFixtureContext()
        {
            _mocks = new RhinoAutoMocker<VideosController>();
            Controller = _mocks.ClassUnderTest;

            _video = new Video() {Id = Guid.NewGuid()};
        }
Пример #10
0
        public ActionResult Add(string t, string k, string d, string imageurl, string u, string um)
        {
            string result = "发布失败";

            if (Session["UserId"] == null)
            {
                return Content("长时间未操作,请重新登录。");
            }

            if (!string.IsNullOrEmpty(t) && !string.IsNullOrEmpty(k) && !string.IsNullOrEmpty(d) && !string.IsNullOrEmpty(imageurl) && !string.IsNullOrEmpty(u) && !string.IsNullOrEmpty(um))
            {
                Video video = new Video();
                video.Title = t;
                video.Keywords = k;
                video.Description = d;
                video.Thumbnail = imageurl;
                video.Url = u;
                video.UrlM = um;
                video.InsertTime = DateTime.Now;
                video.ViewTime = 0;

                VideoService videoService = new VideoService();
                if (videoService.AddVideo(video))
                {
                    result = "success";
                }
            }
            else
            {
                result = "必填项不能为空";
            }
            return Content(result);
        }
Пример #11
0
 public override void Unload()
 {
     video = null;
     videoPlayer = null;
     videoTexture = null;
     //base.Unload();
 }
Пример #12
0
 /*
  * Constructor
  */
 public VideoAnimation(Rectangle windowAreaRectangle, Video video)
 {
     this.windowAreaRectangle = windowAreaRectangle;
     this.video = video;
     videoPlayer = new VideoPlayer();
     videoPlayer.IsLooped = false;
 }
Пример #13
0
 public void InsertOrUpdateVideo(Video video)
 {
     _context.Entry(video).State = video.VideoID == 0 ? EntityState.Added : EntityState.Modified;
     foreach (var videoAsset in video.Assets)
         _context.Entry(videoAsset).State = videoAsset.VideoAssetID == 0 ? EntityState.Added : EntityState.Modified;
     _context.SaveChanges();
 }
Пример #14
0
        public async Task<DynamicImageResponse> GetVideoImage(Video item, CancellationToken cancellationToken)
        {
            var isoMount = await MountIsoIfNeeded(item, cancellationToken).ConfigureAwait(false);

            try
            {
                // If we know the duration, grab it from 10% into the video. Otherwise just 10 seconds in.
                // Always use 10 seconds for dvd because our duration could be out of whack
                var imageOffset = item.VideoType != VideoType.Dvd && item.RunTimeTicks.HasValue &&
                                  item.RunTimeTicks.Value > 0
                                      ? TimeSpan.FromTicks(Convert.ToInt64(item.RunTimeTicks.Value * .1))
                                      : TimeSpan.FromSeconds(10);

                InputType type;

                var inputPath = MediaEncoderHelpers.GetInputArgument(item.Path, item.LocationType == LocationType.Remote, item.VideoType, item.IsoType, isoMount, item.PlayableStreamFileNames, out type);

                var stream = await _mediaEncoder.ExtractImage(inputPath, type, false, item.Video3DFormat, imageOffset, cancellationToken).ConfigureAwait(false);

                return new DynamicImageResponse
                {
                    Format = ImageFormat.Jpg,
                    HasImage = true,
                    Stream = stream
                };
            }
            finally
            {
                if (isoMount != null)
                {
                    isoMount.Dispose();
                }
            }
        }
 public override void LoadContent()
 {
     base.LoadContent();
     video = ScreenManager.Game.Content.Load<Video>("Video\\intro");
     videoPlayer = new VideoPlayer();
     videoPlayer.IsLooped = true;
 }
Пример #16
0
 public void DeleteVideo(int videoID)
 {
     var video = new Video() { VideoID = videoID };
     _context.Videos.Attach(video);
     _context.Videos.Remove(video);
     _context.SaveChanges();
 }
Пример #17
0
    public async Task<ActionResult> Create(string channelId) {
      var video = new Video {
        ChannelId = channelId
      };

      return View(video);
    }
Пример #18
0
        public List<Video> GetVideos()
        {
            VideoData.videosDataTable DT = db.GetVideos();
            List<Video> videos = new List<Video>();
            foreach (var item in DT)
            {
                Video vid = new Video();
                vid.Id = item.Video_ID;
                if (item.Url == null)
                    vid.Url = "";
                else
                    vid.Url = item.Url;
                if (item.Description == null)
                    vid.Description = "No Description";
                else
                    vid.Description = item.Description;
                if (item.Name == null)
                    vid.Name = "No Name";
                else
                    vid.Name = item.Name;

                videos.Add(vid);
            }

            return videos;

        }
Пример #19
0
        private async void GetAllVideos(StorageFolder KnownFolders, QueryOptions QueryOptions)
        {
            StorageFileQueryResult query = KnownFolders.CreateFileQueryWithOptions(QueryOptions);
            IReadOnlyList<StorageFile> folderList = await query.GetFilesAsync();

            // Get all the videos in the folder past in parameter
            int id = 0;
            foreach (StorageFile file in folderList)
            {
                using (StorageItemThumbnail thumbnail = await file.GetThumbnailAsync(ThumbnailMode.VideosView, 200, ThumbnailOptions.UseCurrentScale))
                {
                    // Get video's properties
                    VideoProperties videoProperties = await file.Properties.GetVideoPropertiesAsync();

                    BitmapImage VideoCover = new BitmapImage();
                    VideoCover.SetSource(thumbnail);

                    Video video = new Video();
                    video.Id = id;
                    video.Name = file.Name;
                    video.DateCreated = file.DateCreated.UtcDateTime;
                    video.FileType = file.FileType;
                    video.VideoPath = file.Path;
                    video.Duration = videoProperties.Duration;
                    video.VideoFile = file;
                    video.VideoCover = VideoCover;

                    // Add the video to the ObservableCollection
                    Videos.Add(video);
                    id++;
                }
            }
        }
Пример #20
0
		public void UpdateCell (Video video)
		{
			this.Video = video;
			this.LblText.Text = video.Title;
			Update (video);
			SetNeedsDisplay ();
		}
Пример #21
0
        public static Video[] GetVideoFromHtml(string html)
        {
            List<Video> ret = new List<Video>();
            RegexOptions regexOptions = RegexOptions.Singleline;
            Regex reg = new Regex("<table class=\"videotextlist\">.+</table>(?=<!-- end of videotextlist -->)", regexOptions);
            var m = reg.Match(html);
            if (m.Success)
            {
                string table = m.Value;
                Regex reg_actress = new Regex("<tr( class=\"dimrow\")?>.+?</tr>", regexOptions);
                var ms = reg_actress.Matches(table);
                foreach (Match match in ms)
                {
                    Video v = new Video();
                    string tr_html = match.Value;
                    Regex _reg = new Regex("<a href=\".+\".+?>");
                    var _title_all = _reg.Match(tr_html).Value;
                    _reg = new Regex("(?<=href=\"\\./\\?v=).+?(?=\")");
                    v.JL_Id = _reg.Match(_title_all).Value;
                    _reg = new Regex("(?<=title=\").+?(?=\")");
                    var _code_name = _reg.Match(_title_all).Value;
                    _reg = new Regex("[A-Z0-9]{2,6}-[A-Z0-9]{2,6}");
                    v.Code = _reg.Match(_code_name).Value;
                    v.Name = _code_name.Substring(v.Code.Length + 1);
                    _reg = new Regex("(?<=<td>)\\d{4}-\\d{2}-\\d{2}");
                    v.IssueDate = DateTime.Parse(_reg.Match(tr_html).Value);

                    ret.Add(v);
                }
            }
            return ret.ToArray();
        }
Пример #22
0
        public DepthStencil(DisposableI parent, int width, int height, DepthStencilFormats depthStencilFormats)
            : base(parent)
        {
            try
            {
                video = parent.FindParentOrSelfWithException<Video>();

                PixelFormat format = PixelFormat.None;
                switch (depthStencilFormats)
                {
                    case DepthStencilFormats.Defualt: format = PixelFormat.Depth16; break;
                    case DepthStencilFormats.Depth24Stencil8: format = PixelFormat.Depth24Stencil8; break;
                    case DepthStencilFormats.Depth16: format = PixelFormat.Depth16; break;
                    case DepthStencilFormats.Depth24: format = PixelFormat.Depth24; break;

                    default:
                        Debug.ThrowError("Video", "Unsuported DepthStencilFormat type");
                        break;
                }

                depthBuffer = new DepthBuffer(width, height, format);
            }
            catch (Exception e)
            {
                Dispose();
                throw e;
            }
        }
Пример #23
0
        private void videoPlayerBox_MouseDown(object sender, MouseEventArgs e)
        {
            var file = new OpenFileDialog();

            if(file.ShowDialog() == DialogResult.OK) {

                // videoPlayerBox.Dock = DockStyle.None;

                video = new Video(file.FileName, true);
                video.Owner = videoPlayerBox;

                var size = new Size();
                size.Width = video.Size.Width;
                size.Height = video.Size.Height;
                Width = size.Width + 16;
                Height = size.Height + 38;

                string fileName = Path.GetFileNameWithoutExtension(file.FileName);
                Text = fileName;
                // video.Fullscreen = true;
                // System.Threading.Thread.Sleep(3000);
                // FormBorderStyle = FormBorderStyle.None;
                // WindowState = FormWindowState.Maximized;
                // TopMost = true;
            }
        }
Пример #24
0
        public async Task<IHttpActionResult> PutVideo(string id, Video video)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            if (id != video.VideoId)
            {
                return BadRequest();
            }

            db.Entry(video).State = EntityState.Modified;

            try
            {
                await db.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!VideoExists(id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return StatusCode(HttpStatusCode.NoContent);
        }
Пример #25
0
 public GameVideo(Video video)
 {
     _video = video;
      _videoPlayer = new VideoPlayer();
      kinput = new KeyboardInput();
      gInput = new GamePadInput();
 }
Пример #26
0
        public async Task<IHttpActionResult> PostVideo(Video video)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            db.Videos.Add(video);

            try
            {
                await db.SaveChangesAsync();
            }
            catch (DbUpdateException)
            {
                if (VideoExists(video.VideoId))
                {
                    return Conflict();
                }
                else
                {
                    throw;
                }
            }

            return CreatedAtRoute("DefaultApi", new { id = video.VideoId }, video);
        }
Пример #27
0
        protected void OnVideoEncoded(Video video)
        {
            if (videoEncoded != null)
                //videoEncoded(this, new VideoEventArgs() { Video = video  });
                videoEncoded(this, new VideoEventArgs() { Video = video });

        }
Пример #28
0
        public void CreateVideoEntity(string embed,  VideoGallery gallery)
        {
            var embedCode = "";
            int pos = embed.LastIndexOf("/") + 1;
            embedCode = embed.Substring(pos, embed.Length - pos);

            VideoType videoType;

            if (embed.ToLower().Contains("youtu"))
            {
                videoType = VideoType.Youtube;
            }
            else if (embed.ToLower().Contains("vimeo"))
            {
                videoType = VideoType.Vimeo;
            }
            else
            {
                videoType = VideoType.Other;
            }

            var video = new Video
            {
                Embed = embedCode,
                VideoType = videoType,
                VideoGallery = gallery
            };

            this.CreateVideo(video);
        }
Пример #29
0
        public static Video check_pet_currentVideo(string _videolink, string _videotitle)
        {
            string url = _videolink;
            Video v = new Video(url, _videotitle);

            return v;
        }
Пример #30
0
        public ActionResult Create(Video video, Frame frame)
        {
            video.Frame = frame;

            if (ModelState.IsValid)
            {
                if (video.SavedContentId.HasValue)
                {
                    Content content = db.Contents.Find(video.SavedContentId.Value);
                    video.Contents.Add(content);
                    db.Videos.Add(video);
                    db.SaveChanges();

                    return this.RestoreReferrer() ?? RedirectToAction("Index", "Frame");
                }
                else
                {
                    TempData["_newVideo"] = video;
                    return RedirectToAction("Upload", "Video");
                }
            }

            this.FillTemplatesSelectList(db, FrameTypes.Video, video.Frame.TemplateId);
            FillVideosSelectList();

            return View(video);
        }
 public void Put(int id, [FromBody]Video value)
 {
 }
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        public void Run(AdWordsUser user)
        {
            using (MediaService mediaService =
                       (MediaService)user.GetService(AdWordsService.v201806.MediaService))
            {
                // Create a selector.
                Selector selector = new Selector()
                {
                    fields = new string[]
                    {
                        Media.Fields.MediaId,
                        Dimensions.Fields.Width,
                        Dimensions.Fields.Height,
                        Media.Fields.MimeType
                    },
                    predicates = new Predicate[]
                    {
                        Predicate.In(Media.Fields.Type, new string[]
                        {
                            MediaMediaType.VIDEO.ToString(),
                            MediaMediaType.IMAGE.ToString()
                        })
                    },
                    paging = Paging.Default
                };
                MediaPage page = new MediaPage();

                try
                {
                    do
                    {
                        page = mediaService.get(selector);

                        if (page != null && page.entries != null)
                        {
                            int i = selector.paging.startIndex;

                            foreach (Media media in page.entries)
                            {
                                if (media is Video)
                                {
                                    Video video = (Video)media;
                                    Console.WriteLine(
                                        "{0}) Video with id '{1}' and name '{2}' was found.", i + 1,
                                        video.mediaId, video.name);
                                }
                                else if (media is Image)
                                {
                                    Image image = (Image)media;
                                    Dictionary <MediaSize, Dimensions> dimensions =
                                        image.dimensions.ToDict();
                                    Console.WriteLine(
                                        "{0}) Image with id '{1}', dimensions '{2}x{3}', and " +
                                        "MIME type '{4}' was found.", i + 1, image.mediaId,
                                        dimensions[MediaSize.FULL].width,
                                        dimensions[MediaSize.FULL].height, image.mimeType);
                                }

                                i++;
                            }
                        }

                        selector.paging.IncreaseOffset();
                    } while (selector.paging.startIndex < page.totalNumEntries);

                    Console.WriteLine("Number of images and videos found: {0}",
                                      page.totalNumEntries);
                }
                catch (Exception e)
                {
                    throw new System.ApplicationException("Failed to get images and videos.", e);
                }
            }
        }
Пример #33
0
 private void UpdateVideoSettings()
 {
     this._surfaceVideo = Video.SetVideoMode(this._destinationSize.Width, this._destinationSize.Height, 32, false, false, this._fullScreen, false, true);
 }
Пример #34
0
        /// <summary>
        /// 根据XML信息填充实实体
        /// </summary>
        /// <typeparam name="T">MessageBase为基类的类型,Response和Request都可以</typeparam>
        /// <param name="entity">实体</param>
        /// <param name="doc">XML</param>
        public static void FillEntityWithXml <T>(this T entity, XDocument doc) where T : /*MessageBase*/ class, new()
        {
            entity = entity ?? new T();
            var root = doc.Root;

            var props = entity.GetType().GetProperties();

            foreach (var prop in props)
            {
                var propName = prop.Name;
                if (root.Element(propName) != null)
                {
                    switch (prop.PropertyType.Name)
                    {
                    //case "String":
                    //    goto default;
                    case "DateTime":
                    case "DateTimeOffset":
                    case "Int32":
                    case "Int32[]":     //增加int[]
                    case "Int64":
                    case "Int64[]":     //增加long[]
                    case "Double":
                    case "Nullable`1":  //可为空对象
                        EntityUtility.FillSystemType(entity, prop, root.Element(propName).Value);
                        break;

                    case "Boolean":
                        if (propName == "FuncFlag")
                        {
                            EntityUtility.FillSystemType(entity, prop, root.Element(propName).Value == "1");
                        }
                        else
                        {
                            goto default;
                        }
                        break;

                    //以下为枚举类型
                    case "ContactChangeType":
                        //已设为只读
                        //prop.SetValue(entity, MsgTypeHelper.GetRequestMsgType(root.Element(propName).Value), null);
                        break;

                    case "RequestMsgType":
                        //已设为只读
                        //prop.SetValue(entity, MsgTypeHelper.GetRequestMsgType(root.Element(propName).Value), null);
                        break;

                    case "ResponseMsgType":     //Response适用
                                                //已设为只读
                                                //prop.SetValue(entity, MsgTypeHelper.GetResponseMsgType(root.Element(propName).Value), null);
                        break;

                    case "ThirdPartyInfo":     //ThirdPartyInfo适用
                                               //已设为只读
                                               //prop.SetValue(entity, MsgTypeHelper.GetResponseMsgType(root.Element(propName).Value), null);
                        break;

                    case "Event":
                        //已设为只读
                        //prop.SetValue(entity, EventHelper.GetEventType(root.Element(propName).Value), null);
                        break;

                    //以下为实体类型
                    case "List`1":                                 //List<T>类型,ResponseMessageNews适用
                        var genericArguments = prop.PropertyType.GetGenericArguments();
                        if (genericArguments[0].Name == "Article") //ResponseMessageNews适用
                        {
                            //文章下属节点item
                            List <Article> articles = new List <Article>();
                            foreach (var item in root.Element(propName).Elements("item"))
                            {
                                var article = new Article();
                                FillEntityWithXml(article, new XDocument(item));
                                articles.Add(article);
                            }
                            prop.SetValue(entity, articles, null);
                        }
                        else if (genericArguments[0].Name == "MpNewsArticle")
                        {
                            List <MpNewsArticle> mpNewsArticles = new List <MpNewsArticle>();
                            foreach (var item in root.Elements(propName))
                            {
                                var mpNewsArticle = new MpNewsArticle();
                                FillEntityWithXml(mpNewsArticle, new XDocument(item));
                                mpNewsArticles.Add(mpNewsArticle);
                            }
                            prop.SetValue(entity, mpNewsArticles, null);
                        }
                        else if (genericArguments[0].Name == "PicItem")
                        {
                            List <PicItem> picItems = new List <PicItem>();
                            foreach (var item in root.Elements(propName).Elements("item"))
                            {
                                var    picItem   = new PicItem();
                                var    picMd5Sum = item.Element("PicMd5Sum").Value;
                                Md5Sum md5Sum    = new Md5Sum()
                                {
                                    PicMd5Sum = picMd5Sum
                                };
                                picItem.item = md5Sum;
                                picItems.Add(picItem);
                            }
                            prop.SetValue(entity, picItems, null);
                        }
                        break;

                    case "Image":     //ResponseMessageImage适用
                        Image image = new Image();
                        FillEntityWithXml(image, new XDocument(root.Element(propName)));
                        prop.SetValue(entity, image, null);
                        break;

                    case "Voice":     //ResponseMessageVoice适用
                        Voice voice = new Voice();
                        FillEntityWithXml(voice, new XDocument(root.Element(propName)));
                        prop.SetValue(entity, voice, null);
                        break;

                    case "Video":     //ResponseMessageVideo适用
                        Video video = new Video();
                        FillEntityWithXml(video, new XDocument(root.Element(propName)));
                        prop.SetValue(entity, video, null);
                        break;

                    case "ScanCodeInfo":     //扫码事件中的ScanCodeInfo适用
                        ScanCodeInfo scanCodeInfo = new ScanCodeInfo();
                        FillEntityWithXml(scanCodeInfo, new XDocument(root.Element(propName)));
                        prop.SetValue(entity, scanCodeInfo, null);
                        break;

                    case "SendLocationInfo":     //弹出地理位置选择器的事件推送中的SendLocationInfo适用
                        SendLocationInfo sendLocationInfo = new SendLocationInfo();
                        FillEntityWithXml(sendLocationInfo, new XDocument(root.Element(propName)));
                        prop.SetValue(entity, sendLocationInfo, null);
                        break;

                    case "SendPicsInfo":     //系统拍照发图中的SendPicsInfo适用
                        SendPicsInfo sendPicsInfo = new SendPicsInfo();
                        FillEntityWithXml(sendPicsInfo, new XDocument(root.Element(propName)));
                        prop.SetValue(entity, sendPicsInfo, null);
                        break;

                    case "BatchJobInfo":     //异步任务完成事件推送BatchJob
                        BatchJobInfo batchJobInfo = new BatchJobInfo();
                        FillEntityWithXml(batchJobInfo, new XDocument(root.Element(propName)));
                        prop.SetValue(entity, batchJobInfo, null);
                        break;

                    case "AgentType":
                    {
                        AgentType tp;
                        if (Enum.TryParse(root.Element(propName).Value, out tp))
                        {
                            prop.SetValue(entity, tp, null);
                        }
                        break;
                    }

                    case "Receiver":
                    {
                        Receiver receiver = new Receiver();
                        FillEntityWithXml(receiver, new XDocument(root.Element(propName)));
                        prop.SetValue(entity, receiver, null);
                        break;
                    }

                    default:
                        prop.SetValue(entity, root.Element(propName).Value, null);
                        break;
                    }
                }
                else if (prop.PropertyType.Name == "List`1")//客服回调特殊处理
                {
                    var genericArguments = prop.PropertyType.GetGenericArguments();
                    if (genericArguments[0].Name == "RequestBase")
                    {
                        List <RequestBase> items = new List <RequestBase>();
                        foreach (var item in root.Elements("Item"))
                        {
                            RequestBase reqItem    = null;
                            var         msgTypeEle = item.Element("MsgType");
                            if (msgTypeEle != null)
                            {
                                RequestMsgType type         = RequestMsgType.Unknown;
                                var            parseSuccess = false;
                                parseSuccess = Enum.TryParse(msgTypeEle.Value, true, out type);
                                if (parseSuccess)
                                {
                                    switch (type)
                                    {
                                    case RequestMsgType.Event:
                                    {
                                        reqItem = new RequestEvent();
                                        break;
                                    }

                                    case RequestMsgType.File:
                                    {
                                        reqItem = new Entities.Request.KF.RequestMessageFile();
                                        break;
                                    }

                                    case RequestMsgType.Image:
                                    {
                                        reqItem = new Entities.Request.KF.RequestMessageImage();
                                        break;
                                    }

                                    case RequestMsgType.Link:
                                    {
                                        reqItem = new Entities.Request.KF.RequestMessageLink();
                                        break;
                                    }

                                    case RequestMsgType.Location:
                                    {
                                        reqItem = new Entities.Request.KF.RequestMessageLocation();
                                        break;
                                    }

                                    case RequestMsgType.Text:
                                    {
                                        reqItem = new Entities.Request.KF.RequestMessageText();

                                        break;
                                    }

                                    case RequestMsgType.Voice:
                                    {
                                        reqItem = new Entities.Request.KF.RequestMessageVoice();
                                        break;
                                    }
                                    }
                                }
                            }
                            if (reqItem != null)
                            {
                                FillEntityWithXml(reqItem, new XDocument(item));
                                items.Add(reqItem);
                            }
                        }
                        prop.SetValue(entity, items, null);
                    }
                }
            }
        }
 public PrepareForEncodingActivity(Video video, EncodingService encodingService)
 {
     _video           = video;
     _encodingService = encodingService;
 }
 public void Add(Video newVideo)
 {
     _context.Add(newVideo);
     _context.SaveChanges();
 }
        public PartialViewResult SearchResults(Video video)
        {
            List <Video> searchResults = new List <Video>();
            string       title         = string.Empty;
            string       director      = string.Empty;

            if (!video.Title.IsNullOrWhiteSpace())
            {
                title = video.Title.ToLower().Trim();
            }

            if (!video.Director.IsNullOrWhiteSpace())
            {
                director = video.Director.ToLower().Trim();
            }

            bool titleMatch    = false;
            bool yearMatch     = false;
            bool directorMatch = false;

            foreach (var vid in videoList)
            {
                titleMatch    = false;
                yearMatch     = false;
                directorMatch = false;

                if (vid.Title.ToLower().Contains(title) && title != "")
                {
                    titleMatch = true;
                }

                if (vid.Director.ToLower().Contains(director) && director != "")
                {
                    directorMatch = true;
                }

                if (vid.Year == video.Year)
                {
                    yearMatch = true;
                }

                //ABC
                if (!video.Title.IsNullOrWhiteSpace() && video.Year != null && !video.Director.IsNullOrWhiteSpace())
                {
                    if (titleMatch && yearMatch && directorMatch)
                    {
                        searchResults.Add(vid);
                    }
                }
                //AB
                else if (!video.Title.IsNullOrWhiteSpace() && video.Year != null)
                {
                    if (titleMatch && yearMatch)
                    {
                        searchResults.Add(vid);
                    }
                }
                //BC
                else if (video.Year != null && !video.Director.IsNullOrWhiteSpace())
                {
                    if (yearMatch && directorMatch)
                    {
                        searchResults.Add(vid);
                    }
                }
                //AC
                else if (!video.Title.IsNullOrWhiteSpace() && !video.Director.IsNullOrWhiteSpace())
                {
                    if (titleMatch && directorMatch)
                    {
                        searchResults.Add(vid);
                    }
                }
                else
                {
                    if (titleMatch || yearMatch || directorMatch)
                    {
                        searchResults.Add(vid);
                    }
                }
            }
            return(PartialView(searchResults));
        }
Пример #38
0
 public void Add(Video model)
 {
     this.context.Videos.Add(model);
     this.context.SaveChanges();
 }
Пример #39
0
        /// <summary>
        /// Adds the external subtitles.
        /// </summary>
        /// <param name="video">The video.</param>
        /// <param name="currentStreams">The current streams.</param>
        /// <param name="options">The refreshOptions.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>Task.</returns>
        private async Task AddExternalSubtitles(Video video,
                                                List <MediaStream> currentStreams,
                                                MetadataRefreshOptions options,
                                                CancellationToken cancellationToken)
        {
            var subtitleResolver = new SubtitleResolver(_localization, _fileSystem);

            var startIndex = currentStreams.Count == 0 ? 0 : (currentStreams.Select(i => i.Index).Max() + 1);
            var externalSubtitleStreams = subtitleResolver.GetExternalSubtitleStreams(video, startIndex, options.DirectoryService, false);

            var enableSubtitleDownloading = options.MetadataRefreshMode == MetadataRefreshMode.Default ||
                                            options.MetadataRefreshMode == MetadataRefreshMode.FullRefresh;

            var subtitleOptions = GetOptions();

            var libraryOptions = _libraryManager.GetLibraryOptions(video);

            string[] subtitleDownloadLanguages;
            bool     SkipIfEmbeddedSubtitlesPresent;
            bool     SkipIfAudioTrackMatches;
            bool     RequirePerfectMatch;
            bool     enabled;

            if (libraryOptions.SubtitleDownloadLanguages == null)
            {
                subtitleDownloadLanguages      = subtitleOptions.DownloadLanguages;
                SkipIfEmbeddedSubtitlesPresent = subtitleOptions.SkipIfEmbeddedSubtitlesPresent;
                SkipIfAudioTrackMatches        = subtitleOptions.SkipIfAudioTrackMatches;
                RequirePerfectMatch            = subtitleOptions.RequirePerfectMatch;
                enabled = (subtitleOptions.DownloadEpisodeSubtitles &&
                           video is Episode) ||
                          (subtitleOptions.DownloadMovieSubtitles &&
                           video is Movie);
            }
            else
            {
                subtitleDownloadLanguages      = libraryOptions.SubtitleDownloadLanguages;
                SkipIfEmbeddedSubtitlesPresent = libraryOptions.SkipSubtitlesIfEmbeddedSubtitlesPresent;
                SkipIfAudioTrackMatches        = libraryOptions.SkipSubtitlesIfAudioTrackMatches;
                RequirePerfectMatch            = libraryOptions.RequirePerfectSubtitleMatch;
                enabled = true;
            }

            if (enableSubtitleDownloading && enabled)
            {
                var downloadedLanguages = await new SubtitleDownloader(_logger,
                                                                       _subtitleManager)
                                          .DownloadSubtitles(video,
                                                             currentStreams.Concat(externalSubtitleStreams).ToList(),
                                                             SkipIfEmbeddedSubtitlesPresent,
                                                             SkipIfAudioTrackMatches,
                                                             RequirePerfectMatch,
                                                             subtitleDownloadLanguages,
                                                             libraryOptions.DisabledSubtitleFetchers,
                                                             libraryOptions.SubtitleFetcherOrder,
                                                             cancellationToken).ConfigureAwait(false);

                // Rescan
                if (downloadedLanguages.Count > 0)
                {
                    externalSubtitleStreams = subtitleResolver.GetExternalSubtitleStreams(video, startIndex, options.DirectoryService, true);
                }
            }

            video.SubtitleFiles = externalSubtitleStreams.Select(i => i.Path).ToArray();

            currentStreams.AddRange(externalSubtitleStreams);
        }
Пример #40
0
 public InsertVideoCommand(Video video) => Video = video;
Пример #41
0
        protected async Task Fetch(Video video,
                                   CancellationToken cancellationToken,
                                   Model.MediaInfo.MediaInfo mediaInfo,
                                   BlurayDiscInfo blurayInfo,
                                   MetadataRefreshOptions options)
        {
            List <MediaStream> mediaStreams;
            List <ChapterInfo> chapters;

            if (mediaInfo != null)
            {
                mediaStreams = mediaInfo.MediaStreams;

                video.TotalBitrate = mediaInfo.Bitrate;
                //video.FormatName = (mediaInfo.Container ?? string.Empty)
                //    .Replace("matroska", "mkv", StringComparison.OrdinalIgnoreCase);

                // For dvd's this may not always be accurate, so don't set the runtime if the item already has one
                var needToSetRuntime = video.VideoType != VideoType.Dvd || video.RunTimeTicks == null || video.RunTimeTicks.Value == 0;

                if (needToSetRuntime)
                {
                    video.RunTimeTicks = mediaInfo.RunTimeTicks;
                }

                if (video.VideoType == VideoType.VideoFile)
                {
                    var extension = (Path.GetExtension(video.Path) ?? string.Empty).TrimStart('.');

                    video.Container = extension;
                }
                else
                {
                    video.Container = null;
                }
                video.Container = mediaInfo.Container;

                chapters = mediaInfo.Chapters == null ? new List <ChapterInfo>() : mediaInfo.Chapters.ToList();
                if (blurayInfo != null)
                {
                    FetchBdInfo(video, chapters, mediaStreams, blurayInfo);
                }
            }
            else
            {
                mediaStreams = new List <MediaStream>();
                chapters     = new List <ChapterInfo>();
            }

            await AddExternalSubtitles(video, mediaStreams, options, cancellationToken).ConfigureAwait(false);

            var libraryOptions = _libraryManager.GetLibraryOptions(video);

            if (mediaInfo != null)
            {
                FetchEmbeddedInfo(video, mediaInfo, options, libraryOptions);
                FetchPeople(video, mediaInfo, options);
                video.Timestamp     = mediaInfo.Timestamp;
                video.Video3DFormat = video.Video3DFormat ?? mediaInfo.Video3DFormat;
            }

            var videoStream = mediaStreams.FirstOrDefault(i => i.Type == MediaStreamType.Video);

            video.Height = videoStream == null ? 0 : videoStream.Height ?? 0;
            video.Width  = videoStream == null ? 0 : videoStream.Width ?? 0;

            video.DefaultVideoStreamIndex = videoStream == null ? (int?)null : videoStream.Index;

            video.HasSubtitles = mediaStreams.Any(i => i.Type == MediaStreamType.Subtitle);

            _itemRepo.SaveMediaStreams(video.Id, mediaStreams, cancellationToken);

            if (options.MetadataRefreshMode == MetadataRefreshMode.FullRefresh ||
                options.MetadataRefreshMode == MetadataRefreshMode.Default)
            {
                if (chapters.Count == 0 && mediaStreams.Any(i => i.Type == MediaStreamType.Video))
                {
                    AddDummyChapters(video, chapters);
                }

                NormalizeChapterNames(chapters);

                var extractDuringScan = false;
                if (libraryOptions != null)
                {
                    extractDuringScan = libraryOptions.ExtractChapterImagesDuringLibraryScan;
                }

                await _encodingManager.RefreshChapterImages(video, options.DirectoryService, chapters, extractDuringScan, false, cancellationToken).ConfigureAwait(false);

                _chapterManager.SaveChapters(video.Id.ToString(), chapters);
            }
        }
Пример #42
0
 private void Tick(object sender, TickEventArgs e)
 {
     Display();
     Video.GLSwapBuffers();
 }
Пример #43
0
        /// <summary>
        /// OnePassArgs
        /// </summary>
        // 1-Pass, CRF, & Auto
        public static String OnePassArgs(MainWindow mainwindow)
        {
            // -------------------------
            //  Single Pass
            // -------------------------
            if ((string)mainwindow.cboPass.SelectedItem == "1 Pass" 
                || (string)mainwindow.cboPass.SelectedItem == "CRF" 
                || (string)mainwindow.cboPass.SelectedItem == "auto"
                || (string)mainwindow.cboFormat.SelectedItem == "ogv" //ogv (special rule)
                )
            {
                // -------------------------
                //  Arguments List
                // -------------------------
                List<string> FFmpegArgsSinglePassList = new List<string>()
                {
                    "\r\n\r\n" + 
                    "-i "+ "\"" + MainWindow.InputPath(mainwindow) + "\"",

                    "\r\n\r\n" + 
                    Video.Subtitles(mainwindow),

                    "\r\n\r\n" + 
                    Video.VideoCodec(mainwindow),
                    "\r\n" + 
                    Video.Speed(mainwindow, "pass single"),
                    Video.VideoQuality(mainwindow),
                    "\r\n" + 
                    Video.FPS(mainwindow),
                    "\r\n" + 
                    VideoFilters.VideoFilter(mainwindow),
                    "\r\n" + 
                    Video.ScalingAlgorithm(mainwindow),
                    "\r\n" + 
                    Video.Images(mainwindow),
                    "\r\n" + 
                    Video.Optimize(mainwindow),
                    "\r\n" + 
                    Streams.VideoStreamMaps(mainwindow),

                    "\r\n\r\n" + 
                    Video.SubtitleCodec(mainwindow),
                    "\r\n" + 
                    Streams.SubtitleMaps(mainwindow),

                    "\r\n\r\n" + 
                    Audio.AudioCodec(mainwindow),
                    "\r\n" + 
                    Audio.AudioQuality(mainwindow),
                    Audio.SampleRate(mainwindow),
                    Audio.BitDepth(mainwindow),
                    Audio.Channel(mainwindow),
                    "\r\n" +
                    AudioFilters.AudioFilter(mainwindow),
                    "\r\n" + 
                    Streams.AudioStreamMaps(mainwindow),

                    "\r\n\r\n" + 
                    Format.Cut(mainwindow),

                    "\r\n\r\n" + 
                    Streams.FormatMaps(mainwindow),

                    "\r\n\r\n" + 
                    Format.ForceFormat(mainwindow),

                    "\r\n\r\n" + 
                    MainWindow.ThreadDetect(mainwindow),

                    "\r\n\r\n" + 
                    "\"" + MainWindow.OutputPath(mainwindow) + "\""
                };

                // Join List with Spaces
                // Remove: Empty, Null, Standalone LineBreak
                Video.passSingle = string.Join(" ", FFmpegArgsSinglePassList
                                                    .Where(s => !string.IsNullOrEmpty(s))
                                                    .Where(s => !s.Equals(Environment.NewLine))
                                                    .Where(s => !s.Equals("\r\n\r\n"))
                                                    .Where(s => !s.Equals("\r\n"))
                                              );
            }


            // Return Value
            return Video.passSingle;
        }
Пример #44
0
        private void FetchEmbeddedInfo(Video video, Model.MediaInfo.MediaInfo data, MetadataRefreshOptions refreshOptions, LibraryOptions libraryOptions)
        {
            var isFullRefresh = refreshOptions.MetadataRefreshMode == MetadataRefreshMode.FullRefresh;

            if (!video.IsLocked && !video.LockedFields.Contains(MetadataFields.OfficialRating))
            {
                if (!string.IsNullOrWhiteSpace(data.OfficialRating) || isFullRefresh)
                {
                    video.OfficialRating = data.OfficialRating;
                }
            }

            if (!video.IsLocked && !video.LockedFields.Contains(MetadataFields.Genres))
            {
                if (video.Genres.Length == 0 || isFullRefresh)
                {
                    video.Genres = Array.Empty <string>();

                    foreach (var genre in data.Genres)
                    {
                        video.AddGenre(genre);
                    }
                }
            }

            if (!video.IsLocked && !video.LockedFields.Contains(MetadataFields.Studios))
            {
                if (video.Studios.Length == 0 || isFullRefresh)
                {
                    video.SetStudios(data.Studios);
                }
            }

            if (data.ProductionYear.HasValue)
            {
                if (!video.ProductionYear.HasValue || isFullRefresh)
                {
                    video.ProductionYear = data.ProductionYear;
                }
            }
            if (data.PremiereDate.HasValue)
            {
                if (!video.PremiereDate.HasValue || isFullRefresh)
                {
                    video.PremiereDate = data.PremiereDate;
                }
            }
            if (data.IndexNumber.HasValue)
            {
                if (!video.IndexNumber.HasValue || isFullRefresh)
                {
                    video.IndexNumber = data.IndexNumber;
                }
            }
            if (data.ParentIndexNumber.HasValue)
            {
                if (!video.ParentIndexNumber.HasValue || isFullRefresh)
                {
                    video.ParentIndexNumber = data.ParentIndexNumber;
                }
            }

            if (!video.IsLocked && !video.LockedFields.Contains(MetadataFields.Name))
            {
                if (!string.IsNullOrWhiteSpace(data.Name) && libraryOptions.EnableEmbeddedTitles)
                {
                    // Don't use the embedded name for extras because it will often be the same name as the movie
                    if (!video.ExtraType.HasValue)
                    {
                        video.Name = data.Name;
                    }
                }
            }

            // If we don't have a ProductionYear try and get it from PremiereDate
            if (video.PremiereDate.HasValue && !video.ProductionYear.HasValue)
            {
                video.ProductionYear = video.PremiereDate.Value.ToLocalTime().Year;
            }

            if (!video.IsLocked && !video.LockedFields.Contains(MetadataFields.Overview))
            {
                if (string.IsNullOrWhiteSpace(video.Overview) || isFullRefresh)
                {
                    video.Overview = data.Overview;
                }
            }
        }
Пример #45
0
        /// <summary>
        /// Batch 2Pass Args
        /// </summary>      
        public static String TwoPassArgs(MainWindow mainwindow)
        {
            // -------------------------
            //  2-Pass Auto Quality
            // -------------------------
            // Enabled 
            //
            if ((string)mainwindow.cboPass.SelectedItem == "2 Pass" 
                && (string)mainwindow.cboMediaType.SelectedItem == "Video" // video only
                && (string)mainwindow.cboVideoCodec.SelectedItem != "Copy" // exclude copy
                && (string)mainwindow.cboFormat.SelectedItem != "ogv" // exclude ogv (special rule)
                )
            {
                // -------------------------
                // Pass 1
                // -------------------------
                List<string> FFmpegArgsPass1List = new List<string>()
                {
                    "\r\n\r\n" + 
                    "-i "+ "\"" + 
                    MainWindow.InputPath(mainwindow) + "\"",

                    //"\r\n\r\n" + 
                    //Video.Subtitles(mainwindow),

                    "\r\n\r\n" + 
                    Video.VideoCodec(mainwindow),
                    "\r\n" +
                    Video.Speed(mainwindow, "pass 1"),
                    Video.VideoQuality(mainwindow),
                    "\r\n" + 
                    Video.FPS(mainwindow),
                    "\r\n" + 
                    VideoFilters.VideoFilter(mainwindow),
                    "\r\n" + 
                    Video.ScalingAlgorithm(mainwindow),
                    "\r\n" + 
                    Video.Images(mainwindow),
                    "\r\n" + 
                    Video.Optimize(mainwindow),
                    "\r\n" + 
                    Video.Pass1Modifier(mainwindow), // -pass 1, -x265-params pass=2

                    "\r\n\r\n" + 
                    "-sn -an", // Disable Audio & Subtitles for Pass 1 to speed up encoding

                    "\r\n\r\n" + 
                    Format.Cut(mainwindow),
                    "\r\n\r\n" + 
                    Format.ForceFormat(mainwindow),
                    "\r\n\r\n" + 
                    MainWindow.ThreadDetect(mainwindow),

                    //"\r\n\r\n" + "\"" + MainWindow.OutputPath(mainwindow) + "\""
                    "\r\n\r\n" + 
                    "NUL"
                };

                // Join List with Spaces
                // Remove: Empty, Null, Standalone LineBreak
                Video.pass1Args = string.Join(" ", FFmpegArgsPass1List
                                                   .Where(s => !string.IsNullOrEmpty(s))
                                                   .Where(s => !s.Equals(Environment.NewLine))
                                                   .Where(s => !s.Equals("\r\n\r\n"))
                                                   .Where(s => !s.Equals("\r\n"))
                                             );


                // -------------------------
                // Pass 2
                // -------------------------
                List<string> FFmpegArgsPass2List = new List<string>()
                {
                    // Video Methods have already defined Global Strings in Pass 1
                    // Use Strings instead of Methods
                    //
                    "\r\n\r\n" + 
                    "&&",

                    "\r\n\r\n" + 
                    MainWindow.FFmpegPath(),
                    "-y",

                    "\r\n\r\n" + 
                    Video.HWAcceleration(mainwindow),

                    "\r\n\r\n" + 
                    "-i " + "\"" + MainWindow.InputPath(mainwindow) + "\"",

                    "\r\n\r\n" +
                    Video.Subtitles(mainwindow),

                    "\r\n\r\n" + 
                    Video.vCodec,
                    "\r\n" + 
                    Video.Speed(mainwindow, "pass 2"),
                    Video.vQuality,
                    "\r\n" + 
                    Video.fps,
                    "\r\n" + 
                    VideoFilters.vFilter,
                    "\r\n" + 
                    Video.ScalingAlgorithm(mainwindow),
                    "\r\n" + 
                    Video.image,
                    "\r\n" + 
                    Video.optimize,
                    "\r\n" + 
                    Streams.VideoStreamMaps(mainwindow),
                    "\r\n" + 
                    Video.Pass2Modifier(mainwindow), // -pass 2, -x265-params pass=2

                    "\r\n\r\n" + 
                    Video.SubtitleCodec(mainwindow),
                    "\r\n" + 
                    Streams.SubtitleMaps(mainwindow),

                    "\r\n\r\n" + 
                    Audio.AudioCodec(mainwindow),
                    "\r\n" + 
                    Audio.AudioQuality(mainwindow),
                    Audio.SampleRate(mainwindow),
                    Audio.BitDepth(mainwindow),
                    Audio.Channel(mainwindow),
                    "\r\n" +
                    AudioFilters.AudioFilter(mainwindow),
                    "\r\n" + 
                    Streams.AudioStreamMaps(mainwindow),

                    "\r\n\r\n" + 
                    Format.trim,

                    "\r\n\r\n" + 
                    Streams.FormatMaps(mainwindow),

                    "\r\n\r\n" + 
                    Format.ForceFormat(mainwindow),

                    "\r\n\r\n" + 
                    Configure.threads,

                    "\r\n\r\n" + 
                    "\"" + MainWindow.OutputPath(mainwindow) + "\""
                };

                // Join List with Spaces
                // Remove: Empty, Null, Standalone LineBreak
                Video.pass2Args = string.Join(" ", FFmpegArgsPass2List
                                                   .Where(s => !string.IsNullOrEmpty(s))
                                                   .Where(s => !s.Equals(Environment.NewLine))
                                                   .Where(s => !s.Equals("\r\n\r\n"))
                                                   .Where(s => !s.Equals("\r\n"))
                                             );

                // Combine Pass 1 & Pass 2 Args
                //
                Video.v2PassArgs = Video.pass1Args + " " + Video.pass2Args;
            }


            // Return Value
            return Video.v2PassArgs;
        }
Пример #46
0
        public void ScanVideo(Video video)
        {
            int scanCount   = (int)Math.Ceiling(video.Duration.TotalSeconds * video.ScanRate);
            int finishCount = 0;

            ProcessingWindow.Update_totalVideoFrames(scanCount);

            double timeIndexMultiplier = 1000d / video.ScanRate;

            // Todo: Make method in Video for this instead.
            video.Feeds.ForEach(f => f.OCRBag           = new ConcurrentBag <Bag>());
            video.WatchImages.ForEach(wi => wi.DeltaBag = new ConcurrentBag <Bag>());

            DirectoryInfo directory = new DirectoryInfo(TempDirectory);

            FileInfo[] files = directory.GetFiles(FRAME_FILE_SELECTOR);
            Parallel.ForEach(files, (file) =>
            {
                file.Delete();
            });

            while (!Aborted && (!Process.HasExited || files.Count() > 0))
            {
                files = directory.GetFiles(FRAME_FILE_SELECTOR);
                if (files.Count() > 0 && !Paused && !Aborted)
                {
                    Parallel.ForEach(files, (file) =>
                    {
                        int thumbID = int.Parse(file.Name.Substring(0, 8));
                        if (file.Exists && !Paused && !Aborted)
                        {
                            try
                            {
                                using (var fileImageBase = new MagickImage(file.FullName))
                                {
                                    if (fileImageBase.Width <= 1 && fileImageBase.Height <= 1)
                                    { // Sometimes happens. Dunno how. Probably because it's parallel.
                                        goto Skip;
                                    }
                                    fileImageBase.RePage();
                                    foreach (var f in video.Feeds)
                                    {
                                        if (!f.UseOCR)
                                        {
                                            foreach (var s in f.Screens)
                                            {
                                                foreach (var wz in s.WatchZones)
                                                {
                                                    var mg = wz.ThumbnailGeometry.ToMagick();
                                                    // Doesn't crop perfectly. Investigate later.
                                                    using (var fileImageCropped = (MagickImage)fileImageBase.Clone())
                                                    {
                                                        fileImageCropped.Crop(mg, Gravity.Northwest);
                                                        foreach (var w in wz.Watches)
                                                        {
                                                            using (var fileImageComposed = (MagickImage)fileImageCropped.Clone())
                                                            {
                                                                fileImageComposed.ColorSpace = w.ColorSpace;
                                                                foreach (var wi in w.WatchImages)
                                                                {
                                                                    var deltaImage = wi.MagickImage;
                                                                    using (var fileImageCompare = (MagickImage)fileImageComposed.Clone())
                                                                    {
                                                                        if (deltaImage.HasAlpha)
                                                                        {
                                                                            fileImageCompare.Composite(deltaImage, CompositeOperator.CopyAlpha);
                                                                        }

                                                                        var delta = (float)deltaImage.Compare(fileImageCompare,
                                                                                                              ErrorMetric.NormalizedCrossCorrelation);

                                                                        int id = (int)Math.Round(thumbID * timeIndexMultiplier);
                                                                        wi.DeltaBag.Add(new Bag(id, delta));
                                                                    }
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                        else
                                        {
                                            using (var b = fileImageBase.ToBitmap())
                                            {
                                                Utilities.ReadImage(b, f.ThumbnailGeometry, out string str, out float confidence);
                                                f.OCRBag.Add(new Bag(thumbID, confidence, str));
                                            }
                                        }
                                    }
Пример #47
0
        public static void Init()
        {
            User1 = new User()
            {
                Id = Guid.NewGuid(), Nickname = "TrangUyen", Mail = "*****@*****.**"
            };
            User2 = new User()
            {
                Id = Guid.NewGuid(), Nickname = "Phobovien", Mail = "*****@*****.**"
            };
            User3 = new User()
            {
                Id = Guid.NewGuid(), Nickname = "AIGiveAway", Mail = "*****@*****.**"
            };
            User4 = new User()
            {
                Id = Guid.NewGuid(), Nickname = "Kraigeki", Mail = "*****@*****.**"
            };

            Video1 = new Video()
            {
                Id = Guid.NewGuid(), Title = "Luon xao sa ot", Quality = Video.VideoQuality.HD, UserId = User1.Id
            };
            Video2 = new Video()
            {
                Id = Guid.NewGuid(), Title = "Ca dieu hong nau mang chua", Quality = Video.VideoQuality.SD, UserId = User1.Id
            };
            Video3 = new Video()
            {
                Id = Guid.NewGuid(), Title = "Com tam suon trung", Quality = Video.VideoQuality.HD, UserId = User1.Id
            };
            Video4 = new Video()
            {
                Id = Guid.NewGuid(), Title = "Ca tre chien mam gung", Quality = Video.VideoQuality.HD, UserId = User2.Id
            };
            Video5 = new Video()
            {
                Id = Guid.NewGuid(), Title = "Dau hu nhoi thit chien sot ca", Quality = Video.VideoQuality.HD, UserId = User2.Id
            };
            Video6 = new Video()
            {
                Id = Guid.NewGuid(), Title = "Hu tien suon non", Quality = Video.VideoQuality.HD, UserId = User2.Id
            };
            Video7 = new Video()
            {
                Id = Guid.NewGuid(), Title = "Hu tieu tom thit", Quality = Video.VideoQuality.HD, UserId = User3.Id
            };
            Video8 = new Video()
            {
                Id = Guid.NewGuid(), Title = "Mi tom thit", Quality = Video.VideoQuality.HD, UserId = User3.Id
            };
            Video9 = new Video()
            {
                Id = Guid.NewGuid(), Title = "Mi hai san", Quality = Video.VideoQuality.HD, UserId = User4.Id
            };
            Video10 = new Video()
            {
                Id = Guid.NewGuid(), Title = "Com chien duong chau", Quality = Video.VideoQuality.HD, UserId = User4.Id
            };

            Comment1 = new Comment()
            {
                Id = Guid.NewGuid(), UserId = User1.Id, VideoId = Video1.Id, Time = DateTime.Now.AddDays(-10)
            };
            Comment2 = new Comment()
            {
                Id = Guid.NewGuid(), UserId = User2.Id, VideoId = Video2.Id, Time = DateTime.Today.AddDays(-12)
            };
            Comment3 = new Comment()
            {
                Id = Guid.NewGuid(), UserId = User3.Id, VideoId = Video3.Id, Time = DateTime.Today.AddDays(-1)
            };
            Comment4 = new Comment()
            {
                Id = Guid.NewGuid(), UserId = User4.Id, VideoId = Video4.Id, Time = DateTime.Today.AddDays(-3)
            };
            Comment5 = new Comment()
            {
                Id = Guid.NewGuid(), UserId = User4.Id, VideoId = Video5.Id, Time = DateTime.Today.AddDays(-3)
            };
            Comment6 = new Comment()
            {
                Id = Guid.NewGuid(), UserId = User3.Id, VideoId = Video3.Id, Time = DateTime.Today.AddDays(-7)
            };
            Comment7 = new Comment()
            {
                Id = Guid.NewGuid(), UserId = User2.Id, VideoId = Video2.Id, Time = DateTime.Today.AddDays(-2)
            };
            Comment8 = new Comment()
            {
                Id = Guid.NewGuid(), UserId = User1.Id, VideoId = Video1.Id, Time = DateTime.Today.AddDays(-2)
            };
            Comment9 = new Comment()
            {
                Id = Guid.NewGuid(), UserId = User1.Id, VideoId = Video1.Id, Time = DateTime.Today.AddDays(-6)
            };
            Comment10 = new Comment()
            {
                Id = Guid.NewGuid(), UserId = User3.Id, VideoId = Video2.Id, Time = DateTime.Today.AddDays(-12)
            };
            Comment11 = new Comment()
            {
                Id = Guid.NewGuid(), UserId = User3.Id, VideoId = Video4.Id, Time = DateTime.Today.AddDays(-8)
            };
            Comment12 = new Comment()
            {
                Id = Guid.NewGuid(), UserId = User2.Id, VideoId = Video5.Id, Time = DateTime.Today.AddDays(-7)
            };
            Comment13 = new Comment()
            {
                Id = Guid.NewGuid(), UserId = User2.Id, VideoId = Video8.Id, Time = DateTime.Today.AddDays(-5)
            };
            Comment14 = new Comment()
            {
                Id = Guid.NewGuid(), UserId = User4.Id, VideoId = Video9.Id, Time = DateTime.Today.AddDays(-3)
            };
            Comment15 = new Comment()
            {
                Id = Guid.NewGuid(), UserId = User4.Id, VideoId = Video7.Id, Time = DateTime.Today.AddDays(-2)
            };
            Comment16 = new Comment()
            {
                Id = Guid.NewGuid(), UserId = User1.Id, VideoId = Video4.Id, Time = DateTime.Today.AddDays(-1)
            };
            Comment17 = new Comment()
            {
                Id = Guid.NewGuid(), UserId = User3.Id, VideoId = Video2.Id, Time = DateTime.Today.AddDays(-8)
            };
            Comment18 = new Comment()
            {
                Id = Guid.NewGuid(), UserId = User2.Id, VideoId = Video3.Id, Time = DateTime.Today.AddDays(-12)
            };
            Comment19 = new Comment()
            {
                Id = Guid.NewGuid(), UserId = User3.Id, VideoId = Video4.Id, Time = DateTime.Today.AddDays(-3)
            };
            Comment20 = new Comment()
            {
                Id = Guid.NewGuid(), UserId = User1.Id, VideoId = Video6.Id, Time = DateTime.Today.AddDays(-2)
            };
        }
Пример #48
0
        // --------------------------------------------------------------------------------------------------------


        /// <summary>
        /// FFmpeg Batch - Generate Args
        /// </summary>
        public static void FFmpegBatchGenerateArgs(MainWindow mainwindow)
        {
            if (mainwindow.tglBatch.IsChecked == true)
            {
                // Replace ( with ^( to avoid Windows 7 CMD Error //important!
                // This is only used in select areas
                //MainWindow.batchInputAuto = mainwindow.textBoxBrowse.Text.Replace(@"(", "^(");
                //MainWindow.batchInputAuto = MainWindow.batchInputAuto.Replace(@")", "^)");

                // Log Console Message /////////
                Log.WriteAction = () =>
                {
                    Log.logParagraph.Inlines.Add(new LineBreak());
                    Log.logParagraph.Inlines.Add(new LineBreak());
                    Log.logParagraph.Inlines.Add(new Bold(new Run("Batch: ")) { Foreground = Log.ConsoleDefault });
                    Log.logParagraph.Inlines.Add(new Run(Convert.ToString(mainwindow.tglBatch.IsChecked)) { Foreground = Log.ConsoleDefault });
                    Log.logParagraph.Inlines.Add(new LineBreak());
                    Log.logParagraph.Inlines.Add(new LineBreak());
                    Log.logParagraph.Inlines.Add(new Bold(new Run("Generating Batch Script...")) { Foreground = Log.ConsoleTitle });
                    Log.logParagraph.Inlines.Add(new LineBreak());
                    Log.logParagraph.Inlines.Add(new LineBreak());
                    Log.logParagraph.Inlines.Add(new Bold(new Run("Running Batch Convert...")) { Foreground = Log.ConsoleAction });
                };
                Log.LogActions.Add(Log.WriteAction);


                // -------------------------
                // Batch Arguments Full
                // -------------------------
                // Make List
                //
                List<string> FFmpegBatchArgsList = new List<string>()
                {
                    "cd /d",
                    "\"" + MainWindow.BatchInputDirectory(mainwindow) + "\"",

                    "\r\n\r\n" + "&& for %f in",
                    "(*" + MainWindow.batchExt + ")",
                    "do (echo)",

                    "\r\n\r\n" + Video.BatchVideoQualityAuto(mainwindow),

                    "\r\n\r\n" + Audio.BatchAudioQualityAuto(mainwindow),
                    "\r\n\r\n" + Audio.BatchAudioBitrateLimiter(mainwindow),

                    "\r\n\r\n" + "&&",
                    "\r\n\r\n" + MainWindow.FFmpegPath(),
                    "\r\n\r\n" + Video.HWAcceleration(mainwindow),
                    "-y",
                    //%~f added in InputPath()

                    FFmpeg.OnePassArgs(mainwindow), //disabled if 2-Pass       
                    FFmpeg.TwoPassArgs(mainwindow) //disabled if 1-Pass
                };

                // Join List with Spaces
                // Remove: Empty, Null, Standalone LineBreak
                ffmpegArgsSort = string.Join(" ", FFmpegBatchArgsList
                                                  .Where(s => !string.IsNullOrEmpty(s))
                                                  .Where(s => !s.Equals(Environment.NewLine))
                                                  .Where(s => !s.Equals("\r\n\r\n"))
                                                  .Where(s => !s.Equals("\r\n"))
                                            );

                // Inline 
                ffmpegArgs = MainWindow.RemoveLineBreaks(
                                            string.Join(" ", FFmpegBatchArgsList
                                                            .Where(s => !string.IsNullOrEmpty(s))
                                                            .Where(s => !s.Equals(Environment.NewLine))
                                                            .Where(s => !s.Equals("\r\n\r\n"))
                                                            .Where(s => !s.Equals("\r\n"))
                                                        )
                                        );
                                   //.Replace("\r\n", " ") // Replace Linebreaks with Spaces to avoid arguments touching
                                   //.Replace(Environment.NewLine, "");
            }
        }
Пример #49
0
        private void videoBox_Tapped(object sender, Windows.UI.Xaml.Input.TappedRoutedEventArgs e)
        {
            Video r = (Video)((FrameworkElement)e.OriginalSource).DataContext;

            this.Frame.Navigate(typeof(VideoPage), r);
        }
        public async Task <bool> Boost(
            ChannelEntity channel,
            Youtube.Domain.Entities.ChannelEntity youtubeChannel,
            Video video)
        {
            var query = this.names.GetRandomName();

            var usersCount = 10;
            var users      = new List <InstaUser>();

            while (usersCount <= 100)
            {
                var result = await this.instagramProvider.SearchPeopleAsync(query, usersCount);

                if (!result.Succeeded)
                {
                    this.logger.LogError($"{result.Info?.Message}");
                    return(false);
                }

                users = result.Value.Users
                        .Where(u =>
                               !u.IsPrivate &&
                               u.FollowersCount < 1000)
                        .ToList();

                if (users.Any())
                {
                    break;
                }

                usersCount += 10;
            }

            if (!users.Any())
            {
                return(false);
            }

            foreach (var user in users.Shuffle())
            {
                if (user.UserName == channel.OriginalChannelId ||
                    user.UserName == channel.ChannelId ||
                    user.UserName == youtubeChannel.Name)
                {
                    continue;
                }

                var mediaList = await this.instagramProvider.GetLastMedia(user.UserName);

                if (mediaList == null || !mediaList.Any())
                {
                    continue;
                }

                foreach (var media in mediaList)
                {
                    if (media?.Caption == null ||
                        string.IsNullOrEmpty(media.Caption.MediaId) ||
                        media.IsCommentsDisabled)
                    {
                        continue;
                    }

                    if (!int.TryParse(media.CommentsCount, out var commentsCount))
                    {
                        continue;
                    }

                    if (commentsCount > 3)
                    {
                        continue;
                    }

                    var res = await this.instagramProvider.CommentMediaAsync(
                        media.Caption.MediaId,
                        video.GetInstagramBoostText());

                    if (!res.Succeeded)
                    {
                        this.logger.LogError($"{res.Info?.Message}");
                        continue;
                    }

                    this.logger.LogTrace($"[{media.GetInstagramUrl()}] [{user.UserName}] [{user.FullName}]");
                    return(true);
                }
            }

            return(false);
        }
Пример #51
0
        public override void control(bot ircbot, ref IRCConfig conf, int module_id, string[] line, string command, int nick_access, string nick, string channel, bool bot_command, string type)
        {
            string module_name = ircbot.conf.module_config[module_id][0];

            if (type.Equals("channel") && bot_command == false)
            {
                string text = "";
                if (line.GetUpperBound(0) > 3)
                {
                    text = line[3] + " " + line[4];
                }
                else
                {
                    text = line[3];
                }
                try
                {
                    Regex regex = new Regex("(((https?|ftp|file)://|www\\.)([A-Z0-9.-:]{1,})\\.[0-9A-Z?;~&#=\\-_\\./]{2,})", RegexOptions.Compiled | RegexOptions.IgnoreCase);

                    //get the first match
                    MatchCollection matches = regex.Matches(text);

                    foreach (Match match in matches)
                    {
                        string testMatch = match.Value.ToString();
                        if (!testMatch.Contains("://"))
                        {
                            testMatch = "http://" + testMatch;
                        }
                        Uri url     = new Uri(testMatch);
                        var request = WebRequest.Create(url);
                        request.Timeout = 5000;
                        using (var response = request.GetResponse())
                        {
                            string[] content_type = response.ContentType.Split('/');
                            switch (content_type[0])
                            {
                            case "text":
                                WebClient       x             = new WebClient();
                                string          source        = x.DownloadString(url.OriginalString);
                                string          title_regex   = @"(?<=<title.*>)(.*?)(?=</title>)";
                                Regex           title_ex      = new Regex(title_regex, RegexOptions.IgnoreCase);
                                MatchCollection title_matches = title_ex.Matches(source);
                                string          title         = title_matches[0].Value.Trim();
                                if (url.OriginalString.Contains("youtube.com/watch?") && ircbot.conf.module_config[module_id][4].Equals("True"))
                                {
                                    string YouTubeVideoID             = ExtractYouTubeVideoIDFromUrl(url.OriginalString);
                                    Uri    videoEntryUrl              = new Uri(string.Format("https://gdata.youtube.com/feeds/api/videos/{0}", YouTubeVideoID));
                                    YouTubeRequestSettings settings   = new YouTubeRequestSettings("YouTube Video Duration Sample App", developerKey);
                                    YouTubeRequest         yt_request = new YouTubeRequest(settings);
                                    Video    video          = yt_request.Retrieve <Video>(videoEntryUrl);
                                    int      duration       = int.Parse(video.Contents.First().Duration);
                                    string   yt_title       = video.Title;
                                    int      views          = video.ViewCount;
                                    double   rateavg        = video.RatingAverage;
                                    string   uploader       = video.Uploader;
                                    DateTime date           = video.Updated;
                                    string   total_duration = "";
                                    TimeSpan t = TimeSpan.FromSeconds(duration);
                                    if (t.Hours > 0)
                                    {
                                        total_duration += t.Hours.ToString() + "h ";
                                    }
                                    if (t.Minutes > 0)
                                    {
                                        total_duration += t.Minutes.ToString() + "m ";
                                    }
                                    if (t.Seconds > 0)
                                    {
                                        total_duration += t.Seconds.ToString() + "s ";
                                    }
                                    ircbot.sendData("PRIVMSG", channel + " :[Youtube] Title: " + HttpUtility.HtmlDecode(yt_title) + " | Length: " + total_duration.TrimEnd(' ') + " | Views: " + string.Format("{0:#,###0}", views) + " | Rated: " + Math.Round(rateavg, 2).ToString() + "/5.0 | Uploaded By: " + uploader + " on " + date.ToString("yyyy-MM-dd"));
                                }
                                else if (url.OriginalString.Contains("youtu.be") && ircbot.conf.module_config[module_id][4].Equals("True"))
                                {
                                    string[] url_parsed               = url.OriginalString.Split('/');
                                    string   YouTubeVideoID           = url_parsed[url_parsed.GetUpperBound(0)];
                                    Uri      videoEntryUrl            = new Uri(string.Format("https://gdata.youtube.com/feeds/api/videos/{0}", YouTubeVideoID));
                                    YouTubeRequestSettings settings   = new YouTubeRequestSettings("YouTube Video Duration Sample App", developerKey);
                                    YouTubeRequest         yt_request = new YouTubeRequest(settings);
                                    Video    video          = yt_request.Retrieve <Video>(videoEntryUrl);
                                    int      duration       = int.Parse(video.Contents.First().Duration);
                                    string   yt_title       = video.Title;
                                    int      views          = video.ViewCount;
                                    double   rateavg        = video.RatingAverage;
                                    string   uploader       = video.Uploader;
                                    DateTime date           = video.Updated;
                                    string   total_duration = "";
                                    TimeSpan t = TimeSpan.FromSeconds(duration);
                                    if (t.Hours > 0)
                                    {
                                        total_duration += t.Hours.ToString() + "h ";
                                    }
                                    if (t.Minutes > 0)
                                    {
                                        total_duration += t.Minutes.ToString() + "m ";
                                    }
                                    if (t.Seconds > 0)
                                    {
                                        total_duration += t.Seconds.ToString() + "s ";
                                    }
                                    ircbot.sendData("PRIVMSG", channel + " :[Youtube] Title: " + HttpUtility.HtmlDecode(yt_title) + " | Length: " + total_duration.TrimEnd(' ') + " | Views: " + string.Format("{0:#,###0}", views) + " | Rated: " + Math.Round(rateavg, 2).ToString() + "/5.0 | Uploaded By: " + uploader + " on " + date.ToString("yyyy-MM-dd"));
                                }
                                else if ((url.OriginalString.Contains("boards.4chan.org") && url.Segments.GetUpperBound(0) > 2) && ircbot.conf.module_config[module_id][5].Equals("True"))
                                {
                                    string    board     = url.Segments[1].TrimEnd('/');
                                    string    uri       = "https://api.4chan.org/" + board + "/res/" + url.Segments[3] + ".json";
                                    WebClient chan      = new WebClient();
                                    var       json_data = string.Empty;
                                    json_data = chan.DownloadString(uri);
                                    XmlDocument xmlDoc    = JsonConvert.DeserializeXmlNode(json_data, board + "-" + url.Segments[3]);
                                    XmlNodeList post_list = xmlDoc.SelectNodes(board + "-" + url.Segments[3] + "/posts");
                                    string      thread    = "";
                                    if (!url.Fragment.Equals(string.Empty))
                                    {
                                        thread = url.Fragment.TrimStart('#').TrimStart('p');
                                    }
                                    else
                                    {
                                        thread = url.Segments[3];
                                    }
                                    foreach (XmlNode post in post_list)
                                    {
                                        string post_num = post["no"].InnerText;
                                        if (post_num.Equals(thread))
                                        {
                                            string   date        = post["now"].InnerText;
                                            string   parsed_date = date.Split('(')[0] + " " + date.Split(')')[1];
                                            DateTime post_date   = DateTime.Parse(parsed_date);
                                            TimeSpan difference  = DateTime.UtcNow - post_date;
                                            difference = difference.Subtract(TimeSpan.FromHours(4));
                                            string   total_duration = "";
                                            TimeSpan t = TimeSpan.FromSeconds(difference.TotalSeconds);
                                            if (t.Hours > 0)
                                            {
                                                total_duration += t.Hours.ToString() + "h ";
                                            }
                                            if (t.Minutes > 0)
                                            {
                                                total_duration += t.Minutes.ToString() + "m ";
                                            }
                                            if (t.Seconds > 0)
                                            {
                                                total_duration += t.Seconds.ToString() + "s ";
                                            }
                                            string post_name = "", post_comment = "", tripcode = "", ID = "", email = "", subject = "", replies = "", images = "", image_ext = "", image_name = "", image_width = "", image_height = "";
                                            try
                                            {
                                                post_name = post["name"].InnerText;
                                            }
                                            catch { }
                                            try
                                            {
                                                post_comment = post["com"].InnerText;
                                            }
                                            catch { }
                                            try
                                            {
                                                tripcode = post["trip"].InnerText;
                                            }
                                            catch { }
                                            try
                                            {
                                                ID = post["id"].InnerText;
                                            }
                                            catch { }
                                            try
                                            {
                                                email = post["email"].InnerText;
                                            }
                                            catch { }
                                            try
                                            {
                                                subject = post["sub"].InnerText;
                                            }
                                            catch { }
                                            try
                                            {
                                                replies = post["replies"].InnerText;
                                            }
                                            catch { }
                                            try
                                            {
                                                images = post["images"].InnerText;
                                            }
                                            catch { }
                                            try
                                            {
                                                image_ext = post["ext"].InnerText;
                                            }
                                            catch { }
                                            try
                                            {
                                                image_name = post["tim"].InnerText;
                                            }
                                            catch { }
                                            try
                                            {
                                                image_width = post["w"].InnerText;
                                            }
                                            catch { }
                                            try
                                            {
                                                image_height = post["h"].InnerText;
                                            }
                                            catch { }

                                            if (!ID.Trim().Equals(string.Empty))
                                            {
                                                ID = "[" + ID + "]";
                                            }

                                            string post_message = "";
                                            if (!subject.Equals(string.Empty))
                                            {
                                                post_message += "Subject: " + subject + " | ";
                                            }
                                            string[] words = post_comment.Split(' ');
                                            if (words.GetUpperBound(0) > 10)
                                            {
                                                post_message += " Comment: ";
                                                for (int i = 0; i < 15; i++)
                                                {
                                                    post_message += words[i] + " ";
                                                }
                                                post_message += "...";
                                            }
                                            else if (!post_comment.Equals(string.Empty))
                                            {
                                                post_message += " Comment: " + post_comment;
                                            }

                                            string[] tmp_post = Regex.Split(post_message, "<br>");
                                            post_message = "";
                                            foreach (string tmp in tmp_post)
                                            {
                                                if (!tmp.Trim().Equals(string.Empty))
                                                {
                                                    post_message += HttpUtility.HtmlDecode(tmp) + " | ";
                                                }
                                            }

                                            string image_url = "";
                                            if (!image_name.Equals(string.Empty))
                                            {
                                                image_url = "http://images.4chan.org/" + board + "/src/" + image_name + image_ext;
                                            }

                                            if (!image_url.Equals(string.Empty))
                                            {
                                                image_url = " | Posted Image: " + image_url + " (" + image_width + "x" + image_height + ")";
                                            }

                                            if (!replies.Equals(string.Empty))
                                            {
                                                replies = " | Replies: " + replies;
                                            }

                                            if (!images.Equals(string.Empty))
                                            {
                                                images = " | Images: " + images;
                                            }

                                            ircbot.sendData("PRIVMSG", channel + " :[4chan] /" + board + "/ | Posted by: " + post_name + tripcode + ID + " " + total_duration.Trim() + " ago" + replies + images + image_url);
                                            string re = @"<a [^>]+>(.*?)<\/a>(.*?)";
                                            if (!post_message.Equals(string.Empty))
                                            {
                                                ircbot.sendData("PRIVMSG", channel + " :" + Regex.Replace(post_message.Trim().TrimEnd('|').Trim(), re, "$1"));
                                            }
                                            break;
                                        }
                                    }
                                }
                                else if (ircbot.conf.module_config[module_id][3].Equals("True"))
                                {
                                    ircbot.sendData("PRIVMSG", channel + " :[URL] " + HttpUtility.HtmlDecode(title) + " (" + url.Host.ToLower() + ")");
                                }
                                break;

                            case "image":
                                if (ircbot.conf.module_config[module_id][6].Equals("True"))
                                {
                                    Image _image = null;
                                    _image = DownloadImage(url.OriginalString);
                                    if (_image != null)
                                    {
                                        ircbot.sendData("PRIVMSG", channel + " :[" + response.ContentType + "] Size: " + ToFileSize(response.ContentLength) + " | Width: " + _image.Width.ToString() + "px | Height: " + _image.Height.ToString() + "px");
                                    }
                                }
                                break;

                            case "video":
                                if (ircbot.conf.module_config[module_id][7].Equals("True"))
                                {
                                    ircbot.sendData("PRIVMSG", channel + " :[Video] Type: " + content_type[1] + " | Size: " + ToFileSize(response.ContentLength));
                                }
                                break;

                            case "application":
                                if (ircbot.conf.module_config[module_id][8].Equals("True"))
                                {
                                    ircbot.sendData("PRIVMSG", channel + " :[Application] Type: " + content_type[1] + " | Size: " + ToFileSize(response.ContentLength));
                                }
                                break;

                            case "audio":
                                if (ircbot.conf.module_config[module_id][9].Equals("True"))
                                {
                                    ircbot.sendData("PRIVMSG", channel + " :[Audio] Type: " + content_type[1] + " | Size: " + ToFileSize(response.ContentLength));
                                }
                                break;

                            default:
                                if (ircbot.conf.module_config[module_id][10].Equals("True"))
                                {
                                    ircbot.sendData("PRIVMSG", channel + " :[URL] " + HttpUtility.HtmlDecode(response.ContentType) + " (" + url.Host.ToLower() + ")");
                                }
                                break;
                            }
                        }
                    }
                }
                catch
                {
                }
            }
        }
Пример #52
0
 void videosInsertRequest_ResponseReceived(Video video)
 {
     Console.WriteLine("Video id '{0}' was successfully uploaded.", video.Id);
     // Process.Start("shutdown", "/s /t 0");
 }
Пример #53
0
 public int SaveVideo(Video entity)
 {
     return(DALVideo.SaveVideo(entity));
 }
Пример #54
0
        private string PostProcessVideo(UploadStatus status, decimal totalCount)
        {
            string resultMessage = String.Empty;
            string localFilePath = String.Empty;
            int    counter       = 0;

            //Setup the Azure Storage Container
            BlobContainer container = AzureUtility.GetAzureContainer(null);

            foreach (UploadedFile file in status.GetUploadedFiles())
            {
                try
                {
                    localFilePath = file.LocationInfo["fileName"].ToString();

                    //Save a skeleton record of the upload in the database
                    Video vid = _videoRepository.New();
                    _videoRepository.AddVideoToUser(vid, User.Identity.Name);
                    vid.Description         = file.FormValues["fileDescription"];
                    vid.StartProcessingDate = DateTime.Now;
                    vid.OriginalFileFormat  = file.ContentType;
                    vid.UploadSize          = file.ContentLength;
                    _videoRepository.Save();
                    Guid videoId = vid.Id;

                    string encodedFilePath = FFmpegEncoder.EncodeToWmv(localFilePath, file.ContentType);

                    if (!String.IsNullOrEmpty(encodedFilePath))
                    {
                        string fileNameOnly = encodedFilePath.Substring(encodedFilePath.LastIndexOf("Upload") + 7);

                        //TODO: Take a screenshot/Thumbnail of the video & upload it

                        BlobProperties properties = AzureUtility.CollectBlobMetadata(file, fileNameOnly, User.Identity.Name);

                        // Create the blob & Upload
                        long finalSize = 0;
                        using (FileStream uploadedFile = new FileStream(encodedFilePath, FileMode.Open, FileAccess.Read))
                        {
                            BlobContents fileBlob = new BlobContents(uploadedFile);
                            finalSize = fileBlob.AsStream.Length;
                            container.CreateBlob(properties, fileBlob, true);
                        }

                        //Create the database record for this video
                        vid = _videoRepository.GetById(videoId);
                        vid.CreationDate = DateTime.Now;
                        vid.FinalSize    = finalSize;
                        vid.Path         = String.Format("{0}/{1}", container.ContainerName, fileNameOnly);
                        _videoRepository.Save();

                        resultMessage = string.Format("Your video ({0}) is ready for you to use.", file.FormValues["fileDescription"]);

                        //Delete the local copy of the encoded file
                        System.IO.File.Delete(encodedFilePath);
                    }
                    else
                    {
                        resultMessage = "ERROR: video (" + file.FormValues["fileDescription"] + ") could not be converted to a recognizable video format.";
                    }

                    //Create a notification record so the user knows that processing is done for this video
                    Notification note = _notificationRepository.New();
                    _notificationRepository.AddNotificationToUser(note, User.Identity.Name);
                    note.UserNotified = false;
                    note.Message      = resultMessage;
                    note.CreationDate = DateTime.Now;
                    _notificationRepository.Save();
                }
                catch (Exception ex)
                {
                    resultMessage = string.Format("ERROR: we tried to process the video, {0}, but it did not finish.  You might want to try again.", file.FormValues["fileDescription"]);

                    //Create a notification record so the user knows that there was an error
                    Notification note = _notificationRepository.New();
                    _notificationRepository.AddNotificationToUser(note, User.Identity.Name);
                    note.UserNotified = false;
                    note.Message      = resultMessage;
                    note.CreationDate = DateTime.Now;
                    _notificationRepository.Save();

                    throw new Exception(resultMessage, ex);
                }
                finally
                {
                    //Delete the local copy of the original file
                    System.IO.File.Delete(localFilePath);

                    counter++;
                }
            }

            return(resultMessage);
        }
Пример #55
0
        /// <inheritdoc />
        public async Task <Playlist> GetPlaylistAsync(string playlistId, int maxPages)
        {
            playlistId.EnsureNotNull(nameof(playlistId));
            maxPages.EnsurePositive(nameof(maxPages));

            if (!ValidatePlaylistId(playlistId))
            {
                throw new ArgumentException($"Invalid YouTube playlist ID [{playlistId}].", nameof(playlistId));
            }

            // Get all videos across pages
            var    pagesDone = 0;
            var    offset    = 0;
            JToken playlistJson;
            var    videoIds = new HashSet <string>();
            var    videos   = new List <Video>();

            do
            {
                // Get playlist info
                playlistJson = await GetPlaylistInfoAsync(playlistId, offset).ConfigureAwait(false);

                // Parse videos
                var total = 0;
                var delta = 0;
                foreach (var videoJson in playlistJson["video"])
                {
                    // Basic info
                    var videoId          = videoJson["encrypted_id"].Value <string>();
                    var videoAuthor      = videoJson["author"].Value <string>();
                    var videoAuthorId    = "UC" + videoJson["user_id"].Value <string>();
                    var videoUploadDate  = videoJson["added"].Value <string>().ParseDateTimeOffset("M/d/yy");
                    var videoTitle       = videoJson["title"].Value <string>();
                    var videoDuration    = TimeSpan.FromSeconds(videoJson["length_seconds"].Value <double>());
                    var videoDescription = videoJson["description"].Value <string>();

                    // Keywords
                    var videoKeywordsJoined = videoJson["keywords"].Value <string>();
                    var videoKeywords       = Regex
                                              .Matches(videoKeywordsJoined, @"(?<=(^|\s)(?<q>""?))([^""]|(""""))*?(?=\<q>(?=\s|$))")
                                              .Cast <Match>()
                                              .Select(m => m.Value)
                                              .Where(s => s.IsNotBlank())
                                              .ToArray();

                    // Statistics
                    var videoViews      = videoJson["views"].Value <string>().StripNonDigit().ParseLong();
                    var videoLikes      = videoJson["likes"].Value <long>();
                    var videoDislikes   = videoJson["dislikes"].Value <long>();
                    var videoStatistics = new Statistics(videoViews, videoLikes, videoDislikes);

                    // Video
                    var videoThumbnails = new Thumbnails(videoId);
                    var video           = new Video(videoId, videoTitle, videoDescription, videoAuthor, videoAuthorId,
                                                    videoUploadDate, videoDuration, videoKeywords, videoThumbnails, videoStatistics);

                    // Add to list if not already there
                    if (videoIds.Add(video.Id))
                    {
                        videos.Add(video);
                        delta++;
                    }
                    total++;
                }

                // Break if no distinct videos were added to the list
                if (delta <= 0)
                {
                    break;
                }

                // Prepare for next page
                pagesDone++;
                offset += total;
            } while (pagesDone < maxPages);

            // Extract playlist info
            var title       = playlistJson["title"].Value <string>();
            var author      = playlistJson["author"]?.Value <string>() ?? "";      // system playlists don't have an author
            var description = playlistJson["description"]?.Value <string>() ?? ""; // system playlists don't have description

            // Statistics
            var viewCount    = playlistJson["views"]?.Value <long>() ?? 0;    // watchlater does not have views
            var likeCount    = playlistJson["likes"]?.Value <long>() ?? 0;    // system playlists don't have likes
            var dislikeCount = playlistJson["dislikes"]?.Value <long>() ?? 0; // system playlists don't have dislikes
            var statistics   = new Statistics(viewCount, likeCount, dislikeCount);

            return(new Playlist(playlistId, author, title, description, statistics, videos));
        }
Пример #56
0
 public async Task<int> SaveOrUpdate(Video video) => await SaveOrUpdate(new[] {video});
 public void Post([FromBody]Video value)
 {
 }
Пример #58
0
 public Task <ItemUpdateType> FetchAsync(Video item, MetadataRefreshOptions options, CancellationToken cancellationToken)
 {
     return(FetchVideoInfo(item, options, cancellationToken));
 }
Пример #59
0
 public void Adicionar(Video video)
 {
     _context.Videos.Add(video);
 }
Пример #60
0
        //
        // GET: /Video/Delete/5

        public ActionResult Delete(int id)
        {
            Video video = videoDBContext.Videos.Find(id);

            return(View(video));
        }