/// <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);
        }
Beispiel #2
0
        private YouTubeVideo GetYoutube(string url)
        {
            YouTube      b = YouTube.Default;
            YouTubeVideo v = b.GetVideo(url);

            return(v);
        }
Beispiel #3
0
        protected async void youtubevideo2(string id)
        {
            try
            {
                ProgressProgressBar2.IsEnabled = true;
                var uri = await YouTube.GetVideoUriAsync(id, YouTubeQuality.Quality720P);

                // “JPF_iD1IXyc” video id from youtube video link
                if (uri != null)
                {
                    YouTubePlayerMediaElement2.Source = uri.Uri;
                    YouTubePlayerMediaElement2.Play();
                    // YouTubePlayerMediaElement.Source = uri.Uri;
                    // YouTubePlayerMediaElement.Play();
                }
                else
                {
                    Debugger.Break();
                    // TODO: Show error message (no video uri found)
                    ProgressProgressBar.IsEnabled = false;
                }
            }
            catch (Exception exception)
            {
                // TODO: Add exception handling
                Debugger.Break();
                ProgressProgressBar.IsEnabled = false;
            }
        }
        /// <summary>
        /// Starts loading the feed and parse the response.
        /// </summary>
        /// <returns></returns>
        public async Task <IEnumerable <YouTubeSchema> > Load()
        {
            string xmlContent = await DownloadAsync(_uri);

            var atoms   = XNamespace.Get("http://www.w3.org/2005/Atom");
            var medians = XNamespace.Get("http://search.yahoo.com/mrss/");

            var doc = XDocument.Parse(xmlContent);

            var result = (from entry in doc.Descendants(atoms.GetName("entry"))
                          select new YouTubeSchema()
            {
                Title = GetYouTubeTitle(atoms, entry, medians),
                Summary = GetYouTubeSummary(atoms, entry, medians),
                VideoUrl = GetVideoUrl(atoms, entry),
                ImageUrl = entry.Descendants(medians.GetName("thumbnail")).Select(thumbnail => thumbnail.Attribute("url").Value).FirstOrDefault()
            }).ToArray();

            foreach (var item in result)
            {
                item.MediaUrl = (await YouTube.GetVideoUriAsync(item.VideoId, YouTubeQuality.Unknown)).Uri.ToString();
            }

            return(result);
        }
Beispiel #5
0
        /// <summary>
        /// Populates the page with content passed during navigation.  Any saved state is also
        /// provided when recreating a page from a prior session.
        /// </summary>
        /// <param name="sender">
        /// The source of the event; typically <see cref="NavigationHelper"/>
        /// </param>
        /// <param name="e">Event data that provides both the navigation parameter passed to
        /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested and
        /// a dictionary of state preserved by this page during an earlier
        /// session.  The state will be null the first time a page is visited.</param>
        private async void navigationHelper_LoadState(object sender, LoadStateEventArgs e)
        {
            // TODO: Create an appropriate data model for your problem domain to replace the sample data
            try
            {
                var video       = (Video)e.NavigationParameter;
                var channelVids = await ChannelDataSource.GetChannelAsync(video.ChannelId);

                this.defaultViewModel["Channel"] = new IncrementalVideos(video.ChannelId);
                this.DefaultViewModel["Item"]    = video;


                string videoId = video.Id;
                this.VideoId = videoId;
                var url = await YouTube.GetVideoUriAsync(videoId, Settings.VideoQuality);

                if (url != null)
                {
                    this.mediaPlayer.Source = url.Uri;
                    this.mediaPlayer.Pause();
                }
            }
            catch
            {
                pageTitle.Text = "Video Didn't Load";
            }

            if (VideoId != null)
            {
                SetPlayerSize();
            }

            Window.Current.SizeChanged += OnWindowSizeChanged;
        }
        public async Task Plus(string Url)
        {
            try
            {
                YouTube yt    = YouTube.Default;
                var     video = await yt.GetVideoAsync(Url);

                if (!Directory.Exists(Environment.CurrentDirectory + "\\musics\\"))
                {
                    Directory.CreateDirectory(Environment.CurrentDirectory + "\\musics\\");
                }

                File.WriteAllBytes(Environment.CurrentDirectory + "\\musics\\" + video.FullName.Replace(" ", ""), video.GetBytes());
                using (var engine = new Engine(@"C:\ffmpeg\bin\ffmpeg.exe"))
                {
                    var inputFile = new MediaFile {
                        Filename = Environment.CurrentDirectory + "\\musics\\" + video.FullName.Replace(" ", "")
                    };
                    var outputFile = new MediaFile {
                        Filename = Environment.CurrentDirectory + "\\musics\\" + video.FullName.Replace(" ", "").Replace(video.FileExtension, ".mp3")
                    };
                    engine.Convert(inputFile, outputFile);
                    File.Delete(Environment.CurrentDirectory + "\\musics\\" + video.FullName.Replace(" ", ""));
                    Console.WriteLine("음악 파일 다운로드 완료");
                }
                cts = new CancellationTokenSource();
                await SendAsync(audio, Environment.CurrentDirectory + "\\musics\\" + video.FullName.Replace(" ", "").Replace(video.FileExtension, ".mp3"), cts.Token);
            }
            catch (Exception Ex)
            {
                Console.WriteLine(Ex.StackTrace);
            }
        }
