public static async Task <string> StreamUrl(Song Song, bool AllFormats = true) { if (Song.Type == SongType.YouTube) { var Videos = VideoLibrary.YouTube.Default.GetAllVideos(Song.Url); YouTubeVideo MaxVid = null; foreach (var Vid in Videos) { if (MaxVid == null || (Vid.AudioBitrate >= MaxVid.AudioBitrate && (AllFormats || Vid.AudioFormat == AudioFormat.Aac))) { MaxVid = Vid; } } if (MaxVid == null) { return(string.Empty); } return(await MaxVid.GetUriAsync()); } else if (Song.Type == SongType.SoundCloud) { var SC = await($"http://api.soundcloud.com/resolve?url={Song.Url}&client_id={SoundCloud}").WebResponse(); if (SC != string.Empty && SC.StartsWith("{\"kind\":\"track\"")) { return($"{JObject.Parse(SC)["stream_url"]}?client_id={SoundCloud}"); } } else if (Song.Type == SongType.Telegram) { return(await GetTelegramUrl(Song.Url)); } return(Song.Url); }
public static async Task <IEnumerable <Song> > ResolveSong(string query) { List <Song> m_songs = new List <Song>(); if (string.IsNullOrWhiteSpace(query)) { throw new ArgumentNullException(nameof(query)); } try { if (IsRadioLink(query)) { query = await HandleStreamContainers(query).ConfigureAwait(false) ?? query; m_songs.Add(new Song(new SongInfo { Uri = query, Title = $"{query}", Provider = "Radio Stream", Query = query })); return(m_songs); } else { var links = await Utilities.FindYoutubeUrlByKeywords(query).ConfigureAwait(false); foreach (var link in links) { if (string.IsNullOrWhiteSpace(link)) { throw new OperationCanceledException("Not a valid youtube query."); } var allVideos = await Task.Factory.StartNew(async() => await YouTube.Default.GetAllVideosAsync(link).ConfigureAwait(false)).Unwrap().ConfigureAwait(false); var videos = allVideos.Where(v => v.AdaptiveKind == AdaptiveKind.Audio); YouTubeVideo video = null; try { video = videos .Where(v => v.AudioBitrate < 192) .OrderByDescending(v => v.AudioBitrate) .FirstOrDefault(); } catch { } if (video == null) // do something with this error { continue; //throw new Exception("Could not load any video elements based on the query."); } var m = Regex.Match(query, @"\?t=((?<h>\d*)h)?((?<m>\d*)m)?((?<s>\d*)s?)?"); int gotoTime = 0; if (m.Captures.Count > 0) { int hours; int minutes; int seconds; int.TryParse(m.Groups["h"].ToString(), out hours); int.TryParse(m.Groups["m"].ToString(), out minutes); int.TryParse(m.Groups["s"].ToString(), out seconds); gotoTime = hours * 60 * 60 + minutes * 60 + seconds; } m_songs.Add(new Song(new SongInfo { Title = video.Title.Substring(0, video.Title.Length - 10), // removing trailing "- You Tube" Provider = "YouTube", Uri = await video.GetUriAsync(), Duration = await Utilities.GetVideoDuration(link), Query = link, })); m_songs.Last().SkipTo = gotoTime; } return(m_songs); } } catch (Exception ex) { Logging.LogException(LogType.Bot, ex, "Failed to resolve song"); } return(m_songs); }
/// <summary> /// Get the MediaSource of the specified youtube video, preferring audio stream to video /// </summary> /// <param name="videoId">The id of the video to get audio for</param> /// <returns>The audio of the track</returns> private async Task <MediaSource> GetAudioAsync(string videoId, string trackName) { IEnumerable <YouTubeVideo> videos = await YouTube.Default.GetAllVideosAsync(string.Format(_videoUrlFormat, videoId)); YouTubeVideo maxAudioVideo = null; YouTubeVideo maxNonAudioVideo = null; try { for (int i = 0; i < videos.Count(); i++) { YouTubeVideo video = videos.ElementAt(i); if (video.AdaptiveKind == AdaptiveKind.Audio) { if (maxAudioVideo == null || video.AudioBitrate > maxAudioVideo.AudioBitrate) { maxAudioVideo = video; } } else { if (maxNonAudioVideo == null || video.AudioBitrate > maxNonAudioVideo.AudioBitrate) { maxNonAudioVideo = video; } } } } catch (HttpRequestException) { try { string url = await videos.ElementAt(0).GetUriAsync(); return(MediaSource.CreateFromUri(new Uri(url))); } catch (Exception) { return(MediaSource.CreateFromUri(new Uri(""))); } } if (maxAudioVideo != null) { string url = await maxAudioVideo.GetUriAsync(); return(MediaSource.CreateFromUri(new Uri(url))); } else if (maxNonAudioVideo != null) { HttpClientHandler handler = new HttpClientHandler() { AllowAutoRedirect = true }; HttpClient client = new HttpClient(handler); CancellationTokenSource cancelToken = new CancellationTokenSource(); cancelToken.Token.Register(() => { client.CancelPendingRequests(); client.Dispose(); App.mainPage.HideCancelDialog(localLock); }); try { string url = await maxNonAudioVideo.GetUriAsync(); Task <HttpResponseMessage> clientTask = client.GetAsync(new Uri(url), HttpCompletionOption.ResponseContentRead, cancelToken.Token); Task completedTask = await Task.WhenAny(clientTask, Task.Delay(5000)); if (completedTask != clientTask) { if (App.isInBackgroundMode) { cancelToken.Cancel(); return(MediaSource.CreateFromUri(new Uri(""))); } else { App.mainPage.ShowCancelDialog(localLock, cancelToken, trackName); await Task.Run(() => { while ((clientTask.Status == TaskStatus.WaitingForActivation || clientTask.Status == TaskStatus.WaitingForChildrenToComplete || clientTask.Status == TaskStatus.WaitingToRun || clientTask.Status == TaskStatus.Running) && !cancelToken.Token.IsCancellationRequested) { } }); App.mainPage.HideCancelDialog(localLock); if (cancelToken.Token.IsCancellationRequested) { return(MediaSource.CreateFromUri(new Uri(""))); } } } HttpResponseMessage response = clientTask.Result; Stream stream = await response.Content.ReadAsStreamAsync(); return(MediaSource.CreateFromStream(stream.AsRandomAccessStream(), "video/x-flv")); } catch (OperationCanceledException) { return(MediaSource.CreateFromUri(new Uri(""))); } } return(MediaSource.CreateFromUri(new Uri(""))); }
public async void Download(Download video) { using (var cli = Client.For(new YouTube())) //use a libvideo client to get video metadata { IEnumerable <YouTubeVideo> downloadLinks = null; try { downloadLinks = cli.GetAllVideos(video.VideoData.Url).OrderBy(br => - br.AudioBitrate); //sort by highest audio quality } catch (ArgumentException) { video.DownloadFailed = true; downloadManager.RemoveActive(video); //invalid url gui.DisplayMessage("Invalid URL!"); threadHandler.RemoveActive(Thread.CurrentThread); Thread.CurrentThread.Abort(); } YouTubeVideo highestQuality = null; try { highestQuality = downloadLinks.First(); //grab best quality link } catch { video.DownloadFailed = true; downloadManager.RemoveActive(video); gui.DisplayMessage("Unable to download video"); gui.OnProgressChanged(); return; } //setup http web request to get video bytes var asyncRequest = await highestQuality.GetUriAsync(); var request = (HttpWebRequest)HttpWebRequest.Create(Convert.ToString(asyncRequest)); request.AllowAutoRedirect = true; request.Method = "GET"; request.Proxy = HttpWebRequest.DefaultWebProxy; request.Proxy.Credentials = CredentialCache.DefaultNetworkCredentials; //execute request and save bytes to buffer using (var response = (HttpWebResponse)request.GetResponse()) { var len = response.ContentLength; var buffer = new byte[256]; using (var stream = response.GetResponseStream()) { stream.ReadTimeout = 5000; using (var tempbytes = new TempFile()) { FileStream bytes = new FileStream(tempbytes.Path, FileMode.Open); while (bytes.Length < len) { try { var read = stream.Read(buffer, 0, buffer.Length); if (read > 0) { bytes.Write(buffer, 0, read); double percentage = bytes.Length * 100 / len; if (video.DownloadProgress != percentage) { video.SetDownloadProgress(percentage); gui.OnProgressChanged(); } } else { break; } } catch { video.DownloadFailed = true; downloadManager.RemoveActive(video); //thread aborted return; } } //check integrity of byte array if (bytes.Length != len) { video.DownloadFailed = true; downloadManager.RemoveActive(video); gui.DisplayMessage("File content is corrupted!"); threadHandler.RemoveActive(Thread.CurrentThread); Thread.CurrentThread.Abort(); } else { if (video.Bitrate == 0) //video { video.SetConvertProgress(100); string videoPath = Path.Combine(downloadManager.DownloadsPath, highestQuality.FullName); File.Copy(tempbytes.Path, videoPath, true); gui.DisplayMessage("Successful!"); } else //mp3 { //create temp video file to convert to mp3 and dispose of when done TimeSpan duration = GetVideoDuration(tempbytes.Path); string mp3Name = highestQuality.FullName + ".mp3"; string audioPath = Path.Combine(downloadManager.DownloadsPath, mp3Name); ToMp3(tempbytes.Path, audioPath, duration, video, video.Bitrate); //convert to mp3 } } bytes.Dispose(); bytes.Close(); } } } } downloadManager.RemoveActive(video); }