public void saveAudio(YouTubeVideo video) { string folder; folder = GetCustomExportFolder(); string path = Path.Combine(folder, video.FullName); File.WriteAllBytes(path, video.GetBytes()); var inputFile = new MediaFile { Filename = path }; var outputFile = new MediaFile { Filename = path.Replace(".mp4", "") + ".mp3" }; using (var engine = new Engine()) { engine.Convert(inputFile, outputFile); } if (File.Exists(path)) { File.Delete(path); } }
public void stop() { Console.WriteLine("Stopping music bot..."); queue.Clear(); currentSong = null; playingSong = false; }
public void saveVideo(YouTubeVideo video) { string folder = GetCustomExportFolder(); string path = Path.Combine(folder, video.FullName); File.WriteAllBytes(path, video.GetBytes()); }
public void addVideo(string url) { YouTubeVideo video = youTube.GetVideo(url); Videos.Add(video); OnNotifyPropertyChanged(nameof(Videos)); }
public MusicQueueItem(YouTubeVideo v, string path, TimeSpan dur, string thurl) { video = v; Filepath = path; duration = dur; ThumbnailURL = thurl; }
public void addVideoToPlaylist() { Console.Write("Enter playlist name: "); String playlistName = Console.ReadLine(); try { Playlist playlist = this.playlists[playlistName]; Console.Write("Enter video title: "); String videoTitle = Console.ReadLine(); try { YouTubeVideo video = this.videos[videoTitle]; playlist.addVideo(video); } catch (KeyNotFoundException) { Console.WriteLine("Video of given title does not exist!"); } } catch (KeyNotFoundException) { Console.WriteLine("Playlist of given name does not exist!"); } }
private YouTubeVideo GetYoutube(string url) { YouTube b = YouTube.Default; YouTubeVideo v = b.GetVideo(url); return(v); }
public async Task CrawlService_CanCrawlFromChannelIdAsync() { var video = new YouTubeVideo() { Id = "id", MentionedVideos = new string[] { } }; var videoIds = new [] { "id" }; var youtubeMock = new Mock <IYouTubeApi>(); youtubeMock .Setup(s => s.GetVideoById("id")) .ReturnsAsync(video); youtubeMock .Setup(s => s.GetVideoIdsByChannelId("channel_id")) .ReturnsAsync(videoIds.AsEnumerable()); var dbMock = new Mock <IRepository <YouTubeVideo> >(); dbMock.Setup(db => db.Contains("id")).ReturnsAsync(false); var crawler = new CrawlerService( youtubeMock.Object, dbMock.Object, Mock.Of <ILogger <CrawlerService> >()); await crawler.CrawlChannelAsync("channel_id", 1); youtubeMock.Verify(y => y.GetVideoIdsByChannelId("channel_id")); youtubeMock.Verify(y => y.GetVideoById("id")); dbMock.Verify(m => m.Contains("id")); dbMock.Verify(m => m.Set(video, "id")); }
/// <summary> /// Save YouTube video /// </summary> /// <param name="url">video YouTube url</param> /// <param name="path">absolute path of where save this video</param> /// <returns>operation completed or not</returns> bool SaveVideoOnDisk(string url, string path) { YouTube youTube = YouTube.Default; YouTubeVideo video = null; try { video = youTube.GetVideo(url); if (File.Exists(Path.Combine(path, video.FullName))) { Console.WriteLine("The file '" + Path.Combine(path, video.FullName) + "' already exists. Operation canceled."); return(false); } File.WriteAllBytes(Path.Combine(path, video.FullName), video.GetBytes()); return(true); } catch (Exception) { throw; } finally { youTube = null; video = null; } }
public IList<YouTubeVideo> GetVideos() { if (_videoFeed == null) return new List<YouTubeVideo>(); var videos = new List<YouTubeVideo>(); IList<String> szErrorList = new List<String>(); foreach (Video videoFeedEntry in _videoFeed.Entries) { try { var video = new YouTubeVideo { Title = (videoFeedEntry.Title != null ? videoFeedEntry.Title : "[no title]"), Description = (videoFeedEntry.Description != null ? videoFeedEntry.Description : "[no description]"), Link = (videoFeedEntry.WatchPage != null ? videoFeedEntry.WatchPage.AbsoluteUri : "http://www.youtube.com/watch?v=" + videoFeedEntry.VideoId) }; video.FlvUrl = UrlConverter.GetFlvUrlFromYoutubeVideoUrl(video.Link); if (!string.IsNullOrEmpty(video.FlvUrl)) { videos.Add(video); } } catch (NotSignedInException) { szErrorList.Add(videoFeedEntry.Title); } } if (szErrorList.Count > 0) ShowErrors(szErrorList); return videos; }
public async Task Handle(AddSampleYouTubeVideos busCommand) { // Get some sample users to be the authors for the videos we're going to add List <Guid> userIds = await _sampleDataRetriever.GetRandomSampleUserIds(busCommand.NumberOfVideos).ConfigureAwait(false); if (userIds.Count == 0) { Logger.Warn("No sample users available. Cannot add sample YouTube videos."); return; } // Get some unused sample videos List <YouTubeVideo> sampleVideos = await _youTubeManager.GetUnusedVideos(busCommand.NumberOfVideos).ConfigureAwait(false); // Add them to the site using sample users for (int idx = 0; idx < sampleVideos.Count; idx++) { YouTubeVideo sampleVideo = sampleVideos[idx]; Guid userId = userIds[idx]; // Submit the video await _videoCatalog.SubmitYouTubeVideo(new SubmitYouTubeVideo { VideoId = Guid.NewGuid(), UserId = userId, YouTubeVideoId = sampleVideo.YouTubeVideoId, Name = sampleVideo.Name, Description = sampleVideo.Description, Tags = sampleVideo.SuggestedTags }).ConfigureAwait(false); // Mark them as used so we make a best effort not to reuse sample videos and post duplicates await _youTubeManager.MarkVideoAsUsed(sampleVideo).ConfigureAwait(false); } }
public string ParseCharacter(YouTubeVideo ytVideo, bool parsePlayer2) { if (ytVideo.SourceChannel.ToLower() == "gamestorage ch" || ytVideo.SourceChannel.ToLower() == "huawen sol") { string playerAndCharacter; if (parsePlayer2) { playerAndCharacter = LenticularBracketTitleParser(ytVideo.Title, parsePlayer2); } else { playerAndCharacter = LenticularBracketTitleParser(ytVideo.Title); } // HuaWen Sol uploads videos that highlight one single player and their character, // so cover these instances by ensuring that the character name will be an empty string if (parsePlayer2 && string.IsNullOrWhiteSpace(playerAndCharacter)) { return(null); } else { // Add 1 to the index since we want to start the substring after the opening parenthesis var openParenthesisIndex = playerAndCharacter.IndexOf('(') + 1; var character = playerAndCharacter[openParenthesisIndex..].Replace(")", string.Empty);
private void bgwVideo_DoWork(object sender, DoWorkEventArgs e) { try { var backgroundWorker = sender as BackgroundWorker; bgwVideo.ReportProgress(20); var youTube = YouTube.Default; bgwVideo.ReportProgress(20); YouTubeVideo video = youTube.GetVideo(this.txtLink.Text); this.videoTitle = video.Title; File.WriteAllBytes(Path.Combine(folderName, video.FullName), video.GetBytes()); bgwVideo.ReportProgress(40); File.WriteAllBytes(Path.Combine(folderName, video.FullName), video.GetBytes()); bgwVideo.ReportProgress(20); if (bgwVideo.CancellationPending) { e.Cancel = true; } } catch (Exception ex) { this.Invoke((Func <DialogResult>)(() => MessageBox.Show(this, "No se puede descargar el vídeo.\nCompruebe el enlace."))); } }
private void openNewDownloadForm(YouTubeVideo item, string url) { VideoDownloader videoDownloader = new VideoDownloader(); videoDownloader.Visible = true; videoDownloader.DownloadVideo(item, url); }
public YouTubeVideo YoutubeVideoValidation(string YouTubeID) { YouTubeVideo YTVideo = new YouTubeVideo(); var ValidationRequest = yt.Videos.List("snippet"); ValidationRequest.Id = YouTubeID; var ListResponse = ValidationRequest.Execute(); if (ListResponse.Items.Count > 0) { if (Convert.IsDBNull(ListResponse.Items[0].Snippet.Thumbnails.Maxres)) { YTVideo.BannerLink = ListResponse.Items[0].Snippet.Thumbnails.Maxres.Url; } else { if (Convert.IsDBNull(ListResponse.Items[0].Snippet.Thumbnails.Standard)) { YTVideo.BannerLink = ListResponse.Items[0].Snippet.Thumbnails.Standard.Url; } else { YTVideo.BannerLink = ListResponse.Items[0].Snippet.Thumbnails.High.Url; } } YTVideo.ActiveFlag = true; } return(YTVideo); }
public async Task <IActionResult> Edit(int id, [Bind("VideoID,youtubeId")] YouTubeVideo youTubeVideo) { if (id != youTubeVideo.VideoID) { return(NotFound()); } if (ModelState.IsValid) { try { _context.Update(youTubeVideo); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!YouTubeVideoExists(youTubeVideo.VideoID)) { return(NotFound()); } else { throw; } } return(RedirectToAction(nameof(Index))); } return(View(youTubeVideo)); }
private static YouTubeVideoThumbnail GetThumbnail(YouTubeVideo video) { var thumbnails = new List <YouTubeVideoThumbnail>(); if (video.Snippet.Thumbnails.HasDefault) { thumbnails.Add(video.Snippet.Thumbnails.Default); } if (video.Snippet.Thumbnails.HasStandard) { thumbnails.Add(video.Snippet.Thumbnails.Standard); } if (video.Snippet.Thumbnails.HasMedium) { thumbnails.Add(video.Snippet.Thumbnails.Medium); } if (video.Snippet.Thumbnails.HasHigh) { thumbnails.Add(video.Snippet.Thumbnails.High); } if (video.Snippet.Thumbnails.HasMaxRes) { thumbnails.Add(video.Snippet.Thumbnails.MaxRes); } var thumbnail = thumbnails.OrderBy(x => x.Width).FirstOrDefault(x => x.Width >= 350); return(thumbnail); }
public void DownloadAction() { try { IsDownloading = true; youTube = YouTube.Default; // starting point for YouTube actions video = youTube.GetVideo(Url); // gets a Video object with info about the video using (var writer = new BinaryWriter(System.IO.File.Open(@"D:\" + video.FullName, FileMode.Create))) { var bytesLeft = video.GetBytes().Length; var array = video.GetBytes(); ProgressMax = array.Length; var bytesWritten = 0; while (bytesLeft > 0) { int chunk = Math.Min(64, bytesLeft); writer.Write(array, bytesWritten, chunk); bytesWritten += chunk; bytesLeft -= chunk; CurrentProgress = bytesWritten; } } } catch (Exception ie) { MessageBox.Show($"Exception : {ie.Message}\r\n{ie.StackTrace}"); } finally { IsDownloading = false; youTube = null; video = null; } }
public async Task YouTubeService_GetVideoById() { var id = "ci1PJexnfNE"; YouTubeService service = CreateService(); var request = service.Videos.List("id,snippet,statistics,contentDetails"); request.Id = id; var result = await request.ExecuteAsync(); var item = Assert.Single(result.Items); Assert.Equal(id, item.Id); Assert.StartsWith("Why is C such an influential language?", item.Snippet.Description); Assert.Equal("UC9-y-6csu5WGm29I7JiwpnA", item.Snippet.ChannelId); Assert.NotNull(item.Statistics); Assert.NotNull(item.ContentDetails); // Assert.Empty(item.Snippet.Tags); var video = YouTubeVideo.From(item); Assert.Equal(2, video.MentionedVideos.Count()); Assert.Equal("9T8A89jgeTI", video.MentionedVideos.First()); Assert.Equal("rh7kpkwXnwA", video.MentionedVideos.Skip(1).Single()); Assert.Equal(TimeSpan.Parse("00:10:50"), video.Length); }
private async Task DownloadToFile(MetadataTask task, string pathToSave) { YouTubeVideo vid = task.SelectedVideo.YoutubeVideo; long totalDownloaded = 0; string tempFile = $"{pathToSave}.tmp"; string mp3File = $"{pathToSave}.mp3"; try { task.Status = MetadataState.RUNNING; task.Message = String.Format(Properties.Resources.COMMAND_MSG_URI_SEARCH); using (ChunkDownloader client = new ChunkDownloader()) { client.OnProgress += (new ProgressHandler(task)).HandleProgress; totalDownloaded = await client.DownloadToFile(vid.Uri, tempFile); } task.Message = String.Format(Properties.Resources.COMMAND_MSG_START_MP3, tempFile); FFMpegConverter converter = new FFMpegConverter(); converter.ConvertProgress += (new ConvertProgressHandler(task)).HandleProgress; converter.ConvertMedia(tempFile, mp3File, "mp3"); System.IO.File.Delete(tempFile); task.Status = MetadataState.METADATA; task.Message = String.Format(Properties.Resources.COMMAND_MSG_END_MP3, mp3File); } catch (Exception ex) { task.Status = MetadataState.ERROR; task.Message = ex.Message + Environment.NewLine + ex.StackTrace; } }
public void Crawl() { var newsPages = _newsPages .Where(x => x.VideoLink != null) .Where(x => x.Video == null).ToArray(); foreach (var newsPage in newsPages) { try { if (newsPage.Video != null) { return; } var id = YouTubeVideo.ParseId(newsPage.VideoLink); var video = _videos.FirstOrDefault(x => x.ExternalId == id); newsPage.Video = video ?? _youTubeProvider.Get(id); } catch (Exception e) { Trace.TraceError(e.Message); } _unitOfWork.SaveChanges(); } }
private string getSaveLocation(YouTubeVideo ytv) { string path = null; var dialog = new Microsoft.Win32.SaveFileDialog(); dialog.RestoreDirectory = true; dialog.Title = "Save as..."; dialog.DefaultExt = cbxFormat.SelectedValue as string; dialog.Filter = string.Format("{0} files|*.{1}|All files|*.*", dialog.DefaultExt.ToUpper(), dialog.DefaultExt); dialog.FileName = ytv.Title; bool?ok = dialog.ShowDialog(); if (ok.HasValue && ok.Value) { path = dialog.FileName; if (File.Exists(path)) { File.Delete(path); } } return(path); }
private async void Button1_Click(object sender, EventArgs e) { using (FolderBrowserDialog fbd = new FolderBrowserDialog() { Description = "Select Path" }) { if (textBox1.Text != "") { if (fbd.ShowDialog() == DialogResult.OK) { var youtube = YouTube.Default; YouTubeVideo video = await youtube.GetVideoAsync(textBox1.Text); string filename = ""; string ending = comboBox1.SelectedItem.ToString(); setName(filename, video.FullName, ending); using (WebClient client = new WebClient()) { client.DownloadFileCompleted += client_Completed; client.DownloadProgressChanged += dlProgressChange; client.DownloadFileAsync(new Uri(video.GetUri()), fbd.SelectedPath + @"\" + getName()); //File.WriteAllBytes(fbd.SelectedPath + @"\" + filename, await video.GetBytesAsync()); } } } else { MessageBox.Show("Enter valid URL"); } } }
// link de uma playlist = https://www.youtube.com/playlist?list=PLb2HQ45KP0WstF2TXsreWRv-WUr5tqzy1 // link de um video = https://www.youtube.com/watch?v=KxiHM3pQbGQ public ActionResult Index(string link = null) { List <YouTubeVideo> videos = new List <YouTubeVideo>(); if (Request.IsAjaxRequest()) { if (link.Contains("https://www.youtube.com/playlist?list=")) { string[] split = link.Split('='); var playlistId = split[1].ToString(); videos = YouTubeApi.GetPlaylistInfo(playlistId); return(PartialView("_PlaylistVideos", videos)); } else { string[] split = link.Split('='); var videoId = split[1].ToString(); YouTubeVideo video = new YouTubeVideo(videoId); videos.Add(video); return(PartialView("_PlaylistVideos", videos)); } } return(View(videos)); }
/// <summary> /// Main start of the program /// </summary> /// <param name="apikey">Key provided by the user (Shazam api key)</param> /// <param name="url">YouTube url of the song</param> private bool Start(string apikey, string url, string searchTerms = "") { EnableFields(false); YouTube youtube = YouTube.Default; video = youtube.GetVideo(url); if (searchTerms.Trim() == string.Empty) { song = getSongInfo(video.FullName, apikey); } else { song = getSongInfo(searchTerms, apikey); } if (song == null) { var status = "No song found"; var message = "Enter a valid title and/or artist to specify song."; ShowError(status, message); UpdateStatusUI("Invalid song title and/or artist.", true); return(false); } UpdateSongInfoDisplay(); UpdateStatusUI("Verify song information and press Download to continue."); EnableFields(true); return(true); }
public XDoc Media( [DekiExtParam("media uri")] XUri source, [DekiExtParam("media width (default: player dependent)", true)] float?width, [DekiExtParam("media height (default: player dependent)", true)] float?height, [DekiExtParam("auto-start media on load (default: false)", true)] bool?start ) { // determine the media type AMedia media = null; media = media ?? YouTubeVideo.New(source); media = media ?? GoogleVideo.New(source); media = media ?? ViddlerVideo.New(source); media = media ?? VeohVideo.New(source); media = media ?? UStreamVideo.New(source); media = media ?? KalturaVideo.New(source, Config); media = media ?? WindowsMedia.New(source); media = media ?? UnknownMedia.New(source); if (media != null) { media.Width = width; media.Height = height; media.AutoPlay = start ?? false; return(media.AsXDoc()); } return(XDoc.Empty); }
public Core.Classes.Video GetVideoByUrl(Uri uri) { var youtube = YouTube.Default; YouTubeVideo ytVideo = youtube.GetVideo(uri.AbsoluteUri); var filePath = $@"{GetHashString(uri.ToString())}.mp4"; byte[] bytes = null; if (!File.Exists(filePath)) { bytes = ytVideo.GetBytes(); File.WriteAllBytes(filePath, bytes); } else { bytes = File.ReadAllBytes(filePath); } return(new Core.Classes.Video( ytVideo.Title, ytVideo.Uri, (Core.Classes.VideoFormat)ytVideo.Format, (Core.Classes.AudioFormat)ytVideo.AudioFormat, bytes, filePath )); }
private void AddNewDownloadJob(IEnumerable <YouTubeVideo> videos) { YouTubeVideo maxQualityVideo = videos.First(); foreach (YouTubeVideo v in videos) { if (v.Resolution > maxQualityVideo.Resolution && v.AudioBitrate > maxQualityVideo.AudioBitrate) { maxQualityVideo = v; } } YouTubeVideo maxBitrate = videos.First(i => i.AudioBitrate == videos.Max(j => j.AudioBitrate)); switch (formatDownloadComboBox.Text) { case (FileExtensions.mp4): AddJobRow(new Agent(maxQualityVideo, settings), jobTable); break; case (FileExtensions.mp3): AddJobRow(new Agent(maxBitrate, settings, true), jobTable); break; } }
private void Downloader (YouTubeVideo video, MainProgramElements mainWindow, bool isAudio) { string temporaryDownloadPath = Path.Combine(this.UserSettings.TemporarySaveLocation, video.FullName); string movingPath = Path.Combine(this.UserSettings.MainSaveLocation, video.FullName); if (this.UserSettings.ValidationLocations.All(path => !File.Exists(Path.Combine(path, video.FullName)) && !File.Exists(movingPath)) { if(isAudio) { var audioDownloader = new AudioDownloader (video, temporaryDownloadPath);; audioDownloader.AudioExtractionProgressChanged += (sender, args) => mainWindow.CurrentDownloadProgress = (int)(85 + args.ProgressPercentage * 0.15); audioDownloader.Execute(); } else { var videoDownloader = new VideoDownloader (video, temporaryDownloadPath); videoDownloader.DownloadProgressChanged += ((sender, args) => mainWindow.CurrentDownloadProgress = (int)args.ProgressPercentage); videoDownloader.Execute(); } if (!temporaryDownloadPath.Equals(movingPath, StringComparison.OrdinalIgnoreCase)) File.Move(temporaryDownloadPath, movingPath); } else { throw new DownloadCanceledException(string.Format(CultureInfo.CurrentCulture, "The download of #{0} '{1}({2})' has been canceled because it already existed.", videoToUse.Position, RemoveIllegalPathCharacters(video.Title).Truncate(10), videoToUse.Location.Truncate(100))); } }
public string ParseCharacter(YouTubeVideo ytVideo, bool parsePlayer2) { if (ytVideo.SourceChannel.ToLower() == "guilty gear strive movies") { Regex ggsmCharacterRegex = new(@"(?<=\s)\((.+) vs (.+)\)"); var charNameMatch = ggsmCharacterRegex.Match(ytVideo.Title); if (charNameMatch.Success) { string extractedContent; if (parsePlayer2) { extractedContent = charNameMatch.Groups[2].Value; } else { extractedContent = charNameMatch.Groups[1].Value; } // Want to split the Japanese glyphs for the character name // (usually katakana) from the English character name, then // give the English name proper name casing instead of all caps. // Example: メイ/MAY --> MAY --> May var englishName = extractedContent.Split('/')[1]; var characterInNamecase = englishName[0] + englishName[1..].ToLower();
public IActionResult SaveMP3([FromBody] AddMp3Body addMp3Body) { if (addMp3Body.source == "" || addMp3Body.source == null) { return(BadRequest("Invalid source.")); } if (addMp3Body.videoURL == "" || addMp3Body.videoURL == null) { return(BadRequest("Invalid video.")); } if (addMp3Body.soundName == "" || addMp3Body.soundName == null) { return(BadRequest("Invalid sound name.")); } YouTubeVideo video = soundpadService.GetYouTubeVideo(addMp3Body.videoURL); if (video == null) { return(BadRequest($"Invalid YouTube video URL.")); } if (video.Info.LengthSeconds > 600) { return(BadRequest($"Invalid YouTube video length; please keep under 10 minutes long.")); } bool saved = soundpadService.SaveMP3(addMp3Body.source, video, addMp3Body.soundName); return(!saved?BadRequest($"A sound with the name '{addMp3Body.soundName}' already exists in this category.") : Ok(saved)); }
/// <summary> /// Gets the description of a video from the YouTube DOM. /// </summary> /// <param name="video">Video to get description from.</param> private static void getVideoDescription(ref YouTubeVideo video) { var url = string.Format("https://www.youtube.com/watch?v={0}", video.Code); var webClient = new WebClient(); var source = string.Empty; try { var bytes = webClient.DownloadData(url); source = Encoding.UTF8.GetString(bytes); } catch { } var sp = source.IndexOf("id=\"eow-description\"", StringComparison.InvariantCultureIgnoreCase); if (sp == -1) return; var description = source.Substring(sp); description = description.Substring(description.IndexOf(">", StringComparison.InvariantCultureIgnoreCase) + 1); description = description.Substring(0, description.IndexOf("<", StringComparison.InvariantCultureIgnoreCase)); video.Description = description; }
/// <summary> /// Adds a video to the group /// </summary> /// <param name="video">A new YouTubeVideo to add to the group</param> /// <returns>Whether the video was successfully added. Returns false if the video is already in the group.</returns> public bool AddVideo(YouTubeVideo video) { if (!VideoGroupList.Contains(video)) return false; VideoGroupList.Add(video); CheckVideosReady(); return true; }
public VideoGroupEventArgs(YouTubeVideo video, int progress) { Video = video; Progress = progress; }
/// <summary> /// Removes a video from the group /// </summary> /// <param name="video">A YouTubeVideo to remove from the group</param> /// <returns>Whether the group was successfully removed from the group</returns> public bool RemoveVideo(YouTubeVideo video) { if (!VideoGroupList.Contains(video)) return false; VideoGroupList.Remove(video); return true; }