Beispiel #7
0
        protected void btnYtSave_Click(object sender, EventArgs e)
        {
            //string curlan = (Page as DotNetNuke.Framework.PageBase).PageCulture.Name;
            //int pluggid = Convert.ToInt32(((DotNetNuke.Framework.CDefault)this.Page).Title);
            //PluggContainer p = new PluggContainer(curlan, pluggid);

            //List<PluggComponent> comps = p.GetComponentList();

            //BaseHandler bh = new BaseHandler();


            //List<object> objToadd = new List<object>();
            BaseHandler bh = new BaseHandler();
            YouTube     yt = bh.GetYouTubeByComponentId(YouTubeId);

            if (yt == null)
            {
                yt = new YouTube();
            }
            try
            {
                yt.YouTubeTitle     = yttitle.Value;
                yt.YouTubeDuration  = Convert.ToInt32(ytduration.Value);
                yt.YouTubeCode      = ytYouTubeCode.Value;
                yt.YouTubeAuthor    = ytAuthor.Value;
                yt.YouTubeCreatedOn = Convert.ToDateTime(ytYouTubeCreatedOn.Value);
                yt.YouTubeComment   = ytYouTubeComment.Value;
                yt.PluggComponentId = YouTubeId;
            }
            catch
            {
            }

            bh.SaveYouTube(yt);
        }
Beispiel #8
0
        protected async override void OnNavigatedTo(NavigationEventArgs e)
        {
            try
            {
                if (NetworkInterface.GetIsNetworkAvailable())
                {
                    string videoId = String.Empty;
                    if (NavigationContext.QueryString.TryGetValue("videoId", out videoId))
                    {
                        //Get The Video Uri and set it as a player source
                        var url = await YouTube.GetVideoUriAsync(videoId, YouTubeQuality.Quality480P);

                        player.Source = url.Uri;
                    }
                }
                else
                {
                    MessageBox.Show("You're not connected to Internet!");
                    NavigationService.GoBack();
                }
            }
            catch (Exception ex) { MessageBox.Show(ex.Message); }

            base.OnNavigatedTo(e);
        }
        protected async override void OnNavigatedTo(NavigationEventArgs e)
        {
            try
            {
                if (NetworkInterface.GetIsNetworkAvailable())
                {
                    video = e.Parameter as Video;
                    var Url = await YouTube.GetVideoUriAsync(video.Id, YouTubeQuality.QualityLow);

                    Player.Source = Url.Uri;
                    Player.Play();
                }
                else
                {
                    MessageDialog message = new MessageDialog("You are not connected to Internet");
                    await message.ShowAsync();

                    this.Frame.GoBack();
                }
            }
            catch
            {
            }
            base.OnNavigatedTo(e);
        }
Beispiel #10
0
        public static void play_youtube_audio(string url)
        {
            YouTube youtube = YouTube.Default;
            Video   vid     = youtube.GetVideo(url);

            System.IO.File.WriteAllBytes(videoDownloadPath + vid.FullName, vid.GetBytes());

            var inputFile = new MediaFile {
                Filename = videoDownloadPath + vid.FullName
            };
            var outputFile = new MediaFile {
                Filename = $"{videoDownloadPath + vid.FullName}.mp3"
            };

            using (var engine = new Engine())
            {
                engine.GetMetadata(inputFile);

                engine.Convert(inputFile, outputFile);
            }
            InjectMicrophone(outputFile.Filename);

            //removes files when done
            if (System.IO.File.Exists(inputFile.Filename))
            {
                System.IO.File.Delete(inputFile.Filename);
            }
        }
Beispiel #11
0
        private async void OnPlayYouTubeVideo(object sender, RoutedEventArgs e)
        {
            try
            {
                Progress.IsActive = true;

                var uri = await YouTube.GetVideoUriAsync(YouTubeIdBox.Text, YouTubeQuality.Quality720P);

                if (uri != null)
                {
                    YouTubePlayer.Source = uri.Uri;
                    YouTubePlayer.Play();
                }
                else
                {
                    Debugger.Break(); // TODO: Show error message (no video uri found)
                    Progress.IsActive = false;
                }
            }
            catch (Exception exception)
            {
                // TODO: Add exception handling
                Debugger.Break();
                Progress.IsActive = false;
            }
        }
Beispiel #12
0
        public static void AddToCrawl(YouTubeLink link)
        {
            var path = "watch?v=" + link.Path;
            var yt   = new YouTube(path);

            Crawler.RegisterSite(yt);
        }
Beispiel #13
0
        public async Task <ActionResult> Create([Bind(Include = "Id,Name,Link,InstructorId,CourseId")] YouTube youTube)
        {
            if (ModelState.IsValid)
            {
                string second_string = string.Empty;
                if (youTube.Link.Contains(string.Format("https://www.youtube.com/watch?v=")))
                {
                    second_string = youTube.Link.Remove(youTube.Link.IndexOf(string.Format("https://www.youtube.com/watch?v=")), string.Format("https://www.youtube.com/watch?v=").Length);
                }
                else if (youTube.Link.Contains(string.Format("www.youtube.com/watch?v=")))
                {
                    second_string = youTube.Link.Remove(youTube.Link.IndexOf(string.Format("www.youtube.com/watch?v=")), string.Format("www.youtube.com/watch?v=").Length);
                }
                else
                {
                    ViewBag.Link = "The Link is not valid";
                }
                youTube.Link = second_string;
                db.YouTubes.Add(youTube);
                await db.SaveChangesAsync();

                return(RedirectToAction("Create", "YouTubes"));
            }


            ViewBag.CourseId     = new SelectList(db.Courses, "Id", "CourseCode", youTube.CourseId);
            ViewBag.InstructorId = new SelectList(db.Instructors, "id", "LastName", youTube.InstructorId);
            return(View(youTube));
        }
Beispiel #14
0
        /// <summary>
        /// Populates the page with content passed during navigation. Any saved state is also
        /// provided when recreating a page from a prior session.
        /// </summary>
        /// <param name="sender">
        /// The source of the event; typically <see cref="NavigationHelper"/>
        /// </param>
        /// <param name="e">Event data that provides both the navigation parameter passed to
        /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested and
        /// a dictionary of state preserved by this page during an earlier
        /// session. The state will be null the first time a page is visited.</param>
        private async void navigationHelper_LoadState(object sender, LoadStateEventArgs e)
        {
            try
            {
                if (NetworkInterface.GetIsNetworkAvailable())
                {
                    player.Visibility   = Visibility.Collapsed;
                    progress.Visibility = Visibility.Visible;

                    string       videoId = String.Empty;
                    YoutubeVideo video   = e.NavigationParameter as YoutubeVideo;
                    if (video != null && !video.Id.Equals(String.Empty))
                    {
                        //Get The Video Uri and set it as a player source
                        var url = await YouTube.GetVideoUriAsync(video.Id, YouTubeQuality.Quality1080P);

                        player.Source = url.Uri;
                    }

                    player.Visibility   = Visibility.Visible;
                    progress.Visibility = Visibility.Collapsed;
                }
                else
                {
                    MessageDialog message = new MessageDialog("İnternet bağlantınızda sorun var, lütfen internet bağlantınızı kontrol edin ve tekrar deneyin.");
                    await message.ShowAsync();

                    this.Frame.GoBack();
                }
            }
            catch { }
        }
Beispiel #15
0
        /// <summary>
        /// <summary>
        /// アイテムをタップしたとき
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void itemGridView_Tapped(object sender, TappedRoutedEventArgs e)
        {
            var item = (sender as GridView).SelectedItem;

            if (item == null)
            {
                return;
            }

            vm.Current = item as Video;
            MainPage.SelectItemIndex = (sender as GridView).SelectedIndex;

            var uri = new Uri(vm.Current.Url);

            if (vm.GoIE == true)
            {
                await Launcher.LaunchUriAsync(uri);
            }
            else
            {
                try
                {
                    var url = await YouTube.GetVideoUriAsync(vm.Current.VidoId, YouTubeQuality.Quality1080P);

                    this.media.AutoPlay = true;
                    this.media.Source   = url.Uri;
                    this.media.Play();
                }
                catch { }
            }
        }
Beispiel #16
0
        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            try
            {
                if (NetworkInterface.GetIsNetworkAvailable())
                {
                    player.Visibility   = Visibility.Collapsed;
                    progress.Visibility = Visibility.Visible;

                    string       videoId = String.Empty;
                    YoutubeVideo video   = e.Parameter as YoutubeVideo;
                    if (video != null && !video.Id.Equals(String.Empty))
                    {
                        //Get The Video Uri and set it as a player source
                        var url = await YouTube.GetVideoUriAsync(video.Id, YouTubeQuality.Quality480P);

                        player.Source = url.Uri;
                    }

                    player.Visibility   = Visibility.Visible;
                    progress.Visibility = Visibility.Collapsed;
                }
                else
                {
                    MessageDialog message = new MessageDialog("You're not connected to Internet!");
                    await message.ShowAsync();

                    this.Frame.GoBack();
                }
            }
            catch { }

            base.OnNavigatedTo(e);
        }
Beispiel #17
0
        public void Teste_AddOrUpdate()
        {
            // YoutubeEntity
            var video = new YouTube()
            {
                Id          = "a9__D53WsUs",
                Description = "Amazon Web Services (AWS) is the world’s most comprehensive and broadly adopted cloud platform, offering over 175 services such as compute, databases, and storage. Learn more: https://amzn.to/33lsybW",
                Title       = "What is AWS?",
                SearchedAt  = DateTime.Now,
                Type        = Domain.Enum.EYoutubeType.Video
            };

            var options = new DbContextOptionsBuilder <SegFyContext>().UseInMemoryDatabase().Options;

            var context = new SegFyContext(options);

            var repository = new YoutubeRepository(context);

            repository.AddOrUpdate(video);

            video.Type = Domain.Enum.EYoutubeType.Canal;

            repository.AddOrUpdate(video);

            var listIds = new List <string>()
            {
                "a9__D53WsUs"
            };

            var items = repository.GetAllByIds(listIds);

            // Assert
            Assert.AreEqual(1, items.Count());
        }
Beispiel #18
0
 public static void DecorateURLForYouTube(URL url, YouTube youTube)
 {
     url.Type = "youtube";
     url.Thumbnail = youTube.items[0].snippet.thumbnails["default"].url;
     url.Title = youTube.items[0].snippet.title;
     url.Description = youTube.items[0].snippet.description;
 }
Beispiel #19
0
    private void DownloadVideo(VideoData videoData, string path)
    {
        YouTube youtube = YouTube.Default;
        Video   video   = youtube.GetVideo(videoData.VideoUrl);

        File.WriteAllBytes(path, video.GetBytes());
    }
Beispiel #20
0
        /// <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;
            }
        }
        private void DownloadBtnClick(object sender, RoutedEventArgs e)
        {
            Regex YtRegex = new Regex(@"http(?:s?):\/\/(?:www\.)?youtu(?:be\.com\/watch\?v=|\.be\/)([\w\-_]*)(&(amp;)?‌​[\w\?‌​=]*)?");

            if (!YtRegex.IsMatch(YoutubeBrowser.Address))
            {
                MessageBox.Show("올바른 유튜브 영상 링크가 아닙니다.");
                return;
            }
            new Action(async() =>
            {
                YouTube yt = YouTube.Default;
                var items  = yt.GetAllVideos(YoutubeBrowser.Address).ToList();
                items      = items.OrderByDescending(item => item.AudioBitrate).ToList();
                foreach (var item in items)
                {
                    Debug.WriteLine(item.FullName + " - " + item.AudioBitrate);
                }
                File.WriteAllBytes(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\musics\" + items[0].FullName, await items[0].GetBytesAsync());
                var inputFile = new MediaFile {
                    Filename = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\musics\" + items[0].FullName
                };
                var outputFile = new MediaFile {
                    Filename = $"{Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\musics\" + items[0].FullName}.mp3"
                };

                using (var engine = new Engine())
                {
                    engine.GetMetadata(inputFile);
                    engine.Convert(inputFile, outputFile);
                    File.Delete(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\musics\" + items[0].FullName);
                    Refresh();
                }
            }).Invoke();
        }
        public List <YouTube> Search(string query)
        {
            List <YouTube> videoList = new List <YouTube>();

            String       url             = "https://www.googleapis.com/youtube/v3/search?q=" + query + "&part=id,snippet&maxResults=10&key=AIzaSyC979dpVpUH7DNQ8E9T5rpMJ72vaARKtzs&order=relevance";
            WebRequest   request         = WebRequest.Create(url);
            Stream       response_stream = request.GetResponse().GetResponseStream();
            StreamReader reader          = new StreamReader(response_stream);
            XmlDocument  resultXml       = (XmlDocument)JsonConvert.DeserializeXmlNode(reader.ReadToEnd(), "root");
            XmlNodeList  wordList        = resultXml.GetElementsByTagName("items");

            foreach (XmlNode wordNode in wordList)
            {
                YouTube video = new YouTube("", "", "", "", DateTime.Parse("12:15:12"));
                foreach (XmlNode ChildwordNode in wordNode.ChildNodes)
                {
                    if (ChildwordNode.Name == "id")
                    {
                        video.VideoId = ChildwordNode.ChildNodes[1].InnerText;
                    }
                    else if (ChildwordNode.Name == "snippet")
                    {
                        video.PublishedAt  = DateTime.Parse(ChildwordNode.ChildNodes[0].InnerText);
                        video.ThumbnailUrl = ChildwordNode.ChildNodes[4].ChildNodes[0].InnerText;
                        video.Title        = ChildwordNode.ChildNodes[2].InnerText;
                        video.Description  = ChildwordNode.ChildNodes[3].InnerText;
                    }
                }
                videoList.Add(video);
            }
            return(videoList);
        }
        public async void GetVideoYoutubeSource(string id, MediaElement media, TextBlock RequestUrl, TextBlock TypeVideo)
        {
            try
            {
                var videoSource = await YouTube.GetVideoUriAsync(id, YouTubeQuality.Quality720P);

                if (videoSource.Uri != null)
                {
                    media.Source    = videoSource.Uri;
                    RequestUrl.Text = videoSource.Uri.ToString();
                    TypeVideo.Text  = GetTypeYoutube(videoSource.Itag);
                    media.Play();
                }
                else
                {
                    var dialog = new MessageDialog("Couldn't get link from youtube");
                    await dialog.ShowAsync();
                }
            }
            catch (Exception)
            {
                var dialog = new MessageDialog("Could not play this video in your country!");
                await dialog.ShowAsync();
            }
        }
Beispiel #24
0
        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker backgroundWorker = (BackgroundWorker)sender;

            backgroundWorker.WorkerReportsProgress = true;

            YouTube youtube = new YouTube();
            Video   video   = youtube.GetVideo(urlBox.Text);

            string title = videoTitle.Text;//video.Title.Substring(0, video.Title.Length - 10);

            Byte[]     videoBytes = video.GetBytes();
            String     filePath   = @"C:\Users\Icefireburn1\Videos\";
            FileStream fs         = new FileStream(filePath + title + video.FileExtension, FileMode.Create, FileAccess.Write);

            for (int offset = 0; offset < videoBytes.Length; offset += 65536)
            {
                fs.Write(videoBytes, offset, Math.Min(65536, videoBytes.Length - offset));
                float percent = ((float)offset / (float)videoBytes.Length) * 100f;

                backgroundWorker.ReportProgress((int)Math.Round(percent, MidpointRounding.AwayFromZero));

                Thread.Sleep(1);
            }
            fs.Dispose(); //Frees file so it can be converted to FLAC
            if (convertMp3.Checked)
            {
                toFlacFormat(filePath + title + video.FileExtension, filePath + title + ".flac");
                System.IO.File.Delete(filePath + title + video.FileExtension);
            }
        }
Beispiel #25
0
 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 VideoDetailItem()
        {
            this.InitializeComponent();
            if (player != null && player.CurrentState.ToString() == "Playing")
            {
                player.Stop();
            }
            this.DataContextChanged += async(s, e) => {
                //Get The Video Uri and set it as a player source
                var Item = this.DataContext as Model.Video;
                if (Item != null && !Item.Id.Equals(String.Empty))
                {
                    try
                    {
                        var url = await YouTube.GetVideoUriAsync(Item.Id, YouTubeQuality.Quality480P);

                        player.Source = url.Uri; this.Bindings.Update();
                    }
                    catch (YouTubeUriNotFoundException _e)
                    {
                        Debug.WriteLine(_e.Message);
                        MessageDialog message = new MessageDialog("This video is not availible, please select other");
                        await message.ShowAsync();
                    }
                }
            };
        }
Beispiel #27
0
    public void ParseYtCodeTest()
    {
        var actual   = YouTube.ParseYtCode("https://www.youtube.com/watch?v=7JoitjrFLlU");
        var expected = "7JoitjrFLlU";

        Assert.Equal(actual, expected);
    }
Beispiel #28
0
 public TranscriptModel(
     YouTube yt,
     ILogger <TranscriptModel> logger)
 {
     _yt     = yt;
     _logger = logger;
 }
Beispiel #29
0
        /// <summary>
        /// Tries to get a youtube link from a post. If it fails
        /// it returns null.
        /// </summary>
        /// <param name="post"></param>
        /// <returns></returns>
        private static async Task <YouTubeUri> GetYouTubeVideoUrl(Post post)
        {
            if (String.IsNullOrWhiteSpace(post.Url))
            {
                return(null);
            }

            try
            {
                // Try to find the ID
                string youtubeVideoId = TryToGetYouTubeId(post);

                if (!String.IsNullOrWhiteSpace(youtubeVideoId))
                {
                    // We found it!
                    // #todo make this quality an option dependent on device!
                    return(await YouTube.GetVideoUriAsync(youtubeVideoId, YouTubeQuality.QualityMedium));
                }
            }
            catch (Exception)
            {
                App.BaconMan.TelemetryMan.ReportEvent("YoutubeString", "Failed to find youtube video");
            }

            return(null);
        }
 private void PhoneApplicationPage_BackKeyPress(object sender, System.ComponentModel.CancelEventArgs e)
 {
     if (YouTube.CancelPlay())
     {
         e.Cancel = true;
     }
 }
Beispiel #31
0
        public async Task When_loading_PQVlW4xbNuI_then_correct_uris_are_returned()
        {
            //// Arrange
            var youTubeId = "PQVlW4xbNuI";

            //// Act
            var allUris = await YouTube.GetUrisAsync(youTubeId);

            var uri720P = await YouTube.GetVideoUriAsync(youTubeId, YouTubeQuality.Quality480P, YouTubeQuality.Quality720P);

            var has480P = false;

            try
            {
                var uri480P = await YouTube.GetVideoUriAsync(youTubeId, YouTubeQuality.Quality480P, YouTubeQuality.Quality480P);

                has480P = true;
            }
            catch (Exception) { }

            //// Assert
            Assert.IsTrue(allUris.Any(u => u.VideoQuality == YouTubeQuality.Quality480P && !u.HasAudio));
            Assert.IsFalse(allUris.Any(u => u.VideoQuality == YouTubeQuality.Quality480P && u.HasAudio));
            Assert.IsFalse(has480P);   //// No 480p stream with audio available

            Assert.IsNotNull(uri720P); //// 720p stream with audio available
            Assert.AreEqual(YouTubeQuality.Quality720P, uri720P.VideoQuality);
        }
        public ActionResult Publish(YouTubeViewModel oModel)
        {
            var channels = oCore.iRepositories.ICategoryTypeRepository.Select(CTRecordStatus.Ative).OrderBy(model => model.name);
            ViewBag.Categories = channels;

            try
            {
                if (ModelState.IsValid)
                {
                    try
                    {
                        var yt = new YouTube()
                        {
                            videoId = oModel.videoId
                        };

                        if (yt.ResolveYoutube())
                        {
                            yt.ResolveYoutube(TopAppRouter.YoutubeDataSource, TopAppRouter.YoutubeApiKey, TopAppRouter.YoutubeApiResources, TopAppRouter.RemoteConectionTimeout);
                        }
                        else
                        {
                            yt.ExternalData = new YouTubeTemplate()
                            {
                                Id = yt.videoId
                            };

                            yt.videoId = Newtonsoft.Json.JsonConvert.SerializeObject(yt.ExternalData);
                            yt.ResolveYoutube(TopAppRouter.YoutubeDataSource, TopAppRouter.YoutubeApiKey, TopAppRouter.YoutubeApiResources, TopAppRouter.RemoteConectionTimeout);
                        }

                        if (yt.ResolveYoutube(TopAppRouter.YoutubeDataSource, TopAppRouter.YoutubeApiKey, TopAppRouter.YoutubeApiResources, TopAppRouter.RemoteConectionTimeout))
                        {
                            oModel.videoId = Newtonsoft.Json.JsonConvert.SerializeObject(yt.ExternalData);
                        }
                    }
                    catch
                    {

                    }

                    oModel.categoryId = (oModel.categoryId == null || oModel.categoryId == 0) ? 1 : oModel.categoryId;
                    var result = oCore.businessControllers.bcYouTube.Create(oUserProfile.oAccount, oModel.url, oModel.description, oModel.videoId, (long)oModel.categoryId);
                    if (result.Item2)
                    {
                        var chn = channels.SingleOrDefault(ch => ch.id == oModel.categoryId);
                        Country oCountry;
                        if (oUserProfile == null || oUserProfile.oAccount.Country1 == null)
                            oCountry = oCurrentUserLocation.Country;
                        else
                            oCountry = oUserProfile.oAccount.Country1;

                        return PartialView("Confirm", new Tuple<YouTube, CategoryType, System.Collections.Generic.IEnumerable<Post>>(result.Item1, chn, oCore.businessControllers.bcChannel.LatestPosts(oCountry, oUserProfile.oAccount, chn, PostType.YouTube, 6)));
                    }
                    else
                    {
                        ViewBag.ErrorMsg = Resources.Resources.YouTubeSharingError;
                    }
                }
            }
            catch (Exception ex)
            {
                ViewBag.ErrorMsg = Resources.Resources.YouTubeSharingError1;

                //Salva o erro no arquivo de log do sistema
                ex.Save(new StackTrace(ex, true), ErrorLog.system);
            }

            return PartialView("New", oModel);
        }
Beispiel #33
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        private Object GetSource(String query, String data)
        {
            try
            {
                if (String.IsNullOrEmpty(query))
                    return null;

                YouTube yTube = new YouTube();
                return yTube.SearchVideos(query, Int32.Parse(data.Split('|')[0]), Int32.Parse(data.Split('|')[1]));
            }
            catch { }

            return null;
        }