public GDataResultAggregator(string playlistURL)
    {
      YouTubeRequestSettings settings = new YouTubeRequestSettings(APPNAME, CLIENTID, DEVELKEY);
      YouTubeRequest request = new YouTubeRequest(settings);

      _videoFeed = request.Get<Video>(new Uri(playlistURL));
    }
Esempio n. 2
0
        private static IObservable<IReadOnlyList<ISong>> RealSearch(string searchTerm)
        {
            var query = new YouTubeQuery(YouTubeQuery.DefaultVideoUri)
            { 
                OrderBy = "relevance",
                Query = searchTerm,
                SafeSearch = YouTubeQuery.SafeSearchValues.None,
                NumberToRetrieve = RequestLimit
            };

            var settings = new YouTubeRequestSettings("Espera", ApiKey);
            var request = new YouTubeRequest(settings);

            return Observable.FromAsync(async () =>
            {
                Feed<Video> feed = await Task.Run(() => request.Get<Video>(query));
                List<Video> entries = await Task.Run(() => feed.Entries.ToList());

                return (from video in entries
                    let url = video.WatchPage.OriginalString.Replace("&feature=youtube_gdata_player", String.Empty).Replace("https://", "http://")
                    select new YoutubeSong()
                    {
                        Artist = video.Uploader, Title = video.Title, OriginalPath = url
                    }).ToList();
            })
            .Catch<IReadOnlyList<YoutubeSong>, Exception>(ex => Observable.Throw<IReadOnlyList<YoutubeSong>>(new Exception("YoutubeSongFinder search failed", ex)));
        }
Esempio n. 3
0
        public IEnumerable<VideoModel> Search(string searchText)
        {
            var modelList = new List<VideoModel>();
            var settings = new YouTubeRequestSettings("YouTunes", "AIzaSyCgNs6G_0w36g6dhAxxBL4nL7wD3C6jmOw");
            var request = new YouTubeRequest(settings);
            var query = new YouTubeQuery("https://gdata.youtube.com/feeds/api/videos") { Query = searchText };

            Feed<Video> feed = null;

            try
            {
                feed = request.Get<Video>(query);

                foreach (var video in feed.Entries)
                {
                    modelList.Add(new VideoModel() { VideoTitle = video.Title, VideoId = video.VideoId });
                }
            }
            catch (GDataRequestException gdre)
            {

            }

            return modelList;
        }
        protected void BBuscador(String track)
        {
            string spotUrl = String.Format("http://ws.spotify.com/search/1/track?q={0}", track);
            WebClient spotService = new WebClient();
            spotService.Encoding = Encoding.UTF8;
            spotService.DownloadStringCompleted += new DownloadStringCompletedEventHandler(SpotService_DownloadTracksCompleted);
            spotService.DownloadStringAsync(new Uri(spotUrl));

            YouTubeRequest request = new YouTubeRequest(settings);
            YouTubeQuery query = new YouTubeQuery(YouTubeQuery.DefaultVideoUri);
            query.OrderBy = "relevance";
            query.Query = track;
            query.SafeSearch = YouTubeQuery.SafeSearchValues.None;
            Feed<Video> videoFeed = request.Get<Video>(query);
            if (videoFeed.Entries.Count() > 0)
            {
                video1 = videoFeed.Entries.ElementAt(0);
                literal1.Text = String.Format(embed, video1.VideoId);
                if (videoFeed.Entries.Count() > 1)
                {
                    video1 = videoFeed.Entries.ElementAt(1);
                    literal1.Text += String.Format(embed, video1.VideoId);
                }
            }
        }
Esempio n. 5
0
        //
        // GET: /Candidates/Details/5
        public ViewResult Details(int id)
        {
            Candidate candidate = context.Candidates.Single(x => x.Id == id);

            YouTubeRequest req = new YouTubeRequest(new YouTubeRequestSettings("OpenPac", "AI39si5R4licFRGAWgvNI5G6ANPqGfcuyuTWW55nb7rE49bv5kIyMm7YbGpfvUpCX_5nNBJYXztGiUvhULoBQOoEUVQD8xI-Nw"));

            Uri u = new Uri(string.Format("https://gdata.youtube.com/feeds/api/users/{0}/uploads", candidate.YouTubeId));

            Feed<Video> videos = req.Get<Video>(u);

            List<YouTubeVideo> videoUrls = new List<YouTubeVideo>();

            foreach (Video v in videos.Entries)
            {
                videoUrls.Add(new YouTubeVideo
                {
                    VideoId = v.YouTubeEntry.VideoId,
                    Description = v.Description,
                    Title = v.Title,
                    Rating = v.YouTubeEntry.Rating == null ? 0.0 : v.YouTubeEntry.Rating.Average,
                    Updated = v.YouTubeEntry.Updated,
                    Duration = v.YouTubeEntry.Duration.IntegerValue,
                    YouTubeUrl = v.WatchPage.ToString()
                });
            }

            ViewBag.YouTubeVideos = videoUrls;

            return View(candidate);
        }
        private void AddVideo(YouTubeRequest request, string urlTemplate, string maxResultsKey, VideoList videoList)
        {
            int maxResults = ConfigService.GetConfig(maxResultsKey, 0);
            if (maxResults > 0)
            {
                string url = string.Format(urlTemplate, maxResults);
                Feed<Video> videos = request.Get<Video>(new Uri(url));

                YouTubeVideoParser parser = new YouTubeVideoParser();
                parser.Parse(videos, videoList);
            }
        }
Esempio n. 7
0
        private void Guncelle()
        {
            using (OleDbConnection conn = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=hesap.mdb"))
            {
                conn.Open();
                OleDbCommand komut = new OleDbCommand();
                komut.Connection = conn;
                komut.CommandText = "Select * from hesap"; // sorgu / komut cumlemi yazıyorum.
                komut.ExecuteNonQuery(); // insert , updateiçin gerekli satir sayisi donduruyoruz.
                OleDbDataReader dr = komut.ExecuteReader(); // datareader olusturup komut sorgulayıp veritabaninda okuma işlemini tanıtıyoruz
                while (dr.Read()) // datareader ile okuyoruz.
                {
                    string hadi = dr["hadi"].ToString();
                    string kadi = dr["kadi"].ToString();
                    string q;
                    using (WebClient asd = new WebClient())
                    {
                        asd.Encoding = Encoding.UTF8;
                        q = asd.DownloadString("http://gdata.youtube.com/feeds/api/users/" + kadi + "/uploads?v=2&alt=jsonc&max-results=0");
                    }
                    string[] adet1 = q.Split(new string[] { "totalItems\":" }, StringSplitOptions.None);
                    string[] adet2 = adet1[1].Split(',');
                    listView1.Items.Add(new ListViewItem(new string[] { hadi, "Adet: "+adet2[0] }));
                }
                dr.Close();
                komut.ExecuteNonQuery(); // insert , updateiçin gerekli satir sayisi donduruyoruz.
                dr = komut.ExecuteReader(); // datareader olusturup komut sorgulayıp veritabaninda okuma işlemini tanıtıyoruz
                while (dr.Read()) // datareader ile okuyoruz.
                {
                    string kadi = dr["hadi"].ToString(); // veritabanimdaki "kadi" alanımdaki veriyi alip kadi değişkenine atıyorum(yukarıda string olusturmustum)
                    string sifre = dr["hsifresi"].ToString(); // aynı durum söz konusu
                    string devkey = dr["devkey"].ToString();
                    Random a = new Random();
                    string id = a.Next(100000, 999999).ToString();
                    YouTubeRequestSettings settings = new YouTubeRequestSettings(id, devkey, kadi,sifre);
                    YouTubeRequest request = new YouTubeRequest(settings);

                    string feedUrl = "https://gdata.youtube.com/feeds/api/users/default/uploads";

                    Feed<Video> videoFeed = request.Get<Video>(new Uri(feedUrl));
                    foreach (Video entry in videoFeed.Entries)
                    {
                        string vid_thumb ="http://img.youtube.com/vi/"+entry.VideoId+"/0.jpg";
                        int izlenme = entry.ViewCount;
                        if(izlenme == -1)
                            izlenme = 0;
                        listView1.Items.Add(new ListViewItem(new string[] { kadi,entry.YouTubeEntry.Title.Text,izlenme.ToString()  }));
                    }
                }
            }
        }
Esempio n. 8
0
        public void PerformSearch(string searchVal)
        {
            YouTubeQuery query = new YouTubeQuery(YouTubeQuery.DefaultVideoUri);

            //order results by the number of views (most viewed first)
            query.OrderBy = "relevance";

            // perform querying with restricted content included in the results
            // query.SafeSearch could also be set to YouTubeQuery.SafeSearchValues.Moderate
            query.Query      = searchVal;
            query.SafeSearch = YouTubeQuery.SafeSearchValues.None;

            this.video_results = yt_request.Get <Video> (query);
        }
        // one simple intuitive public access point for the client (thus, FACADE)
        // the client no longer needs to know how to work with Youtube,
        // it just need to give the FACADE a string of the video id, and all the work with Youtube is done here!
        public string GetVideoKeyWords(string i_VideoID)
        {
            string keyWords = string.Empty;

            string       videoURI  = k_YouTubeAPIVideoAddress + i_VideoID;
            Feed <Video> videoFeed = m_YouTubeRequest.Get <Video>(new Uri(videoURI));

            foreach (Google.YouTube.Video video in videoFeed.Entries)
            {
                keyWords += "," + video.Keywords;
            }

            return(keyWords);
        }
Esempio n. 10
0
        private static IEnumerable <Video> GetVideos(YouTubeQuery q)
        {
            YouTubeRequest request = GetRequest();
            Feed <Video>   feed    = null;

            try
            {
                feed = request.Get <Video>(q);
            }
            catch (GDataRequestException gdre)
            {
                var response = (HttpWebResponse)gdre.Response;
            }
            return(feed != null ? feed.Entries : null);
        }
Esempio n. 11
0
        public static List <Video> Search(string text)
        {
            try
            {
                List <Video> vids  = new List <Video>();
                YouTubeQuery query = new YouTubeQuery(YouTubeQuery.DefaultVideoUri);

                query.OrderBy = "viewCount";
                query.Query   = text;
                Feed <Video> videofeed = yourequest.Get <Video>(query);

                foreach (Video entry in videofeed.Entries)
                {
                    vids.Add(entry);
                }


                return(vids);
            }
            catch
            {
                return(null);
            }
        }
        private void AddVideo(YouTubeRequest request, string maxResultsKey, string query, VideoList videoList)
        {
            int maxResults = ConfigService.GetConfig(maxResultsKey, 0);
            if (maxResults > 0)
            {
                YouTubeQuery youtubeQuery = new YouTubeQuery(YouTubeQuery.DefaultVideoUri);
                youtubeQuery.Query = "%22" + query +  "%22";
                youtubeQuery.SafeSearch = YouTubeQuery.SafeSearchValues.Strict;
                youtubeQuery.NumberToRetrieve = maxResults;
                Feed<Video> videos = request.Get<Video>(youtubeQuery);

                YouTubeVideoParser parser = new YouTubeVideoParser();
                parser.Parse(videos, videoList);
            }
        }
        internal List<KeyValuePair<string, List<Video>>> GetListOfSubscriptions(Settings i_settings)
        {
            List<KeyValuePair<string, List<Video>>> resObj = new  List<KeyValuePair<string, List<Video>>> ();

            YouTubeRequestSettings settings = new YouTubeRequestSettings(
                  i_settings.appName
                , i_settings.devKey
                , i_settings.username
                , i_settings.password);

            YouTubeRequest request = new YouTubeRequest(settings);
            Feed<Subscription> feedOfSubcr = request.GetSubscriptionsFeed(i_settings.userShort);

            string[] stringSeparators = new string[] { "Activity of:" };

            foreach (Subscription subItem in feedOfSubcr.Entries)
            {
                string keyStr = subItem.ToString().Split(stringSeparators, StringSplitOptions.None)[1].Trim();
                List<Video> listOfVideos = new List<Video>();

                string userName = subItem.UserName;
                string url = string.Format(i_settings.urlFormatter, userName);

                Feed<Video> videoFeed = request.Get<Video>(new Uri(url));

                int depth = 0;
                foreach (Video entry in videoFeed.Entries)
                {
                    //strBuilder.AppendLine("    " + entry.Title);
                    listOfVideos.Add(entry);
                    depth++;
                    if (depth >= i_settings.feedDepth)
                    {
                        break;
                    }
                }

                if (listOfVideos.Count > 0)
                {
                    KeyValuePair<string, List<Video>> subscriptionO = new KeyValuePair<string, List<Video>>(keyStr, listOfVideos);
                    resObj.Add(subscriptionO);
                }

            }

            return resObj;
        }
Esempio n. 14
0
        private static IObservable<IReadOnlyList<YoutubeSong>> RealSearch(string searchTerm)
        {
            var query = new YouTubeQuery(YouTubeQuery.DefaultVideoUri)
            {
                OrderBy = "relevance",
                Query = searchTerm,
                SafeSearch = YouTubeQuery.SafeSearchValues.None,
                NumberToRetrieve = RequestLimit
            };

            // NB: I have no idea where this API blocks exactly
            var settings = new YouTubeRequestSettings("Espera", ApiKey);
            var request = new YouTubeRequest(settings);

            return Observable.FromAsync(async () =>
            {
                Feed<Video> feed = await Task.Run(() => request.Get<Video>(query));
                List<Video> entries = await Task.Run(() => feed.Entries.ToList());

                var songs = new List<YoutubeSong>();

                foreach (Video video in entries)
                {
                    var duration = TimeSpan.FromSeconds(Int32.Parse(video.YouTubeEntry.Duration.Seconds));
                    string url = video.WatchPage.OriginalString
                        .Replace("&feature=youtube_gdata_player", String.Empty) // Unnecessary long url
                        .Replace("https://", "http://"); // Secure connections are not always easy to handle when streaming

                    var song = new YoutubeSong(url, duration)
                    {
                        Artist = video.Uploader,
                        Title = video.Title,
                        Description = video.Description,
                        Rating = video.RatingAverage >= 1 ? video.RatingAverage : (double?)null,
                        ThumbnailSource = new Uri(video.Thumbnails[0].Url),
                        Views = video.ViewCount
                    };

                    songs.Add(song);
                }

                return songs;
            })
                // The API gives no clue what can throw, wrap it all up
            .Catch<IReadOnlyList<YoutubeSong>, Exception>(ex => Observable.Throw<IReadOnlyList<YoutubeSong>>(new NetworkSongFinderException("YoutubeSongFinder search failed", ex)));
        }
Esempio n. 15
0
        private static IObservable <IReadOnlyList <YoutubeSong> > RealSearch(string searchTerm)
        {
            var query = new YouTubeQuery(YouTubeQuery.DefaultVideoUri)
            {
                OrderBy          = "relevance",
                Query            = searchTerm,
                SafeSearch       = YouTubeQuery.SafeSearchValues.None,
                NumberToRetrieve = RequestLimit
            };

            // NB: I have no idea where this API blocks exactly
            var settings = new YouTubeRequestSettings("Espera", ApiKey);
            var request  = new YouTubeRequest(settings);

            return(Observable.FromAsync(async() =>
            {
                Feed <Video> feed = await Task.Run(() => request.Get <Video>(query));
                List <Video> entries = await Task.Run(() => feed.Entries.ToList());

                var songs = new List <YoutubeSong>();

                foreach (Video video in entries)
                {
                    var duration = TimeSpan.FromSeconds(Int32.Parse(video.YouTubeEntry.Duration.Seconds));
                    string url = video.WatchPage.OriginalString
                                 .Replace("&feature=youtube_gdata_player", String.Empty) // Unnecessary long url
                                 .Replace("https://", "http://");                        // Secure connections are not always easy to handle when streaming

                    var song = new YoutubeSong(url, duration)
                    {
                        Artist = video.Uploader,
                        Title = video.Title,
                        Description = video.Description,
                        Rating = video.RatingAverage >= 1 ? video.RatingAverage : (double?)null,
                        ThumbnailSource = new Uri(video.Thumbnails[0].Url),
                        Views = video.ViewCount
                    };

                    songs.Add(song);
                }

                return songs;
            })
                   // The API gives no clue what can throw, wrap it all up
                   .Catch <IReadOnlyList <YoutubeSong>, Exception>(ex => Observable.Throw <IReadOnlyList <YoutubeSong> >(new NetworkSongFinderException("YoutubeSongFinder search failed", ex))));
        }
    protected void Page_Load(object sender, EventArgs e)
    {
        YouTubeRequestSettings yy      = new YouTubeRequestSettings("aa", "AIzaSyC6No029dfRA2FiZ5Hi3bRSAtWhSzDmRNE");
        YouTubeRequest         request = new YouTubeRequest(yy);
        YouTubeQuery           query   = new YouTubeQuery(YouTubeQuery.DefaultVideoUri + "?region=SG");

        //order results by the number of views (most viewed first)
        //  query.OrderBy = "viewCount";

        // search for puppies and include restricted content in the search results
        // query.SafeSearch could also be set to YouTubeQuery.SafeSearchValues.Moderate
        query.Query      = "People's Action Party";
        query.SafeSearch = YouTubeQuery.SafeSearchValues.None;

        Feed <Video> videoFeed = request.Get <Video>(query);

        printVideoFeed(videoFeed);
    }
Esempio n. 17
0
        public static Feed<Google.YouTube.Video> GetCurtVideos()
        {
            try {
                YouTubeRequestSettings settings = new YouTubeRequestSettings("eLocal", "AI39si6iCFZ_NutrvZe04i9_m7gFhgmPK1e7LF6-yHMAwB-GDO3vC3eD0R-5lberMQLdglNjH3IWUMe3tJXe9qrFe44n2jAUyg");
                YouTubeRequest req = new YouTubeRequest(settings);

                YouTubeQuery query = new YouTubeQuery(YouTubeQuery.DefaultVideoUri);
                query.Author = "curtmfg";
                query.Formats.Add(YouTubeQuery.VideoFormat.Embeddable);
                query.OrderBy = "viewCount";

                // We need to load the feed data for the CURTMfg Youtube Channel
                Feed<Google.YouTube.Video> video_feed = req.Get<Google.YouTube.Video>(query);
                return video_feed;
            } catch (Exception) {
                return null;
            }
        }
Esempio n. 18
0
        /// <summary>
        /// Returns a list of tracks from one of the YouTube feeds
        /// </summary>
        /// <param name="feed">The feed</param>
        /// <returns>An observable collection of TrackData that represents the most viewed YouTube tracks</returns>
        public static ObservableCollection <TrackData> TopFeed(string feed = "top_rated")
        {
            ObservableCollection <TrackData> tracks = new ObservableCollection <TrackData>();

            try
            {
                YouTubeRequest request = new YouTubeRequest(settings);

                int maxFeedItems = 50;

                string filter = SettingsManager.YouTubeFilter;
                if (String.IsNullOrWhiteSpace(filter) || filter == "None")
                {
                    filter = "";
                }
                else
                {
                    filter = String.Format("_{0}", filter);
                }

                int          i         = 1;
                Feed <Video> videoFeed = request.Get <Video>(new Uri(uriBase + "/feeds/api/standardfeeds/" + feed + filter + "?format=5"));
                foreach (Video entry in videoFeed.Entries)
                {
                    if (i++ > maxFeedItems)
                    {
                        break;
                    }
                    if (entry != null)
                    {
                        tracks.Add(CreateTrack(entry));
                    }
                }
            }
            catch (Exception e)
            {
                U.L(LogLevel.Warning, "YouTube", "Could not fetch top rated: " + e.Message);
                VerifyConnectivity();
            }

            TrackSource = tracks;
            return(tracks);
        }
Esempio n. 19
0
    void fetch()
    {
        YouTubeQuery   query   = new YouTubeQuery(YouTubeQuery.DefaultVideoUri);
        YouTubeRequest request = new YouTubeRequest(new YouTubeRequestSettings("", DeveloperKey));

        query.Query            = keyword;
        query.NumberToRetrieve = ChunkSize;
        query.StartIndex       = CurrentIndex;
        query.SafeSearch       = YouTubeQuery.SafeSearchValues.None;   // p**n

        // TODO: find out how to async this
        Feed <Video> videoFeed = request.Get <Video>(query);

        foreach (Video vid in videoFeed.Entries)
        {
            menu.AddToEnd(CreateItem(vid));
            CurrentIndex++;
        }
    }
Esempio n. 20
0
        public void GetStats()
        {
            YouTubeRequest request = GetRequest();

            Uri uri = new Uri("https://gdata.youtube.com/feeds/api/videos/" + this.videoID + "?v=2");

            try
            {
                Feed <Video> feed = request.Get <Video>(uri);
                foreach (Video entry in feed.Entries)
                {
                    this.CommentCount = entry.CommmentCount;
                    this.Views        = entry.ViewCount;
                    this.Title        = entry.Title;
                    this.Updated      = entry.Updated;
                    this.Link         = entry.WatchPage.ToString();
                }
            }
            catch
            { }
        }
Esempio n. 21
0
        private void youTubeSearch(string searchTerm)
        {
            YouTubeRequestSettings settings =
            new YouTubeRequestSettings("SmartHome", developerKeyV2);
            YouTubeRequest request = new YouTubeRequest(settings);

            YouTubeQuery query = new YouTubeQuery(YouTubeQuery.DefaultVideoUri);

            //For Categories
            //AtomCategory category1 = new AtomCategory("News", YouTubeNameTable.KeywordSchema);
            //query.Categories.Add(new QueryCategory(category1);

            //For Playlist
            // YouTubeQuery query = new YouTubeQuery(YouTubeQuery.BaseUserUri);
            // Feed<Google.YouTube.Playlist> userPlayList = request.GetPlaylistsFeed("*****@*****.**");
            // foreach (Google.YouTube.Playlist p in userPlayList.Entries)
            // {
            //     Feed<PlayListMember> list = request.GetPlaylist(p);
            //     foreach (Google.YouTube.Video entry in list.Entries)
              //      {
              //          System.Windows.MessageBox.Show(entry.Title);
              //      }
              //  }

            //order results by the number of views (most viewed first)
            query.OrderBy = "viewCount";
            query.NumberToRetrieve = 50;

            // search for puppies and include restricted content in the search results
            // query.SafeSearch could also be set to YouTubeQuery.SafeSearchValues.Moderate
            query.Query = searchTerm;
            query.SafeSearch = YouTubeQuery.SafeSearchValues.None;

            Feed<Google.YouTube.Video> videoFeed = request.Get<Google.YouTube.Video>(query);

            foreach (Google.YouTube.Video entry in videoFeed.Entries)
            {
            //System.Windows.MessageBox.Show(entry.Title);
            }
        }
Esempio n. 22
0
        public override List<Result> Search(string pKeyWords)
        {
            string youtubeApplicationName = ConfigurationManager.AppSettings["youtube-application-name"];
            string youtubeDeveloperKey = ConfigurationManager.AppSettings["youtube-developer-key"];

            if (string.IsNullOrWhiteSpace(youtubeApplicationName) || string.IsNullOrWhiteSpace(youtubeDeveloperKey))
                throw new Exception("App was unable to find Youtube credentials on the current settings file. Please add youtube-application-name and youtube-developer-key to the appSettings section.");

            YouTubeRequestSettings requestSettings = new YouTubeRequestSettings(youtubeApplicationName, youtubeDeveloperKey);
            requestSettings.AutoPaging = false;

            YouTubeRequest youtubeRequest = new YouTubeRequest(requestSettings);

            YouTubeQuery youtubeQuery = new YouTubeQuery(YouTubeQuery.DefaultVideoUri)
            {
                OrderBy = "viewCount",
                Query = pKeyWords,
                NumberToRetrieve = this.MaxResultSearch
            };

            Feed<Video> youtubeVideos = youtubeRequest.Get<Video>(youtubeQuery);

            List<Result> domainResults = new List<Result>();

            foreach (Video video in youtubeVideos.Entries)
            {
                domainResults.Add(
                    new Result()
                    {
                        CreatedDate = video.Updated,
                        Type = SourceType.YouTube,
                        Text = string.Format("{0} {1}", video.Description, video.Keywords),
                        Title = video.Title,
                        URL = video.WatchPage.OriginalString
                    }
                );
            }

            return domainResults;
        }
Esempio n. 23
0
    private void CreateVideoFeed(string s)
    {
        YouTubeRequestSettings settings = new YouTubeRequestSettings("most_viewed", YouTubeDeveloperKey);
        YouTubeRequest request = new YouTubeRequest(settings);

        //Link to the feed we wish to read from
        string feedUrl = String.Format("http://gdata.youtube.com/feeds/api/videos?q=" + s);

        dtVideoData.Columns.Add("Title");
       
        dtVideoData.Columns.Add("DateUploaded");


        dtVideoData.Columns.Add("VideoID");
        dtVideoData.Columns.Add("Duration");

        DataRow drVideoData;

        Feed<Video> videoFeed = request.Get<Video>(new Uri(feedUrl));

        //Iterate through each video entry and store details in DataTable
        foreach (Video videoEntry in videoFeed.Entries)
        {
            drVideoData = dtVideoData.NewRow();

            drVideoData["Title"] = videoEntry.Title;
           
            drVideoData["DateUploaded"] = videoEntry.Updated.ToShortDateString();


            drVideoData["VideoID"] = videoEntry.YouTubeEntry.VideoId;
            drVideoData["Duration"] = videoEntry.YouTubeEntry.Duration.Seconds.ToString();

            dtVideoData.Rows.Add(drVideoData);
        }

        RadGrid1.DataSource = dtVideoData;
        RadGrid1.DataBind();

    }
Esempio n. 24
0
        /*	private int GetYoutubeVideos(BikeModel bike, int howManyVideosToAdd = 900) { // 1000 is the max
         *              int pageSize = 50;
         *              int howManyAdded = 0;
         *              int loopNumber = 0;
         *              while (howManyAdded < howManyVideosToAdd) {
         *
         *                      Feed<Google.YouTube.Video> vids = GetVideos(bike.Title, (loopNumber * pageSize) + 1, pageSize);
         *
         *                      try {
         *                              if (vids.TotalResults <= 0) break;
         *                      } catch (Google.GData.Client.GDataRequestException) {
         *                              // ran out of videos - so break
         *                              break;
         *                      }
         *
         *                      // add video info to our database
         *                      howManyAdded += AddToDatabase(vids, bike.ID);
         *                      loopNumber++;
         *                      if (vids.TotalResults < loopNumber * pageSize) break;
         *              }
         *              return howManyAdded;
         *      }
         */

        private Feed <Google.YouTube.Video> GetVideos(string keyword)          //, int startIndex, int pageLength
        {
            YouTubeQuery query = new YouTubeQuery(YouTubeQuery.DefaultVideoUri);

            // tag search (lowercase - upper would mean category search)
            AtomCategory category1 = new AtomCategory(keyword, YouTubeNameTable.KeywordSchema);

            query.Categories.Add(new QueryCategory(category1));
            //query.Query = keyword; // normal 'everything' search
            query.NumberToRetrieve = 4;
            //query.StartIndex = startIndex;
            query.LR         = "en";
            query.Time       = YouTubeQuery.UploadTime.ThisWeek;
            query.SafeSearch = YouTubeQuery.SafeSearchValues.Moderate;
            query.OrderBy    = "rating";

            YouTubeRequestSettings      settings = new YouTubeRequestSettings("HowLong", Beweb.Util.GetSetting("YoutubeApi"));
            YouTubeRequest              request  = new YouTubeRequest(settings);
            Feed <Google.YouTube.Video> feed     = request.Get <Google.YouTube.Video>(query);

            return(feed);
        }
Esempio n. 25
0
    private void CreateVideoFeed(string s)
    {
        YouTubeRequestSettings settings = new YouTubeRequestSettings("most_viewed", YouTubeDeveloperKey);
        YouTubeRequest         request  = new YouTubeRequest(settings);

        //Link to the feed we wish to read from
        string feedUrl = String.Format("http://gdata.youtube.com/feeds/api/videos?q=" + s);

        dtVideoData.Columns.Add("Title");

        dtVideoData.Columns.Add("DateUploaded");


        dtVideoData.Columns.Add("VideoID");
        dtVideoData.Columns.Add("Duration");

        DataRow drVideoData;

        Feed <Video> videoFeed = request.Get <Video>(new Uri(feedUrl));

        //Iterate through each video entry and store details in DataTable
        foreach (Video videoEntry in videoFeed.Entries)
        {
            drVideoData = dtVideoData.NewRow();

            drVideoData["Title"] = videoEntry.Title;

            drVideoData["DateUploaded"] = videoEntry.Updated.ToShortDateString();


            drVideoData["VideoID"]  = videoEntry.YouTubeEntry.VideoId;
            drVideoData["Duration"] = videoEntry.YouTubeEntry.Duration.Seconds.ToString();

            dtVideoData.Rows.Add(drVideoData);
        }

        RadGrid1.DataSource = dtVideoData;
        RadGrid1.DataBind();
    }
Esempio n. 26
0
        /// <summary>
        /// Searches YouTube for tracks matching a certain query
        /// </summary>
        /// <param name="query">The query to search for</param>
        /// <returns>An observable collection of TrackData with all YouTube tracks that match query</returns>
        public static ObservableCollection <TrackData> Search(string query)
        {
            ObservableCollection <TrackData> tracks = new ObservableCollection <TrackData>();

            try
            {
                string filter = SettingsManager.YouTubeFilter;

                YouTubeQuery q = new YouTubeQuery(YouTubeQuery.DefaultVideoUri);
                q.OrderBy = "relevance";
                q.Query   = query;
                q.Formats.Add(YouTubeQuery.VideoFormat.Embeddable);
                q.NumberToRetrieve = 50;
                q.SafeSearch       = YouTubeQuery.SafeSearchValues.None;

                if (!String.IsNullOrWhiteSpace(filter) && filter != "None")
                {
                    AtomCategory category = new AtomCategory(filter, YouTubeNameTable.CategorySchema);
                    q.Categories.Add(new QueryCategory(category));
                }

                YouTubeRequest request = new YouTubeRequest(settings);

                Feed <Video> videoFeed = request.Get <Video>(q);
                foreach (Video entry in videoFeed.Entries)
                {
                    tracks.Add(YouTubeManager.CreateTrack(entry));
                }
            }
            catch (Exception exc)
            {
                U.L(LogLevel.Error, "YOUTUBE", "Error while performing search: " + exc.Message);
                VerifyConnectivity();
            }

            TrackSource = tracks;

            return(tracks);
        }
    public static string getVideos(string searchq)
    {
        YouTubeRequestSettings yy      = new YouTubeRequestSettings("unitysg", "AIzaSyAS1TLHGyfD6yP596kpmckOhUepSPmo8hM");
        YouTubeRequest         request = new YouTubeRequest(yy);
        YouTubeQuery           query   = new YouTubeQuery(YouTubeQuery.DefaultVideoUri + "?region=SG&v=2");

        //order results by the number of views (most viewed first)
        //   query.OrderBy = "viewCount";

        // search for puppies and include restricted content in the search results
        // query.SafeSearch could also be set to YouTubeQuery.SafeSearchValues.Moderate
        query.Query      = searchq.TrimEnd();
        query.SafeSearch = YouTubeQuery.SafeSearchValues.None;
        string[]     url                = new string[5];
        int          viewcount          = 0;
        int          totalrelatedvideos = 0;
        Feed <Video> videoFeed          = request.Get <Video>(query);

        printVideoFeed(videoFeed);
        int i = 0;

        foreach (Video entry in videoFeed.Entries)
        {
            if (i == 5)
            {
                break;
            }
            else
            {
                url[i]             = entry.WatchPage.ToString();
                viewcount          = int.Parse(entry.ViewCount.ToString());
                totalrelatedvideos = int.Parse(videoFeed.TotalResults.ToString());
            }
            i++;
        }

        return(new JavaScriptSerializer().Serialize(url) + "," + viewcount + "," + totalrelatedvideos);
    }
        public static WebFeed ReadFeedYT(string url, string tematica)
        {
            YouTubeRequestSettings settings = new YouTubeRequestSettings("IndignadoFramework", clave);
            YouTubeRequest         request  = new YouTubeRequest(settings);

            //YouTubeQuery query = new YouTubeQuery(url);
            YouTubeQuery query = new YouTubeQuery(YouTubeQuery.DefaultVideoUri);

            //order results by the number of views (most viewed first)
            query.OrderBy = "relevance";

            // search for puppies and include restricted content in the search results
            // query.SafeSearch could also be set to YouTubeQuery.SafeSearchValues.Moderate
            query.Query      = tematica;
            query.SafeSearch = YouTubeQuery.SafeSearchValues.None;

            Feed <Video> videoFeed = request.Get <Video>(query);

            WebFeed wf = new WebFeed
            {
                Title = "You Tube",
                Tipo  = WebFeed.TipoFuente.VIDEO,
                Nodes = new List <WebFeedNode>()
            };

            foreach (Video video in videoFeed.Entries)
            {
                wf.Nodes.Add(new WebFeedNode()
                {
                    Link         = video.WatchPage.ToString(),
                    ThumbnailUrl = video.Thumbnails.First().Url.ToString(),
                    Updated      = video.Updated.ToString(),
                    Title        = video.Title
                });
            }

            return(wf);
        }
Esempio n. 29
0
        public void CreatePlaylist()
        {
            Playlist playlistBlueprint = new Playlist();

            playlistBlueprint.Title   = _playlistName;
            playlistBlueprint.Summary = _playlistSummary;

            Playlist playlist;

            try
            {
                playlist = _request.Insert(new Uri("http://gdata.youtube.com/feeds/api/users/default/playlists"), playlistBlueprint);
            }
            catch (InvalidCredentialsException)
            {
                throw new InvalidLoginInfoException();
            }

            foreach (var query in _queryList)
            {
                YouTubeQuery ytQuery = new YouTubeQuery(YouTubeQuery.DefaultVideoUri);
                //ytQuery.OrderBy = "viewCount";
                ytQuery.Query      = query;
                ytQuery.SafeSearch = YouTubeQuery.SafeSearchValues.None;

                Feed <Video> results    = _request.Get <Video>(ytQuery);
                Video        firstVideo = results.Entries.ToList()[0];

                PlayListMember playlistMember = new PlayListMember();
                playlistMember.VideoId = firstVideo.VideoId;
                _request.AddToPlaylist(playlist, playlistMember);
            }

            int    idIndex = playlist.Id.IndexOf("playlist:");
            string id      = playlist.Id.Substring(idIndex + "playlist:".Length);

            PlaylistUrl = "https://www.youtube.com/playlist?list=" + id;
        }
Esempio n. 30
0
        public Form2(string username, string password)
        {
            InitializeComponent();
            Feed<Video> videoFeed = null;
            string devKey = "yt-dev-key";
            try
            {
                YouTubeRequestSettings settings =
                    new YouTubeRequestSettings("MassVideoEdit", devKey, username, password);
                request = new YouTubeRequest(settings);

                //getting all videos entry
                string uri = "http://gdata.youtube.com/feeds/api/users/default/uploads";
                videoFeed = request.Get<Video>(new Uri(uri));
                //Uri videoEntryUrl = new Uri(
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }

            createFormEntry(videoFeed);
        }
Esempio n. 31
0
        /// <summary>
        /// Starts the <see cref="YoutubeSongFinder"/>.
        /// </summary>
        public override void Start()
        {
            var query = new YouTubeQuery(YouTubeQuery.DefaultVideoUri)
            {
                OrderBy    = "relevance",
                Query      = searchString,
                SafeSearch = YouTubeQuery.SafeSearchValues.None
            };

            var          settings = new YouTubeRequestSettings("Espera", ApiKey);
            var          request  = new YouTubeRequest(settings);
            Feed <Video> feed     = request.Get <Video>(query);

            foreach (Video video in feed.Entries)
            {
                var    duration = TimeSpan.FromSeconds(Int32.Parse(video.YouTubeEntry.Duration.Seconds));
                string url      = video.WatchPage.OriginalString
                                  .Replace("&feature=youtube_gdata_player", String.Empty) /* Unnecessary long url */
                                  .Replace("https://", "http://");                        /* VLC doesn't like https */

                var song = new YoutubeSong(url, AudioType.Mp3, duration, CoreSettings.Default.StreamYoutube)
                {
                    Title           = video.Title,
                    Description     = video.Description,
                    Rating          = video.RatingAverage >= 1 ? video.RatingAverage : (double?)null,
                    ThumbnailSource = new Uri(video.Thumbnails[0].Url),
                    Views           = video.ViewCount
                };

                this.InternSongsFound.Add(song);

                this.OnSongFound(new SongEventArgs(song));
            }

            this.OnFinished(EventArgs.Empty);
        }
Esempio n. 32
0
        public static bool ParseChannel(string pChannelName, string pAppName, string pDevKey, int pLevel)
        {
            ///ReInitialize All Data
            ///
            channelName = "";
            channelId   = "";
            startIndex  = 1;
            recordCount = 0;
            updatedFlag = false;
            ///ReInitializing Done
            ///

            multithreadingChannelName = pChannelName;
            string channelFileName    = ConfigurationManager.AppSettings["channelsFileName"].ToString();
            string channelFileNameXML = ConfigurationManager.AppSettings["channelsFileNameXML"].ToString();
            //File.AppendAllText(pChannelName + "/" + log, "Entered Inside Parse Channel at : " + DateTime.Now + Environment.NewLine + Environment.NewLine);

            //This Request will give us 10 channels from index 1, which is searched by adding its name.

            //e.g.https://gdata.youtube.com/feeds/api/channels?q=" + pChannelName + "&start-index=1&max-results=10&v=2

            //q=<Channel Name>
            //start-index = <start Index of Search result> (by default 1st Index is '1')
            //max-result = <page size (containing number of channels)>
            //v = Not known yet. :S

            //e.g.https://gdata.youtube.com/feeds/api/channels?q=" + pChannelName + "&start-index=1&max-results=10&v=2
            string          channelUrl   = ConfigurationManager.AppSettings["ChannelSearchUrl"].ToString() + pChannelName + "&start-index=1&max-results=10&v=2";
            WebRequest      nameRequest  = WebRequest.Create(channelUrl);
            HttpWebResponse nameResponse = (HttpWebResponse)nameRequest.GetResponse();

            Stream       nameStream = nameResponse.GetResponseStream();
            StreamReader nameReader = new StreamReader(nameStream);

            string xmlData = nameReader.ReadToEnd();

            File.WriteAllText(pChannelName + "/" + channelFileNameXML, xmlData);

            XmlDocument doc = new XmlDocument();

            doc.Load(pChannelName + "/" + channelFileNameXML);
            XmlNamespaceManager namespaceManager = new XmlNamespaceManager(doc.NameTable);

            namespaceManager.AddNamespace("Atom", "http://www.w3.org/2005/Atom");

            XmlNodeList listResult = doc.SelectNodes(channelTitleXPath, namespaceManager);
            int         count      = 0;

            foreach (XmlNode node in listResult)
            {
                count++;
                if (node.FirstChild.InnerText.Equals(pChannelName, StringComparison.InvariantCultureIgnoreCase))
                {
                    break;
                }
            }
            XmlNodeList entryNode = doc.SelectSingleNode(channelAtomEntry + "[" + count + "]", namespaceManager).ChildNodes;

            foreach (XmlNode n in entryNode)
            {
                if (n.Name.Equals("title"))
                {
                    File.AppendAllText(pChannelName + "/" + channelFileName, "Channel Name: " + n.InnerText + "\r\n");
                }
                else if (n.Name.Equals("yt:channelStatistics"))
                {
                    File.AppendAllText(pChannelName + "/" + channelFileName, "Subscribers Count: " + n.Attributes["subscriberCount"].Value + "\r\n");
                    File.AppendAllText(pChannelName + "/" + channelFileName, "Views Count: " + n.Attributes["viewCount"].Value + "\r\n");
                }
                else if (n.Name.Equals("link"))
                {
                    if (n.Attributes["rel"].Value.Equals("alternate", StringComparison.CurrentCultureIgnoreCase))
                    {
                        File.AppendAllText(pChannelName + "/" + channelFileName, "Channel URL: " + n.Attributes["href"].Value + "\r\n");
                        channelUrlMain = n.Attributes["href"].Value;
                    }
                }
                else if (n.Name.Equals("id"))
                {
                    string   id         = n.InnerText;
                    string[] arrId      = n.InnerText.Split(new Char[] { ':' }, StringSplitOptions.RemoveEmptyEntries);
                    bool     indexFound = false;
                    for (int i = 0; i < arrId.Length; i++)
                    {
                        if (arrId[i].Equals("Channel", StringComparison.CurrentCultureIgnoreCase))
                        {
                            indexFound = true;
                            continue;
                        }
                        if (indexFound)
                        {
                            channelId = arrId[i];
                            break;
                        }
                    }
                }
            }
            //"AI39si7SUChDwy6-ms_bz7rY-mzkqWc9vouhT_XZfh_xery5HjOujHc4USzQJ-M6XeWPCmGtaMzBgs3QP5S4O3vFBHoxmCfIjA"
            YouTubeRequestSettings settings = new YouTubeRequestSettings(pAppName, pDevKey);
            YouTubeRequest         request  = new YouTubeRequest(settings);

            Uri          videoEntryUrl = new Uri("http://gdata.youtube.com/feeds/api/users/" + pChannelName);
            Feed <Video> videoFeed     = request.Get <Video>(videoEntryUrl);

            foreach (Entry e in videoFeed.Entries)
            {
                File.AppendAllText(pChannelName + "/" + channelFileName, "Channel Description: " + e.Summary + "\r\n");
                break;
            }

            Constant.tempFiles.Add(channelFileNameXML);
            //Constant.tempFiles.Add(pChannelName + "/" + log);
            Dictionary <string, VideoWrapper> videoDictionary = new Dictionary <string, VideoWrapper>();

            File.AppendAllText(pChannelName + "/" + channelFileName, "Video Lists \r\n");

            startIndex = 1;

            //File.AppendAllText(pChannelName + "/" + log, "\tEntering WriteVideoList at: " + DateTime.Now + Environment.NewLine + Environment.NewLine);

            WriteVideoLists(pChannelName, channelId, startIndex, videoDictionary, Enumeration.VideoRequestType.All);

            //File.AppendAllText(pChannelName + "/" + log, "\t\tTotal Dictionary Items : " + videoDictionary.Count + Environment.NewLine);
            //File.AppendAllText(pChannelName + "/" + log, "\r\n\tLeft WriteVideoList at: " + DateTime.Now + Environment.NewLine + Environment.NewLine);
            //File.AppendAllText(pChannelName + "/" + "Count.txt", "Count After complete Request Response (Expected 1000) : " + recordCount + "\r\n");

            //File.AppendAllText(pChannelName + "/" + log, "Leaving Parse Channel at : " + DateTime.Now);


            //ChannelVideo.parseVideo(videoDictionary, pChannelName);
            ///Done Crawling video description

            ///Crawl Comments
            ///
            ChannelComment.CrawlComments(videoDictionary, pChannelName);
            ///Done Crawling Comments
            ///
            ///Remove All Temporary Files here
            ///
            Common.RemoveTempFiles(Constant.tempFiles, pChannelName);
            ///Done
            ///

            //Commenting Temporarily on Paolo Request.. <04/19/2013>

            if (ConfigurationManager.AppSettings["BothLevelsFlag"].ToString().Equals("true", StringComparison.CurrentCultureIgnoreCase))
            {
                /////ReInitialize All Data
                /////
                channelName = "";
                channelId   = "";
                startIndex  = 1;
                recordCount = 0;
                updatedFlag = false;
                /////ReInitializing Done

                dictionary = new Dictionary <string, VideoCommentWrapper>();
                dictionary = GlobalConstants.commentDictionary;
                int testCount = 0;
                foreach (KeyValuePair <string, VideoCommentWrapper> pair in dictionary)
                {
                    GlobalConstants.commentDictionary = new Dictionary <string, VideoCommentWrapper>();
                    VideoCommentWrapper videoComment = pair.Value;
                    ParseChannelLevel2(videoComment, pAppName, pDevKey);
                    testCount++;
                    //if (testCount > 3)
                    //    break;
                }
            }
            return(true);
        }
Esempio n. 33
0
 public void GetMyPlaylist()
 {
     try
     {
         if (isLoggedIn == false) return;
         YouTubeRequestSettings settings = new YouTubeRequestSettings(APP_NAME, DEV_KEY, USERNAME, PASSWORD);
         YouTubeRequest reqeuest = new YouTubeRequest(settings);
         Feed<Playlist> pl_feeds = reqeuest.Get<Playlist>(new Uri("https://gdata.youtube.com/feeds/api/users/default/playlists?v=2"));
         List<List<VideoBase>> list = new List<List<VideoBase>>();
         List<string> playlistName = new List<string>();
         foreach (Playlist pl in pl_feeds.Entries)
         {
             playlistName.Add(pl.Title + " " + pl.CountHint + " video(s)");
             myPlaylistIDs.Add(new PlaylistId(pl.Id));
             Feed<PlayListMember> video_list = reqeuest.GetPlaylist(pl);
             Playlist certain_pl = new Playlist();
             certain_pl = pl;
             List<VideoBase> subVideo = new List<VideoBase>();
             foreach (Video video in video_list.Entries)
             {
                 subVideo.Add(ConvertToVideoBase(video));
             }
             list.Add(subVideo);
         }
         MyPlaylistsName = playlistName;
         MyPlaylistVideo = list;
         MyPlaylist = pl_feeds.Entries.ToList();
     }
     catch
     {
     }
 }
Esempio n. 34
0
        private void button10_Click(object sender, EventArgs e)
        {
            label38.Text = "Search Results:";
            try
            {
                string searchupd = "http://nicoding.com/api.php?app=ripleech&updtrend=search&term=" + textBox7.Text;
                HttpWebRequest searchreq = (HttpWebRequest)WebRequest.Create(searchupd);
                WebResponse searchres = searchreq.GetResponse();
                System.IO.StreamReader sr = new System.IO.StreamReader(searchres.GetResponseStream(), System.Text.Encoding.GetEncoding("windows-1252"));
                string pluginsavail = sr.ReadToEnd();
            }
            catch { }
            listView1.Items.Clear();
            YouTubeRequest request = new YouTubeRequest(settings);
            YouTubeQuery query = new YouTubeQuery(YouTubeQuery.DefaultVideoUri);

            //order results by the number of views (most viewed first)
            query.OrderBy = "relevance";

            // search for puppies and include restricted content in the search results
            // query.SafeSearch could also be set to YouTubeQuery.SafeSearchValues.Moderate
            query.Query = textBox7.Text;
            query.SafeSearch = YouTubeQuery.SafeSearchValues.None;

            Feed<Video> videoFeed = request.Get<Video>(query);
            printVideoFeed(videoFeed);
        }
        /////////////////////////////////////////////////////////////////////////////

        //////////////////////////////////////////////////////////////////////
        /// <summary>runs a test on the YouTube factory object</summary> 
        //////////////////////////////////////////////////////////////////////
        [Test] public void YouTubePagingTest()
        {
            Tracing.TraceMsg("Entering YouTubePagingTest");

            YouTubeRequestSettings settings = new YouTubeRequestSettings("NETUnittests", this.ytClient, this.ytDevKey, this.ytUser, this.ytPwd);
            settings.PageSize = 15;
            YouTubeRequest f = new YouTubeRequest(settings);

            Feed<Video> feed = f.GetStandardFeed(YouTubeQuery.MostPopular);
            Feed<Video> prev = f.Get<Video>(feed, FeedRequestType.Prev);
            Assert.IsTrue(prev == null, "the first chunk should not have a prev"); 

            Feed<Video> next = f.Get<Video>(feed, FeedRequestType.Next); 
            Assert.IsTrue(next != null, "the next chunk should exist"); 

            prev = f.Get<Video>(next, FeedRequestType.Prev);
            Assert.IsTrue(prev != null, "the prev chunk should exist now"); 

        }
Esempio n. 36
0
        //----------------------------------------------------------------------------------------------------------



        //----------------------------------------------------------------------------------------------------------
        // music player popup
        // this logic open player with playlists, songs, and other player related stuff
        public ActionResult MPL()
        {
            // 1.genral declarations
            //--------------------------------------------------------------------------------------------
            hypster_tv_DAL.playlistManagement playlistManager = new hypster_tv_DAL.playlistManagement();
            hypster_tv_DAL.memberManagement   memberManager   = new hypster_tv_DAL.memberManagement();
            //--------------------------------------------------------------------------------------------



            // 2.get requested media type (playlist, single song, default palylist)
            //--------------------------------------------------------------------------------------------
            string MEDIA_TYPE = "";

            if (Request.QueryString["media_type"] != null)
            {
                MEDIA_TYPE         = Request.QueryString["media_type"];
                ViewBag.MEDIA_TYPE = MEDIA_TYPE;
            }
            else
            {
                ViewBag.MEDIA_TYPE = "";
            }
            //--------------------------------------------------------------------------------------------



            //--------------------------------------------------------------------------------------------
            hypster_tv_DAL.Member member = new hypster_tv_DAL.Member();
            if (Request.QueryString["us_id"] != null)
            {
                ViewBag.UserID = Request.QueryString["us_id"];
                int us_id = 0;
                Int32.TryParse(Request.QueryString["us_id"], out us_id);
                if (us_id > 0)
                {
                    member = memberManager.getMemberByID(us_id);
                }
            }
            else
            {
                if (User.Identity.IsAuthenticated)
                {
                    member         = memberManager.getMemberByUserName(User.Identity.Name);
                    ViewBag.UserID = member.id;
                }
            }
            //--------------------------------------------------------------------------------------------



            // 3.parse media type
            //--------------------------------------------------------------------------------------------
            hypster.ViewModels.videoPlayerViewModel model = new ViewModels.videoPlayerViewModel();

            switch (MEDIA_TYPE)
            {
            //
            //display requested playlist
            case "playlist":
                int PLAYLIST_ID = 0;
                if (Request.QueryString["playlist_id"] != null)
                {
                    if (Int32.TryParse(Request.QueryString["playlist_id"], out PLAYLIST_ID) == false)
                    {
                        PLAYLIST_ID = 0;
                    }
                }

                playlistManager.AddPlaylistView(PLAYLIST_ID);

                if (ViewBag.UserID != null && PLAYLIST_ID != null)
                {
                    model.songs_list = playlistManager.GetSongsForPlayList(Int32.Parse(ViewBag.UserID.ToString()), (int)PLAYLIST_ID);
                }

                ViewBag.PlaylistID = PLAYLIST_ID;
                break;

            //
            //display single song
            case "":

                ViewBag.MEDIA_TYPE = "song";


                string SongGuid = "";
                if (Request.QueryString["song_guid"] != null)
                {
                    SongGuid         = Request.QueryString["song_guid"];
                    ViewBag.SongGuid = SongGuid.Replace("&", "amp;");
                }


                string SongTitle = "";
                if (Request.QueryString["song_title"] != null)
                {
                    SongTitle         = Request.QueryString["song_title"];
                    ViewBag.SongTitle = SongTitle.Replace("&", "amp;");
                }



                hypster_tv_DAL.PlaylistData_Song song = new hypster_tv_DAL.PlaylistData_Song();
                song.YoutubeId = SongGuid;
                song.Title     = SongTitle;

                model.songs_list.Add(song);



                if (model.songs_list.Count > 0)
                {
                    ViewBag.SongGuid = model.songs_list[0].YoutubeId;
                }
                break;



            //
            //display default palylist
            case "DEFPL":
                ViewBag.MEDIA_TYPE = "playlist";
                int PLAYLIST_ID_DEF = member.active_playlist;

                playlistManager.AddPlaylistView(member.active_playlist);

                if (ViewBag.UserID != null && PLAYLIST_ID_DEF != null)
                {
                    model.songs_list = playlistManager.GetSongsForPlayList(Int32.Parse(ViewBag.UserID.ToString()), (int)PLAYLIST_ID_DEF);
                }

                ViewBag.PlaylistID = member.active_playlist;
                ViewBag.UserID     = member.id;
                break;



            //
            //display default palylist
            case "Radio":
                ViewBag.MEDIA_TYPE = "radio";


                string Genre_str = "";
                if (Request.QueryString["Genre"] != null)
                {
                    Genre_str     = Request.QueryString["Genre"];
                    Genre_str     = Genre_str.Replace("&", "amp;");
                    ViewBag.Genre = Genre_str;
                }


                #region GET_RADIO_GENRE
                int G_User = 0;
                int G_Plst = 0;
                switch (Genre_str)
                {
                case "Dance":
                    G_User = Int32.Parse(System.Configuration.ConfigurationManager.AppSettings["Radio_User_Dance"]);
                    G_Plst = Int32.Parse(System.Configuration.ConfigurationManager.AppSettings["Radio_Plst_Dance"]);
                    playlistManager.AddPlaylistView(member.active_playlist);
                    model.songs_list = playlistManager.GetSongsForPlayList(G_User, G_Plst);
                    break;

                case "Jazz":
                    G_User = Int32.Parse(System.Configuration.ConfigurationManager.AppSettings["Radio_User_Jazz"]);
                    G_Plst = Int32.Parse(System.Configuration.ConfigurationManager.AppSettings["Radio_Plst_Jazz"]);
                    playlistManager.AddPlaylistView(member.active_playlist);
                    model.songs_list = playlistManager.GetSongsForPlayList(G_User, G_Plst);
                    break;

                case "Bluegrass":
                    G_User = Int32.Parse(System.Configuration.ConfigurationManager.AppSettings["Radio_User_Bluegrass"]);
                    G_Plst = Int32.Parse(System.Configuration.ConfigurationManager.AppSettings["Radio_Plst_Bluegrass"]);
                    playlistManager.AddPlaylistView(member.active_playlist);
                    model.songs_list = playlistManager.GetSongsForPlayList(G_User, G_Plst);
                    break;

                case "Classical":
                    G_User = Int32.Parse(System.Configuration.ConfigurationManager.AppSettings["Radio_User_Classical"]);
                    G_Plst = Int32.Parse(System.Configuration.ConfigurationManager.AppSettings["Radio_Plst_Classical"]);
                    playlistManager.AddPlaylistView(member.active_playlist);
                    model.songs_list = playlistManager.GetSongsForPlayList(G_User, G_Plst);
                    break;

                case "Reggae":
                    G_User = Int32.Parse(System.Configuration.ConfigurationManager.AppSettings["Radio_User_Reggae"]);
                    G_Plst = Int32.Parse(System.Configuration.ConfigurationManager.AppSettings["Radio_Plst_Reggae"]);
                    playlistManager.AddPlaylistView(member.active_playlist);
                    model.songs_list = playlistManager.GetSongsForPlayList(G_User, G_Plst);
                    break;

                case "Rap":
                    G_User = Int32.Parse(System.Configuration.ConfigurationManager.AppSettings["Radio_User_Rap"]);
                    G_Plst = Int32.Parse(System.Configuration.ConfigurationManager.AppSettings["Radio_Plst_Rap"]);
                    playlistManager.AddPlaylistView(member.active_playlist);
                    model.songs_list = playlistManager.GetSongsForPlayList(G_User, G_Plst);
                    break;

                case "Rock":
                    G_User = Int32.Parse(System.Configuration.ConfigurationManager.AppSettings["Radio_User_Rock"]);
                    G_Plst = Int32.Parse(System.Configuration.ConfigurationManager.AppSettings["Radio_Plst_Rock"]);
                    playlistManager.AddPlaylistView(member.active_playlist);
                    model.songs_list = playlistManager.GetSongsForPlayList(G_User, G_Plst);
                    break;

                case "Soundtrack":
                    G_User = Int32.Parse(System.Configuration.ConfigurationManager.AppSettings["Radio_User_Soundtrack"]);
                    G_Plst = Int32.Parse(System.Configuration.ConfigurationManager.AppSettings["Radio_Plst_Soundtrack"]);
                    playlistManager.AddPlaylistView(member.active_playlist);
                    model.songs_list = playlistManager.GetSongsForPlayList(G_User, G_Plst);
                    break;

                case "Blues":
                    G_User = Int32.Parse(System.Configuration.ConfigurationManager.AppSettings["Radio_User_Blues"]);
                    G_Plst = Int32.Parse(System.Configuration.ConfigurationManager.AppSettings["Radio_Plst_Blues"]);
                    playlistManager.AddPlaylistView(member.active_playlist);
                    model.songs_list = playlistManager.GetSongsForPlayList(G_User, G_Plst);
                    break;

                case "Pop":
                    G_User = Int32.Parse(System.Configuration.ConfigurationManager.AppSettings["Radio_User_Pop"]);
                    G_Plst = Int32.Parse(System.Configuration.ConfigurationManager.AppSettings["Radio_Plst_Pop"]);
                    playlistManager.AddPlaylistView(member.active_playlist);
                    model.songs_list = playlistManager.GetSongsForPlayList(G_User, G_Plst);
                    break;

                case "Country":
                    G_User = Int32.Parse(System.Configuration.ConfigurationManager.AppSettings["Radio_User_Country"]);
                    G_Plst = Int32.Parse(System.Configuration.ConfigurationManager.AppSettings["Radio_Plst_Country"]);
                    playlistManager.AddPlaylistView(member.active_playlist);
                    model.songs_list = playlistManager.GetSongsForPlayList(G_User, G_Plst);
                    break;



                case "Opera":
                    G_User = Int32.Parse(System.Configuration.ConfigurationManager.AppSettings["Radio_User_Opera"]);
                    G_Plst = Int32.Parse(System.Configuration.ConfigurationManager.AppSettings["Radio_Plst_Opera"]);
                    playlistManager.AddPlaylistView(member.active_playlist);
                    model.songs_list = playlistManager.GetSongsForPlayList(G_User, G_Plst);
                    break;

                case "Hip-Hop":
                    G_User = Int32.Parse(System.Configuration.ConfigurationManager.AppSettings["Radio_User_HipHop"]);
                    G_Plst = Int32.Parse(System.Configuration.ConfigurationManager.AppSettings["Radio_Plst_HipHop"]);
                    playlistManager.AddPlaylistView(member.active_playlist);
                    model.songs_list = playlistManager.GetSongsForPlayList(G_User, G_Plst);
                    break;

                case "Latin":
                    G_User = Int32.Parse(System.Configuration.ConfigurationManager.AppSettings["Radio_User_Latin"]);
                    G_Plst = Int32.Parse(System.Configuration.ConfigurationManager.AppSettings["Radio_Plst_Latin"]);
                    playlistManager.AddPlaylistView(member.active_playlist);
                    model.songs_list = playlistManager.GetSongsForPlayList(G_User, G_Plst);
                    break;

                case "Electronic":
                    G_User = Int32.Parse(System.Configuration.ConfigurationManager.AppSettings["Radio_User_Electronic"]);
                    G_Plst = Int32.Parse(System.Configuration.ConfigurationManager.AppSettings["Radio_Plst_Electronic"]);
                    playlistManager.AddPlaylistView(member.active_playlist);
                    model.songs_list = playlistManager.GetSongsForPlayList(G_User, G_Plst);
                    break;

                case "R&B":
                    G_User = Int32.Parse(System.Configuration.ConfigurationManager.AppSettings["Radio_User_RandB"]);
                    G_Plst = Int32.Parse(System.Configuration.ConfigurationManager.AppSettings["Radio_Plst_RandB"]);
                    playlistManager.AddPlaylistView(member.active_playlist);
                    model.songs_list = playlistManager.GetSongsForPlayList(G_User, G_Plst);
                    break;

                case "NewAge":
                    G_User = Int32.Parse(System.Configuration.ConfigurationManager.AppSettings["Radio_User_NewAge"]);
                    G_Plst = Int32.Parse(System.Configuration.ConfigurationManager.AppSettings["Radio_Plst_NewAge"]);
                    playlistManager.AddPlaylistView(member.active_playlist);
                    model.songs_list = playlistManager.GetSongsForPlayList(G_User, G_Plst);
                    break;

                case "Folk":
                    G_User = Int32.Parse(System.Configuration.ConfigurationManager.AppSettings["Radio_User_Folk"]);
                    G_Plst = Int32.Parse(System.Configuration.ConfigurationManager.AppSettings["Radio_Plst_Folk"]);
                    playlistManager.AddPlaylistView(member.active_playlist);
                    model.songs_list = playlistManager.GetSongsForPlayList(G_User, G_Plst);
                    break;

                case "J-Pop":
                    G_User = Int32.Parse(System.Configuration.ConfigurationManager.AppSettings["Radio_User_JPop"]);
                    G_Plst = Int32.Parse(System.Configuration.ConfigurationManager.AppSettings["Radio_Plst_JPop"]);
                    playlistManager.AddPlaylistView(member.active_playlist);
                    model.songs_list = playlistManager.GetSongsForPlayList(G_User, G_Plst);
                    break;

                case "Soul":
                    G_User = Int32.Parse(System.Configuration.ConfigurationManager.AppSettings["Radio_User_Soul"]);
                    G_Plst = Int32.Parse(System.Configuration.ConfigurationManager.AppSettings["Radio_Plst_Soul"]);
                    playlistManager.AddPlaylistView(member.active_playlist);
                    model.songs_list = playlistManager.GetSongsForPlayList(G_User, G_Plst);
                    break;

                case "Instrumental":
                    G_User = Int32.Parse(System.Configuration.ConfigurationManager.AppSettings["Radio_User_Instrumental"]);
                    G_Plst = Int32.Parse(System.Configuration.ConfigurationManager.AppSettings["Radio_Plst_Instrumental"]);
                    playlistManager.AddPlaylistView(member.active_playlist);
                    model.songs_list = playlistManager.GetSongsForPlayList(G_User, G_Plst);
                    break;

                case "Adult Contemporary":
                    G_User = Int32.Parse(System.Configuration.ConfigurationManager.AppSettings["Radio_User_AdultContemp"]);
                    G_Plst = Int32.Parse(System.Configuration.ConfigurationManager.AppSettings["Radio_Plst_AdultContemp"]);
                    playlistManager.AddPlaylistView(member.active_playlist);
                    model.songs_list = playlistManager.GetSongsForPlayList(G_User, G_Plst);
                    break;

                case "Alternative":
                    G_User = Int32.Parse(System.Configuration.ConfigurationManager.AppSettings["Radio_User_Alternative"]);
                    G_Plst = Int32.Parse(System.Configuration.ConfigurationManager.AppSettings["Radio_Plst_Alternative"]);
                    playlistManager.AddPlaylistView(member.active_playlist);
                    model.songs_list = playlistManager.GetSongsForPlayList(G_User, G_Plst);
                    break;



                default:         //if custom search started

                    string search_str = "";
                    if (Request.QueryString["search"] != null)
                    {
                        search_str     = Request.QueryString["search"];
                        ViewBag.search = search_str;
                    }
                    YouTubeRequestSettings settings = new YouTubeRequestSettings("hypster", "AI39si5TNjKgF6yiHwUhKbKwIui2JRphXG4hPXUBdlrNh4XMZLXu--lf66gVSPvks9PlWonEk2Qv9fwiadpNbiuh-9TifCNsqA");
                    YouTubeRequest         request  = new YouTubeRequest(settings);

                    int this_page = 1;
                    for (this_page = 1; this_page < 10; this_page++)
                    {
                        string       feedUrl   = "http://gdata.youtube.com/feeds/api/videos?q=" + Genre_str + "&category=Music&format=5&restriction=" + Request.ServerVariables["REMOTE_ADDR"] + "&safeSearch=none&start-index=" + ((this_page * 25) - 24) + "&orderby=viewCount";
                        Feed <Video> videoFeed = request.Get <Video>(new Uri(feedUrl));
                        foreach (Video item in videoFeed.Entries)
                        {
                            hypster_tv_DAL.PlaylistData_Song song_add1 = new hypster_tv_DAL.PlaylistData_Song();
                            song_add1.YoutubeId = item.VideoId;
                            song_add1.Title     = item.Title;
                            model.songs_list.Add(song_add1);
                        }
                    }
                    break;
                }
                #endregion

                ViewBag.UserID     = G_User;
                ViewBag.PlaylistID = G_Plst;



                break;



            default:
                break;
            }
            //--------------------------------------------------------------------------------------------



            //--------------------------------------------------------------------------------------------
            if (member.id != 0)
            {
                model.userPlaylists_list = playlistManager.GetUserPlaylists(member.id);
            }
            //--------------------------------------------------------------------------------------------



            return(View(model));
        }
Esempio n. 37
0
        public void GetVideos()
        {
            var settings = new YouTubeRequestSettings("API_YouTube",
                                                      "AI39si5WA7mB2YVdMdstabh0A-aG8w44dcuKIhyisCCJDP_PbVzFdVT8uBJ760wbgqmZqE33XMRUbblrS0c1dhq3nWc5POg2TQ");
            int counter = 0;

            while (channelNames[counter] != null)
            {
                int index    = 1;
                int pageSize = 50;

                string[] videoTitles   = new string[1000];
                int[]    videoDuration = new int[1000];
                string[] videoDate     = new string[1000];
                string[] videoURL      = new string[1000];

                string day;
                string month;
                string year;

                // Clear Videos
                int count = 0;
                while (videoTitles[count] != null)
                {
                    videoTitles[count]   = null;
                    videoDuration[count] = 0;
                    videoDate[count]     = null;
                    videoURL[count]      = null;
                    count++;
                }

                #region Get Data

                var request = new YouTubeRequest(settings);
                var query   = new YouTubeQuery("http://gdata.youtube.com/feeds/api/users/" + channelNames[counter] + "/uploads");

                query.OrderBy          = "published";
                query.StartIndex       = index;
                query.NumberToRetrieve = pageSize;

                Feed <Video> feed = null;

                try
                {
                    feed = request.Get <Video>(query);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error have occurred while retrieving data from YouTube: {0}", ex.Message);
                }

                if (feed != null && feed.Entries != null)
                {
                    count = 0;
                    try
                    {
                        int videoCounter = 0;

                        foreach (var entry in feed.Entries)
                        {
                            string url = "http://www.youtube.com/watch?v=" + entry.VideoId.ToString();

                            if (url == latestChannelVideos[counter])
                            {
                                break;
                            }
                            else
                            {
                                if (videoCounter == 0)
                                {
                                    AddToLatestVideo(channelNames[counter], url);
                                }
                            }

                            if (specifics[counter, 0] != null)
                            {
                                // Check specifications
                                int  tempCounter    = 0;
                                bool matchSpecifics = false;
                                while (specifics[counter, tempCounter] != null)
                                {
                                    if (SearchString(entry.Title.ToUpper(), specifics[counter, tempCounter].ToUpper()))
                                    {
                                        matchSpecifics = true;
                                    }

                                    tempCounter++;
                                }

                                if (matchSpecifics)
                                {
                                    videoTitles[count]   = entry.Title;
                                    videoDuration[count] = Convert.ToInt32(entry.YouTubeEntry.Duration.Seconds);
                                    videoDate[count]     = entry.Updated.Date.ToString().Substring(0, InString(entry.Updated.Date.ToString(), " 12:00:00 AM"));

                                    // Edit date
                                    day = videoDate[count].Substring(0, InString(videoDate[count], "/"));
                                    videoDate[count] = videoDate[count].Substring(InString(videoDate[count], "/") + 1,
                                                                                  videoDate[count].Length - (InString(videoDate[count], "/") + 1));
                                    month            = videoDate[count].Substring(0, InString(videoDate[count], "/"));
                                    videoDate[count] = videoDate[count].Substring(InString(videoDate[count], "/") + 1,
                                                                                  videoDate[count].Length - (InString(videoDate[count], "/") + 1));
                                    year             = videoDate[count];
                                    videoDate[count] = month + "/" + day + "/" + year;

                                    videoURL[count] = "http://www.youtube.com/watch?v=" + entry.VideoId.ToString();
                                    count++;
                                }
                            }
                            else
                            {
                                videoTitles[count]   = entry.Title;
                                videoDuration[count] = Convert.ToInt32(entry.YouTubeEntry.Duration.Seconds);
                                videoDate[count]     = entry.Updated.Date.ToString().Substring(0, InString(entry.Updated.Date.ToString(), " 12:00:00 AM"));

                                // Edit date
                                day = videoDate[count].Substring(0, InString(videoDate[count], "/"));
                                videoDate[count] = videoDate[count].Substring(InString(videoDate[count], "/") + 1,
                                                                              videoDate[count].Length - (InString(videoDate[count], "/") + 1));
                                month            = videoDate[count].Substring(0, InString(videoDate[count], "/"));
                                videoDate[count] = videoDate[count].Substring(InString(videoDate[count], "/") + 1,
                                                                              videoDate[count].Length - (InString(videoDate[count], "/") + 1));
                                year             = videoDate[count];
                                videoDate[count] = month + "/" + day + "/" + year;

                                videoURL[count] = "http://www.youtube.com/watch?v=" + entry.VideoId.ToString();
                                count++;
                            }

                            videoCounter++;
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("Error have occurred while retrieving data from YouTube: {0}", ex.Message);
                        break;
                    }

                    if (count < pageSize)
                    {
                        // Success!
                    }

                    index = index + count + 1;
                }
                else
                {
                    MessageBox.Show("Error have occurred while retrieving data from YouTube.");
                    break;
                }

                #endregion

                // Show Videos
                count = 0;
                while (videoTitles[count] != null)
                {
                    AddRow(videoTitles[count], channelNames[counter], videoDuration[count], videoDate[count], videoURL[count]);
                    count++;
                }

                counter++;
            }
        }
        public void ProcessRequest(HttpContext context)
        {
            int    userId = -1;
            string genre  = "";
            string page   = "";
            string search = "";


            if (context.Request.QueryString["genre"] != null)
            {
                genre = context.Request.QueryString["genre"];
            }

            if (context.Request.QueryString["page"] != null)
            {
                page = context.Request.QueryString["page"];
            }

            if (context.Request.QueryString["search"] != null)
            {
                search = context.Request.QueryString["search"];
            }
            //--------------------------------------------------------------------------------------------------------------------



            //--------------------------------------------------------------------------------------------------------------------
            //current radio logic
            //if search is (1) then straight go to youtube api if not
            //then try to find radio playlist accorging to genre
            //--------------------------------------------------------------------------------------------------------------------



            //--------------------------------------------------------------------------------------------------------------------
            YouTubeRequestSettings settings = new YouTubeRequestSettings("hypster", "AI39si5TNjKgF6yiHwUhKbKwIui2JRphXG4hPXUBdlrNh4XMZLXu--lf66gVSPvks9PlWonEk2Qv9fwiadpNbiuh-9TifCNsqA");
            YouTubeRequest         request  = new YouTubeRequest(settings);


            //string feedUrl = String.Format("http://gdata.youtube.com/feeds/api/videos?q={0}&category=Music&format=5&restriction={1}&safeSearch=none&start-index={2}&orderby=relevance", HttpUtility.UrlEncode(genre), context.Request.ServerVariables["REMOTE_ADDR"], 1);
            //string feedUrl = "http://gdata.youtube.com/feeds/api/videos/-/music/pop?v=2";
            //YouTubeQuery query = new YouTubeQuery();
            //request.GetVideoForActivity(
            //string feedUrl = "https://gdata.youtube.com/feeds/api/standardfeeds/most_popular";
            //string feedUrl = "http://gdata.youtube.com/feeds/api/videos/-/music/" + genre + "?v=2&start-index=1&orderby=viewCount";



            int this_page = 1;


            string       feedUrl   = "http://gdata.youtube.com/feeds/api/videos?q=" + genre + "&category=Music&format=5&restriction=" + context.Request.ServerVariables["REMOTE_ADDR"] + "&safeSearch=none&start-index=" + this_page + "&orderby=viewCount";
            Feed <Video> videoFeed = request.Get <Video>(new Uri(feedUrl));
            //--------------------------------------------------------------------------------------------------------------------



            //--------------------------------------------------------------------------------------------------------------------
            XElement   xml;
            XNamespace jwNS = "http://developer.longtailvideo.com/trac/wiki/FlashFormats";
            //--------------------------------------------------------------------------------------------------------------------



            //prepare playlist songs
            //--------------------------------------------------------------------------------------------------------------------
            ArrayList tracks_list_xml = new ArrayList();

            foreach (Video item in videoFeed.Entries)
            {
                XElement songs_xml = new XElement("track",
                                                  new XAttribute("id", "0"),
                                                  new XElement("youtubeId", item.VideoId ?? "null"),
                                                  new XElement("type", (item.VideoId == "") ? "mp3" : "youtube"),
                                                  new XElement("title", item.Title),
                                                  new XElement("link", ""),
                                                  new XElement("location", "")
                                                  );
                tracks_list_xml.Add(songs_xml);
            }
            //--------------------------------------------------------------------------------------------------------------------



            this_page += 1;
            string       feedUrl_2   = "http://gdata.youtube.com/feeds/api/videos?q=" + genre + "&category=Music&format=5&restriction=" + context.Request.ServerVariables["REMOTE_ADDR"] + "&safeSearch=none&start-index=" + (this_page * 25) + "&orderby=viewCount";
            Feed <Video> videoFeed_2 = request.Get <Video>(new Uri(feedUrl_2));

            //--------------------------------------------------------------------------------------------------------------------
            //prepare playlist songs
            //--------------------------------------------------------------------------------------------------------------------
            foreach (Video item in videoFeed_2.Entries)
            {
                XElement songs_xml = new XElement("track",
                                                  new XAttribute("id", "0"),
                                                  new XElement("youtubeId", item.VideoId ?? "null"),
                                                  new XElement("type", (item.VideoId == "") ? "mp3" : "youtube"),
                                                  new XElement("title", item.Title),
                                                  new XElement("link", ""),
                                                  new XElement("location", "")
                                                  );
                tracks_list_xml.Add(songs_xml);
            }
            //--------------------------------------------------------------------------------------------------------------------



            this_page += 3;
            string       feedUrl_3   = "http://gdata.youtube.com/feeds/api/videos?q=" + genre + "&category=Music&format=5&restriction=" + context.Request.ServerVariables["REMOTE_ADDR"] + "&safeSearch=none&start-index=" + (this_page * 25) + "&orderby=viewCount";
            Feed <Video> videoFeed_3 = request.Get <Video>(new Uri(feedUrl_3));

            //--------------------------------------------------------------------------------------------------------------------
            //prepare playlist songs
            //--------------------------------------------------------------------------------------------------------------------
            foreach (Video item in videoFeed_3.Entries)
            {
                XElement songs_xml = new XElement("track",
                                                  new XAttribute("id", "0"),
                                                  new XElement("youtubeId", item.VideoId ?? "null"),
                                                  new XElement("type", (item.VideoId == "") ? "mp3" : "youtube"),
                                                  new XElement("title", item.Title),
                                                  new XElement("link", ""),
                                                  new XElement("location", "")
                                                  );
                tracks_list_xml.Add(songs_xml);
            }
            //--------------------------------------------------------------------------------------------------------------------



            //populate playlist
            //--------------------------------------------------------------------------------------------------------------------
            xml = new XElement("playlist", new XAttribute(XNamespace.Xmlns + "jwplayer", jwNS.NamespaceName),
                               new XElement("tracklist", tracks_list_xml),
                               new XElement("data",
                                            new XElement("title", " - Hypster Radio"),
                                            new XElement("username", "N/A"),
                                            new XElement("photo", "N/A"),
                                            new XElement("truename", "N/A"),
                                            new XElement("gender", "N/A"),
                                            new XElement("country", "N/A"),
                                            new XElement("city", "N/A"),
                                            new XElement("introduce", "N/A")));
            //--------------------------------------------------------------------------------------------------------------------



            //--------------------------------------------------------------------------------------------------------------------
            context.Response.ContentType = "text/xml";
            context.Response.Write(xml.ToString(SaveOptions.DisableFormatting));
            //--------------------------------------------------------------------------------------------------------------------
        }
Esempio n. 39
0
        public static void ParseChannelLevel2(VideoCommentWrapper commentWrapper, string pAppName, string pDevKey)
        {
            try
            {
                string channelName = commentWrapper.userName;//displayName is not working in 1 case.. Got Luv2bbeautiful ., contains space + .
                string userId = commentWrapper.userName;
                string channelCleanedName = Common.CleanFileName(channelName);
                if (!Directory.Exists(channelCleanedName))
                {
                    Directory.CreateDirectory(channelCleanedName);
                }
                else
                {
                    Directory.Delete(channelCleanedName, true);
                    Directory.CreateDirectory(channelCleanedName);
                }

                //Search for Channel...
                // If Channel doesn't exit Search for following things
                //1. Favourties, 2. Uploaded , 3. Playlist
                multithreadingChannelName = channelCleanedName;
                string channelFileName = ConfigurationManager.AppSettings["channelsFileName"].ToString();
                string channelFileNameXML = ConfigurationManager.AppSettings["channelsFileNameXML"].ToString();
                //File.AppendAllText(channelCleanedName + "/" + log, "Entered Inside Parse Channel at : " + DateTime.Now + Environment.NewLine + Environment.NewLine);

                string videoUrl = "https://gdata.youtube.com/feeds/api/users/" + channelName + "/uploads?&start-index=" + startIndex;
                HttpWebRequest nameRequest1 = (HttpWebRequest)WebRequest.Create(videoUrl);
                nameRequest1.KeepAlive = false;
                nameRequest1.ProtocolVersion = HttpVersion.Version10;
                HttpWebResponse nameResponse1 = (HttpWebResponse)nameRequest1.GetResponse();

                Stream nameStream1 = nameResponse1.GetResponseStream();
                StreamReader nameReader1 = new StreamReader(nameStream1);

                string xmlData1 = nameReader1.ReadToEnd();
                File.WriteAllText(channelCleanedName + "/" + channelFileNameXML, xmlData1);
                //Constant.tempFiles.Add(channelFileNameXML);
                XmlDocument doc1 = new XmlDocument();
                doc1.Load(channelCleanedName + "/" + channelFileNameXML);
                XmlNamespaceManager namespaceManager2 = new XmlNamespaceManager(doc1.NameTable);
                namespaceManager2.AddNamespace("Atom", "http://www.w3.org/2005/Atom");
                //XmlNodeList listResult1 = doc1.SelectNodes(channelAtomEntry, namespaceManager2);

                ////Getting total Record
                XmlNamespaceManager namespaceManager3 = new XmlNamespaceManager(doc1.NameTable);
                namespaceManager3.AddNamespace("openSearch", "http://a9.com/-/spec/opensearchrss/1.0/");

                XmlNode nodeTotal = doc1.SelectSingleNode("//openSearch:totalResults", namespaceManager3);
                int total = Int32.Parse(nodeTotal.InnerText);
                if (total != 0)
                {
                    string channelUrl = ConfigurationManager.AppSettings["ChannelSearchUrl"].ToString() + channelName + "&start-index=1&max-results=10&v=2";
                    WebRequest nameRequest = WebRequest.Create(channelUrl);
                    HttpWebResponse nameResponse = (HttpWebResponse)nameRequest.GetResponse();
                    Stream nameStream = nameResponse.GetResponseStream();
                    StreamReader nameReader = new StreamReader(nameStream);

                    string xmlData = nameReader.ReadToEnd();

                    File.WriteAllText(channelCleanedName + "/" + channelFileNameXML, xmlData);

                    XmlDocument doc = new XmlDocument();
                    doc.Load(channelCleanedName + "/" + channelFileNameXML);

                    XmlNamespaceManager namespaceManager1 = new XmlNamespaceManager(doc.NameTable);
                    namespaceManager1.AddNamespace("openSearch", "http://a9.com/-/spec/opensearch/1.1/");
                    XmlNode node1 = doc.SelectSingleNode("//openSearch:totalResults", namespaceManager1);

                    //This means Channel Exists
                    XmlNamespaceManager namespaceManager = new XmlNamespaceManager(doc.NameTable);
                    namespaceManager.AddNamespace("Atom", "http://www.w3.org/2005/Atom");

                    XmlNodeList listResult = doc.SelectNodes(channelTitleXPath, namespaceManager);
                    int count = 0;
                    foreach (XmlNode node in listResult)
                    {
                        count++;
                        if (node.FirstChild.InnerText.Equals(channelName, StringComparison.InvariantCultureIgnoreCase))
                        {
                            break;
                        }
                    }
                    XmlNodeList entryNode = doc.SelectSingleNode(channelAtomEntry + "[" + count + "]", namespaceManager).ChildNodes;
                    foreach (XmlNode n in entryNode)
                    {
                        if (n.Name.Equals("title"))
                        {
                            File.AppendAllText(channelCleanedName + "/" + channelFileName, "Channel Name: " + n.InnerText + "\r\n");
                        }
                        else if (n.Name.Equals("yt:channelStatistics"))
                        {
                            File.AppendAllText(channelCleanedName + "/" + channelFileName, "Subscribers Count: " + n.Attributes["subscriberCount"].Value + "\r\n");
                            File.AppendAllText(channelCleanedName + "/" + channelFileName, "Views Count: " + n.Attributes["viewCount"].Value + "\r\n");
                        }
                        //else if (n.Name.Equals("summary"))
                        //{
                        //    File.AppendAllText(pChannelName + "/" + channelFileName, "Channel Description: " + n.InnerText + "\r\n");
                        //}
                        else if (n.Name.Equals("link"))
                        {
                            if (n.Attributes["rel"].Value.Equals("alternate", StringComparison.CurrentCultureIgnoreCase))
                            {
                                File.AppendAllText(channelCleanedName + "/" + channelFileName, "Channel URL: " + n.Attributes["href"].Value + "\r\n");
                                channelUrlMain = n.Attributes["href"].Value;
                            }
                        }
                        else if (n.Name.Equals("id"))
                        {
                            string id = n.InnerText;
                            string[] arrId = n.InnerText.Split(new Char[] { ':' }, StringSplitOptions.RemoveEmptyEntries);
                            bool indexFound = false;
                            for (int i = 0; i < arrId.Length; i++)
                            {
                                if (arrId[i].Equals("Channel", StringComparison.CurrentCultureIgnoreCase))
                                {
                                    indexFound = true;
                                    continue;
                                }
                                if (indexFound)
                                {
                                    channelId = arrId[i];
                                    break;
                                }
                            }
                        }
                    }
                    //"AI39si7SUChDwy6-ms_bz7rY-mzkqWc9vouhT_XZfh_xery5HjOujHc4USzQJ-M6XeWPCmGtaMzBgs3QP5S4O3vFBHoxmCfIjA"
                    YouTubeRequestSettings settings = new YouTubeRequestSettings(pAppName, pDevKey);
                    YouTubeRequest request = new YouTubeRequest(settings);

                    Uri videoEntryUrl = new Uri("http://gdata.youtube.com/feeds/api/users/" + channelName);
                    Feed<Video> videoFeed = request.Get<Video>(videoEntryUrl);
                    foreach (Entry e in videoFeed.Entries)
                    {
                        File.AppendAllText(channelCleanedName + "/" + channelFileName, "Channel Description: " + e.Summary + "\r\n");
                        break;
                    }

                    Constant.tempFiles.Add(channelFileNameXML);
                    Dictionary<string, VideoWrapper> videoDictionary = new Dictionary<string, VideoWrapper>();

                    File.AppendAllText(channelCleanedName + "/" + channelFileName, "Video Lists \r\n");

                    startIndex = 1;

                    //File.AppendAllText(channelCleanedName + "/" + log, "\tEntering WriteVideoList at: " + DateTime.Now + Environment.NewLine + Environment.NewLine);

                    WriteVideoLists(channelName, channelId, startIndex, videoDictionary, Enumeration.VideoRequestType.All);

                    //File.AppendAllText(channelCleanedName + "/" + log, "\t\tTotal Dictionary Items : " + videoDictionary.Count + Environment.NewLine);
                    //File.AppendAllText(channelCleanedName + "/" + log, "\r\n\tLeft WriteVideoList at: " + DateTime.Now + Environment.NewLine + Environment.NewLine);
                    //File.AppendAllText(channelCleanedName + "/" + "Count.txt", "Count After complete Request Response (Expected 1000) : " + recordCount + "\r\n");

                    //File.AppendAllText(channelCleanedName + "/" + log, "Leaving Parse Channel at : " + DateTime.Now);

                    ///Crawl Comments
                    ///
                    ChannelComment.CrawlComments(videoDictionary, channelName);
                    ///Done Crawling Comments
                    //ChannelVideo.parseVideo(videoDictionary, channelName);
                    ///Done Crawling video description

                    ///Remove All Temporary Files here
                    ///
                    Common.RemoveTempFiles(Constant.tempFiles, channelName);
                    ///Done
                    ///

                    ///ReInitialize All Data
                    ///
                    //channelName = "";
                    channelId = "";
                    startIndex = 1;
                    recordCount = 0;
                    updatedFlag = false;
                    ///ReInitializing Done
                }
                //Extract Playlists
                ExtractFromPlaylist(channelName, userId, 1);

                ///ReInitialize All Data
                ///
                //channelName = "";
                channelId = "";
                startIndex = 1;
                recordCount = 0;
                updatedFlag = false;
                ///ReInitializing Done

                //Extract Favourites

                ExtractFromUserFavourite(channelName, userId, 1);
            }
            catch (Exception ex)
            {
                Thread.Sleep(10000);
                ParseChannelLevel2(commentWrapper, pAppName, pDevKey);
            }
        }
Esempio n. 40
0
 public List<VideoBase> GetRecommendedVideos()
 {
     List<VideoBase> list = new List<VideoBase>();
     try
     {
         if (isLoggedIn == false) return null;
         YouTubeRequestSettings settings = new YouTubeRequestSettings(APP_NAME, DEV_KEY, USERNAME, PASSWORD);
         YouTubeRequest reqeuest = new YouTubeRequest(settings);
         Feed<Video> pl_feeds = reqeuest.Get<Video>(new Uri("https://gdata.youtube.com/feeds/api/users/default/recommendations?v=2"));
         foreach (Video video in pl_feeds.Entries)
         {
             list.Add(ConvertToVideoBase(video));
         }
     }
     catch
     {
     }
     return list;
 }
Esempio n. 41
0
        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Page_Load runs when the control is loaded
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <history>
        /// </history>
        /// -----------------------------------------------------------------------------
        protected void Page_Load(System.Object sender, System.EventArgs e)
        {
            base.Page_Load(sender, e);

            try
            {
                ServiceReference service = new ServiceReference("~/DesktopModules/ATI_Base/resources/services/StreamService.asmx");
                service.InlineScript = true;
                ScriptManager.GetCurrent(Page).Services.Add(service);
                imgAd.Src         = ResolveUrl("/portals/0/images/adTastyPaleo.jpg");
                imgCheck.ImageUrl = ResolveUrl("~/DesktopModules/ATI_Base/resources/images/iCheck.png");

                if (!Page.IsPostBack && !Page.IsCallback)
                {
                    baseUrl = ResolveUrl("~/");
                    long wId = 0;
                    if (HttpContext.Current.Items["w"] != null)
                    {
                        wId = Convert.ToInt64(HttpContext.Current.Items["w"]);
                    }
                    else if (Request["w"] != null)
                    {
                        wId = Convert.ToInt64(Request["w"]);
                    }

                    // Are we viewing a specific workout ?
                    if (wId > 0)
                    {
                        divMainLinks.Visible = true;

                        atiProfile.Visible     = false;
                        hiddenWorkoutKey.Value = "" + wId;
                        aqufitEntities entities = new aqufitEntities();
                        WOD            wod      = entities.WODs.Include("WODType").Include("WODSets").Include("WODSets.WODExercises").Include("WODSets.WODExercises.Exercise").FirstOrDefault(w => w.Id == wId);
                        if (base.UserSettings != null && wod.Standard == 0)
                        {
                            User2WODFav fav = entities.User2WODFav.FirstOrDefault(mr => mr.WOD.Id == wod.Id && mr.UserSetting.Id == UserSettings.Id);
                            bAddWorkout.Visible    = fav == null;
                            bRemoveWorkout.Visible = fav != null;
                        }
                        lWorkoutTitle.Text = wod.Name;

                        //  lWorkoutDescription.Text = wod.Description;

                        // constructWorkoutInfo(wod);
                        lWorkoutInfo.Text = wod.Description;
                        if (wod.Standard > 0)
                        {
                            imgCrossFit.Visible   = true;
                            imgCrossFit.Src       = ResolveUrl("~/DesktopModules/ATI_Base/resources/images/xfit.png");
                            atiProfileImg.Visible = false;
                        }
                        else
                        {
                            atiProfileImg.Settings = entities.UserSettings.FirstOrDefault(us => us.Id == wod.UserSettingsKey);
                        }
                        atiWorkoutPanel.Visible  = false;
                        atiWorkoutViewer.Visible = true;

                        // Get the leader board
                        IQueryable <Workout> stream = entities.UserStreamSet.OfType <Workout>().Where(w => w.WOD.Id == wId);
                        long typeId = entities.WODs.Where(w => w.Id == wId).Select(w => w.WODType.Id).FirstOrDefault();
                        switch (typeId)
                        {
                        case (long)Affine.Utils.WorkoutUtil.WodType.AMRAP:
                        case (long)Affine.Utils.WorkoutUtil.WodType.SCORE:
                            atiScoreRangePanel.Visible = true;
                            stream = stream.OrderByDescending(w => w.Score);
                            break;

                        case (long)Affine.Utils.WorkoutUtil.WodType.MAX_WEIGHT:
                            atiMaxRangePanel.Visible = true;
                            atiMaxWeightUnitsFirst.UnitList.Add(Affine.Utils.UnitsUtil.MeasureUnit.UNIT_LBS);
                            atiMaxWeightUnitsFirst.UnitList.Add(Affine.Utils.UnitsUtil.MeasureUnit.UNIT_KG);
                            atiMaxWeightUnitsFirst.Selected = WeightUnits;
                            atiMaxWeightUnitsLast.UnitList.Add(Affine.Utils.UnitsUtil.MeasureUnit.UNIT_LBS);
                            atiMaxWeightUnitsLast.UnitList.Add(Affine.Utils.UnitsUtil.MeasureUnit.UNIT_KG);
                            atiMaxWeightUnitsLast.Selected = WeightUnits;
                            stream = stream.OrderByDescending(w => w.Max);
                            break;

                        case (long)Affine.Utils.WorkoutUtil.WodType.TIMED:
                            atiTimeSpanePanel.Visible = true;
                            stream = stream.OrderBy(w => w.Duration);
                            break;

                        default:
                            stream = stream.OrderByDescending(w => w.TimeStamp);
                            break;
                        }
                        string js = string.Empty;
                        atiShareLink.ShareLink  = "http://" + Request.Url.Host + "/workout/" + wod.Id;
                        atiShareLink.ShareTitle = "FlexFWD.com crossfit WOD " + wod.Name;

                        workoutTabTitle.Text = "&nbsp;" + (string.IsNullOrWhiteSpace(wod.Name) ? "Untitled" : wod.Name) + "&nbsp;";
                        Affine.WebService.StreamService ss = new WebService.StreamService();
                        string jsonEveryone = ss.getStreamDataForWOD(wod.Id, -1, 0, 15, true, true, -1, -1, -1);

                        string jsonYou = string.Empty;

                        js += " Aqufit.Page." + atiWorkoutHighChart.ID + ".fromStreamData('" + jsonEveryone + "'); ";
                        if (base.UserSettings != null)
                        {
                            hlLogWorkout.HRef = baseUrl + UserSettings.UserName + "?w=" + wId;
                            hlWorkouts.HRef   = baseUrl + UserSettings.UserName + "/workout-history";
                            jsonYou           = ss.getStreamDataForWOD(wod.Id, base.UserSettings.Id, 0, 10, true, true, -1, -1, -1);
                            js += "Aqufit.Page.atiYouStreamScript.generateStreamDom('" + jsonYou + "');";
                            js += " Aqufit.Page." + atiWorkoutHighChart.ID + ".fromYourStreamData('" + jsonYou + "'); ";
                            // TODO: this could be improved on...
                            Workout thisWod = entities.UserStreamSet.OfType <Workout>().FirstOrDefault(w => w.UserSetting.Id == UserSettings.Id && w.WOD.Id == wId);
                            if (thisWod != null)
                            {   // graphs of this wod
                                hlGraph.HRef = ResolveUrl("~/") + UserSettings.UserName + "/workout/" + thisWod.Id;
                            }
                            else
                            {   // just grab any workout then..
                                Workout any = entities.UserStreamSet.OfType <Workout>().OrderByDescending(w => w.Id).FirstOrDefault(w => w.UserSetting.Id == UserSettings.Id);
                                if (any != null)
                                {
                                    hlGraph.HRef = ResolveUrl("~/") + UserSettings.UserName + "/workout/" + any.Id;
                                }
                                else
                                {   // no workouts ??? say what.. slack man :) hide graph
                                    hlGraph.Visible = false;
                                }
                            }
                        }
                        else
                        {
                            hlGraph.HRef                 = ResolveUrl("~/Login");
                            hlLogWorkout.HRef            = hlGraph.HRef;
                            hlWorkouts.HRef              = hlGraph.HRef;
                            atiPanelYourProgress.Visible = false;
                        }
                        hlCreateWOD.HRef  = baseUrl + "Profile/WorkoutBuilder";
                        hlMyWorkouts.HRef = baseUrl + "Profile/MyWorkouts";
                        js += " Aqufit.Page." + atiWorkoutHighChart.ID + ".drawChart(); ";



                        ScriptManager.RegisterStartupScript(this, Page.GetType(), "SimilarRouteList", "$(function(){ " + js + " Aqufit.Page.atiEveryoneStreamScript.generateStreamDom('" + jsonEveryone + "'); });", true);



                        YouTubeQuery query = new YouTubeQuery(YouTubeQuery.DefaultVideoUri);
                        //order results by the number of views (most viewed first)
                        query.OrderBy          = "viewCount";
                        query.NumberToRetrieve = 3;
                        query.SafeSearch       = YouTubeQuery.SafeSearchValues.Moderate;

                        YouTubeRequestSettings settings = new YouTubeRequestSettings(ConfigurationManager.AppSettings["youtubeApp"], ConfigurationManager.AppSettings["youtubeKey"]);
                        YouTubeRequest         request  = new YouTubeRequest(settings);
                        const int     NUM_ENTRIES       = 50;
                        IList <Video> videos            = new List <Video>();
                        IList <Video> groupVideo        = new List <Video>();
                        // first try to find videos with regard to users group
                        Feed <Video> videoFeed = null;

                        if (this.UserSettings != null)
                        {
                            long[] groupIds = entities.UserFriends.Where(f => (f.SrcUserSettingKey == UserSettings.Id || f.DestUserSettingKey == UserSettings.Id) && f.Relationship >= (int)Affine.Utils.ConstsUtil.Relationships.GROUP_OWNER).Select(f => f.SrcUserSettingKey == UserSettings.Id ? f.DestUserSettingKey : f.SrcUserSettingKey).ToArray();
                            Group  business = entities.UserSettings.OfType <Group>().Where(Utils.Linq.LinqUtils.BuildContainsExpression <Group, long>(us => us.Id, groupIds)).FirstOrDefault(g => g.GroupType.Id == 1);
                            if (business != null)
                            {   // TODO: need the business name...
                                query.Query = business.UserName;
                            }
                            else
                            {
                                UserSettings creator = entities.UserSettings.FirstOrDefault(u => u.Id == wod.UserSettingsKey);
                                if (creator is Group)
                                {   // TODO: need the business name...
                                    query.Query = creator.UserFirstName + " " + creator.UserLastName;
                                }
                                else
                                {
                                    query.Query = UserSettings.UserFirstName + " " + UserSettings.UserLastName;
                                }
                            }
                            videoFeed = request.Get <Video>(query);
                            foreach (Video v in videoFeed.Entries)
                            {
                                groupVideo.Add(v);
                            }
                        }
                        if (videos.Count < NUM_ENTRIES)
                        {   // now try the crossfit WOD name
                            query.NumberToRetrieve = NUM_ENTRIES - videos.Count;
                            query.Query            = "crossfit wod " + wod.Name;
                            videoFeed = request.Get <Video>(query);
                            foreach (Video v in videoFeed.Entries)
                            {
                                videos.Add(v);
                            }
                            if (videos.Count < NUM_ENTRIES)
                            {   // this is last resort .. just get videos about crossfit...
                                query.NumberToRetrieve = NUM_ENTRIES - videos.Count;
                                query.Query            = "crossfit wod";
                                videoFeed = request.Get <Video>(query);
                                foreach (Video v in videoFeed.Entries)
                                {
                                    videos.Add(v);
                                }
                            }
                        }

                        const int TAKE = 3;
                        if (videos.Count > TAKE)
                        {
                            Random random = new Random((int)DateTime.Now.Ticks);
                            int    rand   = random.Next(videos.Count - TAKE);
                            videos = videos.Skip(rand).Take(TAKE).ToList();
                            if (groupVideo.Count > 0)
                            {
                                // always replace one of the main videos with a gorup one.. (if possible)
                                rand      = random.Next(groupVideo.Count - 1);
                                videos[0] = groupVideo[rand];
                            }
                            atiYoutubeThumbList.VideoFeed = videos;
                        }
                        else
                        {
                            atiVideoPanel.Visible = false;
                        }
                    }
                    else
                    {
                        atiVideoPanel.Visible     = false;
                        atiPanelQuickView.Visible = false;
                        hlGraph.Visible           = false;
                        aqufitEntities entities      = new aqufitEntities();
                        var            exerciseArray = entities.Exercises.OrderBy(x => x.Name).Select(x => new{ Text = x.Name, Value = x.Id }).ToArray();
                        RadListBoxExcerciseSource.DataSource = exerciseArray;
                        RadListBoxExcerciseSource.DataBind();

                        string order = orderDate.Checked ? "date" : "popular";
                        if (Settings["Configure"] != null && Convert.ToString(Settings["Configure"]).Equals("ConfigureMyWorkouts"))
                        {
                            this.IsMyWorkouts          = true;
                            atiProfile.ProfileSettings = base.UserSettings;
                            atiProfile.IsOwner         = true;
                            atiProfile.IsSmall         = true;
                            atiWorkoutPanel.Visible    = true;
                            workoutTabTitle.Text       = "My Workouts";
                            liMyWorkouts.Visible       = false;
                            liFindWorkout.Visible      = true;
                            WebService.StreamService streamService = new WebService.StreamService();
                            string json = streamService.GetWorkouts(base.UserSettings.Id, 0, 30, order, null);
                            ScriptManager.RegisterStartupScript(this, Page.GetType(), "WorkoutList", "$(function(){ Aqufit.Page.atiWorkoutListScript.isMyRoutes = true; Aqufit.Page.atiWorkoutListScript.generateStreamDom('" + json + "'); });", true);
                        }
                        else
                        {
                            this.IsMyWorkouts        = false;
                            atiProfile.Visible       = false;
                            workoutTabTitle.Text     = "Workouts";
                            atiWorkoutPanel.Visible  = true;
                            atiWorkoutViewer.Visible = false;
                            WebService.StreamService streamService = new WebService.StreamService();
                            string json = streamService.GetWorkouts(-1, 0, 30, order, null);
                            ScriptManager.RegisterStartupScript(this, Page.GetType(), "WorkoutList2", "$(function(){ Aqufit.Page.atiWorkoutListScript.generateStreamDom('" + json + "'); });", true);
                        }
                    }
                }
            }
            catch (Exception exc) //Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }
Esempio n. 42
0
        public IEnumerable<VideoEntry> Search(string term)
        {
            var request = new YouTubeRequest(_settings);

            Feed<Video> videoFeed = request.Get<Video>(new YouTubeQuery(YouTubeQuery.DefaultVideoUri)
                {
                    Query = term
                });

            return videoFeed.Entries.Select(video => _videoEntryFactory.Build(video));
        }
Esempio n. 43
0
 public List<Playlist> GetMyFavorite()
 {
     List<Playlist> list = new List<Playlist>();
     try
     {
         if (isLoggedIn == false) return null;
         YouTubeRequestSettings settings = new YouTubeRequestSettings(APP_NAME, DEV_KEY, USERNAME, PASSWORD);
         YouTubeRequest reqeuest = new YouTubeRequest(settings);
         Feed<Playlist> pl_feeds = reqeuest.Get<Playlist>(new Uri("https://gdata.youtube.com/feeds/api/users/default/favorites?v=2"));
         list = pl_feeds.Entries.ToList();
         MyFavorite = list;
     }
     catch
     {
     }
     return list;
 }
Esempio n. 44
0
        private static string GetYoutubeLink(string artist, string title)
        {
            string videoUrl;
            try
            {
            YouTubeRequestSettings requestSettings = new YouTubeRequestSettings(Configuration.GDataApp, Configuration.DeveloperKey);
                YouTubeRequest youTubeRequest = new YouTubeRequest(requestSettings);

            YouTubeQuery youTubeQuery = new YouTubeQuery(YouTubeQuery.DefaultVideoUri);
            youTubeQuery.Query = artist + " " + title;
            //youTubeQuery.OrderBy = "viewCount";  use default of relevance instead
            youTubeQuery.NumberToRetrieve = 1;

            Feed<Video> videoFeed = youTubeRequest.Get<Video>(youTubeQuery);

            if (videoFeed.TotalResults == 0)
            {
                return "";
            }

            videoUrl = "http://www.youtube.com/watch?v=";
            foreach (Video vid in videoFeed.Entries)
            {
                videoUrl += vid.VideoId;
            }
            }
            catch (Exception)
            {
                videoUrl = "";
            }

            return videoUrl;
        }
        //----------------------------------------------------------------------------------------------------------



        //----------------------------------------------------------------------------------------------------------
        // perform youtube search
        public ActionResult Music()
        {
            if (Request.QueryString["ss"] != null)
            {
                //---------------------------------------------------------------------
                string search_string = Request.QueryString["ss"].ToString();
                ViewBag.search_string = search_string.Replace(" ", "+");
                //---------------------------------------------------------------------



                //---------------------------------------------------------------------
                int Curr_Page = 1;
                if (Request.QueryString["page"] != null)
                {
                    if (Int32.TryParse(Request.QueryString["page"], out Curr_Page) == false)
                    {
                        Curr_Page = 1;
                    }
                }
                ViewBag.CurrPage = Curr_Page;
                //---------------------------------------------------------------------



                // "orderBy"
                //---------------------------------------------------------------------
                string orderBy = "";
                if (Request.QueryString["orderBy"] != null)
                {
                    orderBy = Request.QueryString["orderBy"].ToString();
                }
                ViewBag.orderBy = orderBy;
                //---------------------------------------------------------------------



                //---------------------------------------------------------------------
                #region save_recent_searches_to_application-varibles
                //save recent searches to application varibles
                if (HttpContext.Application["RECENT_SEARCHES"] != null)
                {
                    List <string> recent_searches = (List <string>)HttpContext.Application["RECENT_SEARCHES"];
                    recent_searches.Add(search_string);
                    if (recent_searches.Count > MAX_RECENT_SEARCHES_NUM)
                    {
                        recent_searches.RemoveAt(recent_searches.Count - 1);
                    }

                    HttpContext.Application["RECENT_SEARCHES"] = recent_searches;
                }
                else
                {
                    List <string> recent_searches = new List <string>();
                    recent_searches.Add(search_string);

                    HttpContext.Application["RECENT_SEARCHES"] = recent_searches;
                }

                if (HttpContext.Application["RECENT_SEARCHES"] != null)
                {
                    ViewBag.recent_searches = (List <string>)HttpContext.Application["RECENT_SEARCHES"];
                }
                #endregion
                //---------------------------------------------------------------------



                YouTubeRequestSettings settings = new YouTubeRequestSettings("hypster", "AI39si5TNjKgF6yiHwUhKbKwIui2JRphXG4hPXUBdlrNh4XMZLXu--lf66gVSPvks9PlWonEk2Qv9fwiadpNbiuh-9TifCNsqA");
                YouTubeRequest         request  = new YouTubeRequest(settings);

                //order by relevance
                //string feedUrl = String.Format("http://gdata.youtube.com/feeds/api/videos?q={0}&category=Music&format=5&restriction={1}&safeSearch=none&start-index={2}&orderby=relevance", HttpUtility.UrlEncode(search_string.Replace("+"," ")), Request.ServerVariables["REMOTE_ADDR"], (Curr_Page * 25) + 1);  //(page.HasValue ? page * 25 : 0) + 1);
                //order by viewCount
                //string feedUrl = String.Format("http://gdata.youtube.com/feeds/api/videos?q={0}&category=Music&format=5&restriction={1}&safeSearch=none&start-index={2}&orderby=viewCount", HttpUtility.UrlEncode(search_string.Replace("+"," ")), Request.ServerVariables["REMOTE_ADDR"], (Curr_Page * 25) + 1);  //(page.HasValue ? page * 25 : 0) + 1);
                //Feed<Video> videoFeed = null;


                //add orderBy if selected
                if (orderBy != "")
                {
                    orderBy = "&orderby=" + orderBy;
                }

                //original sorting order
                string       feedUrl   = String.Format("http://gdata.youtube.com/feeds/api/videos?q={0}&category=Music&format=5&restriction={1}&safeSearch=none&start-index={2}" + orderBy, HttpUtility.UrlEncode(search_string.Replace("+", " ")), Request.ServerVariables["REMOTE_ADDR"], (Curr_Page * 25) - 25 + 1);
                Feed <Video> videoFeed = null;


                try
                {
                    videoFeed = request.Get <Video>(new Uri(feedUrl));
                }
                catch (Exception ex)
                {
                }


                return(View(videoFeed));
            } // NEED TO CHECK AND FIX THIS SECTION
            else
            {
                if (HttpContext.Application["RECENT_SEARCHES"] != null)
                {
                    ViewBag.recent_searches = (List <string>)HttpContext.Application["RECENT_SEARCHES"];
                }

                return(View());
            }
        }
Esempio n. 46
0
        protected void btnSearchVideoKeywords_Click(object sender, EventArgs e)
        {
            if (txtVideoKeywords.Text.Trim().Length == 0)
                return;

            var dtVideos = new DataTable();
            dtVideos.Columns.Add("Title", typeof(string));
            dtVideos.Columns.Add("ThumbnailUrl", typeof(string));
            dtVideos.Columns.Add("VideoUrl", typeof(string));
            dtVideos.Columns.Add("ID", typeof(int));


            var settings = new YouTubeRequestSettings("eStream-ezFixUp", null,
                "AI39si7DZKHR_khn2HMQ-fABrE1J7OI4fT-LTH5fFexEn3Cfl-D2ZIpErZhZiKTAGoSHZA2e3Aeh9RAqrZ9lq7RxtAYbUFyf3g");
            var request = new YouTubeRequest(settings);
            var query = new YouTubeQuery(YouTubeQuery.DefaultVideoUri);

            //order results by the number of views (most viewed first)
            query.OrderBy = "viewCount";

            query.Query = txtVideoKeywords.Text.Trim();
            query.SafeSearch = YouTubeQuery.SafeSearchValues.None;


            Feed<Video> videoFeed;
            try
            {
                videoFeed = request.Get<Video>(query);
            }
            catch (Exception err)
            {
                Global.Logger.LogError("YouTube search for " + txtVideoKeywords.Text, err);
                return;
            }
            foreach (var video in videoFeed.Entries)
            {
                if (video.Contents == null || video.Contents.Count == 0
                    || video.Thumbnails == null || video.Thumbnails.Count == 0)
                    continue;

                var thumbnailUrl = video.Thumbnails[0].Url;
                var videoUrl = video.Contents[0].Url;
                dtVideos.Rows.Add(new object[] { video.Title, thumbnailUrl, videoUrl, 0 });
            }

            /* // Old search implementation
            //string uri = "https://gdata.youtube.com/feeds/videos/-/" +
            //    txtVideoKeywords.Text.Trim().Replace(' ', '/');
            string uri = "https://gdata.youtube.com/feeds/api/videos?q=" +
                Server.UrlEncode(txtVideoKeywords.Text.Trim());

            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(uri);
            XmlNamespaceManager nsMgr = new XmlNamespaceManager(xmlDoc.NameTable);
            nsMgr.AddNamespace("def", "https://www.w3.org/2005/Atom");
            nsMgr.AddNamespace("media", "https://search.yahoo.com/mrss/");
            XmlNodeList nodes = xmlDoc.SelectNodes("/def:feed/def:entry", nsMgr);
            foreach (XmlNode node in nodes)
            {
                if (node.SelectSingleNode("media:group/media:content", nsMgr) == null)
                    continue;

                string title = node.SelectSingleNode("def:title", nsMgr).InnerText;
                string thumbUrl =
                    node.SelectSingleNode("media:group/media:thumbnail", nsMgr).Attributes["url"].InnerText;
                string videoUrl =
                    node.SelectSingleNode("media:group/media:content", nsMgr).Attributes["url"].InnerText;
                dtVideos.Rows.Add(new object[] { title, thumbUrl, videoUrl, 0 });
            }
            */

            dlVideos.DataSource = dtVideos;
            dlVideos.DataBind();

            divVideoPreview.Visible = false;
        }
Esempio n. 47
0
        public static void ParseChannelLevel2(VideoCommentWrapper commentWrapper, string pAppName, string pDevKey)
        {
            try
            {
                string channelName        = commentWrapper.userName;//displayName is not working in 1 case.. Got Luv2bbeautiful ., contains space + .
                string userId             = commentWrapper.userName;
                string channelCleanedName = Common.CleanFileName(channelName);
                if (!Directory.Exists(channelCleanedName))
                {
                    Directory.CreateDirectory(channelCleanedName);
                }
                else
                {
                    Directory.Delete(channelCleanedName, true);
                    Directory.CreateDirectory(channelCleanedName);
                }

                //Search for Channel...
                // If Channel doesn't exit Search for following things
                //1. Favourties, 2. Uploaded , 3. Playlist
                multithreadingChannelName = channelCleanedName;
                string channelFileName    = ConfigurationManager.AppSettings["channelsFileName"].ToString();
                string channelFileNameXML = ConfigurationManager.AppSettings["channelsFileNameXML"].ToString();
                //File.AppendAllText(channelCleanedName + "/" + log, "Entered Inside Parse Channel at : " + DateTime.Now + Environment.NewLine + Environment.NewLine);

                string         videoUrl     = "https://gdata.youtube.com/feeds/api/users/" + channelName + "/uploads?&start-index=" + startIndex;
                HttpWebRequest nameRequest1 = (HttpWebRequest)WebRequest.Create(videoUrl);
                nameRequest1.KeepAlive       = false;
                nameRequest1.ProtocolVersion = HttpVersion.Version10;
                HttpWebResponse nameResponse1 = (HttpWebResponse)nameRequest1.GetResponse();

                Stream       nameStream1 = nameResponse1.GetResponseStream();
                StreamReader nameReader1 = new StreamReader(nameStream1);

                string xmlData1 = nameReader1.ReadToEnd();
                File.WriteAllText(channelCleanedName + "/" + channelFileNameXML, xmlData1);
                //Constant.tempFiles.Add(channelFileNameXML);
                XmlDocument doc1 = new XmlDocument();
                doc1.Load(channelCleanedName + "/" + channelFileNameXML);
                XmlNamespaceManager namespaceManager2 = new XmlNamespaceManager(doc1.NameTable);
                namespaceManager2.AddNamespace("Atom", "http://www.w3.org/2005/Atom");
                //XmlNodeList listResult1 = doc1.SelectNodes(channelAtomEntry, namespaceManager2);

                ////Getting total Record
                XmlNamespaceManager namespaceManager3 = new XmlNamespaceManager(doc1.NameTable);
                namespaceManager3.AddNamespace("openSearch", "http://a9.com/-/spec/opensearchrss/1.0/");

                XmlNode nodeTotal = doc1.SelectSingleNode("//openSearch:totalResults", namespaceManager3);
                int     total     = Int32.Parse(nodeTotal.InnerText);
                if (total != 0)
                {
                    string          channelUrl   = ConfigurationManager.AppSettings["ChannelSearchUrl"].ToString() + channelName + "&start-index=1&max-results=10&v=2";
                    WebRequest      nameRequest  = WebRequest.Create(channelUrl);
                    HttpWebResponse nameResponse = (HttpWebResponse)nameRequest.GetResponse();
                    Stream          nameStream   = nameResponse.GetResponseStream();
                    StreamReader    nameReader   = new StreamReader(nameStream);

                    string xmlData = nameReader.ReadToEnd();

                    File.WriteAllText(channelCleanedName + "/" + channelFileNameXML, xmlData);

                    XmlDocument doc = new XmlDocument();
                    doc.Load(channelCleanedName + "/" + channelFileNameXML);

                    XmlNamespaceManager namespaceManager1 = new XmlNamespaceManager(doc.NameTable);
                    namespaceManager1.AddNamespace("openSearch", "http://a9.com/-/spec/opensearch/1.1/");
                    XmlNode node1 = doc.SelectSingleNode("//openSearch:totalResults", namespaceManager1);


                    //This means Channel Exists
                    XmlNamespaceManager namespaceManager = new XmlNamespaceManager(doc.NameTable);
                    namespaceManager.AddNamespace("Atom", "http://www.w3.org/2005/Atom");

                    XmlNodeList listResult = doc.SelectNodes(channelTitleXPath, namespaceManager);
                    int         count      = 0;
                    foreach (XmlNode node in listResult)
                    {
                        count++;
                        if (node.FirstChild.InnerText.Equals(channelName, StringComparison.InvariantCultureIgnoreCase))
                        {
                            break;
                        }
                    }
                    XmlNodeList entryNode = doc.SelectSingleNode(channelAtomEntry + "[" + count + "]", namespaceManager).ChildNodes;
                    foreach (XmlNode n in entryNode)
                    {
                        if (n.Name.Equals("title"))
                        {
                            File.AppendAllText(channelCleanedName + "/" + channelFileName, "Channel Name: " + n.InnerText + "\r\n");
                        }
                        else if (n.Name.Equals("yt:channelStatistics"))
                        {
                            File.AppendAllText(channelCleanedName + "/" + channelFileName, "Subscribers Count: " + n.Attributes["subscriberCount"].Value + "\r\n");
                            File.AppendAllText(channelCleanedName + "/" + channelFileName, "Views Count: " + n.Attributes["viewCount"].Value + "\r\n");
                        }
                        //else if (n.Name.Equals("summary"))
                        //{
                        //    File.AppendAllText(pChannelName + "/" + channelFileName, "Channel Description: " + n.InnerText + "\r\n");
                        //}
                        else if (n.Name.Equals("link"))
                        {
                            if (n.Attributes["rel"].Value.Equals("alternate", StringComparison.CurrentCultureIgnoreCase))
                            {
                                File.AppendAllText(channelCleanedName + "/" + channelFileName, "Channel URL: " + n.Attributes["href"].Value + "\r\n");
                                channelUrlMain = n.Attributes["href"].Value;
                            }
                        }
                        else if (n.Name.Equals("id"))
                        {
                            string   id         = n.InnerText;
                            string[] arrId      = n.InnerText.Split(new Char[] { ':' }, StringSplitOptions.RemoveEmptyEntries);
                            bool     indexFound = false;
                            for (int i = 0; i < arrId.Length; i++)
                            {
                                if (arrId[i].Equals("Channel", StringComparison.CurrentCultureIgnoreCase))
                                {
                                    indexFound = true;
                                    continue;
                                }
                                if (indexFound)
                                {
                                    channelId = arrId[i];
                                    break;
                                }
                            }
                        }
                    }
                    //"AI39si7SUChDwy6-ms_bz7rY-mzkqWc9vouhT_XZfh_xery5HjOujHc4USzQJ-M6XeWPCmGtaMzBgs3QP5S4O3vFBHoxmCfIjA"
                    YouTubeRequestSettings settings = new YouTubeRequestSettings(pAppName, pDevKey);
                    YouTubeRequest         request  = new YouTubeRequest(settings);

                    Uri          videoEntryUrl = new Uri("http://gdata.youtube.com/feeds/api/users/" + channelName);
                    Feed <Video> videoFeed     = request.Get <Video>(videoEntryUrl);
                    foreach (Entry e in videoFeed.Entries)
                    {
                        File.AppendAllText(channelCleanedName + "/" + channelFileName, "Channel Description: " + e.Summary + "\r\n");
                        break;
                    }

                    Constant.tempFiles.Add(channelFileNameXML);
                    Dictionary <string, VideoWrapper> videoDictionary = new Dictionary <string, VideoWrapper>();

                    File.AppendAllText(channelCleanedName + "/" + channelFileName, "Video Lists \r\n");

                    startIndex = 1;

                    //File.AppendAllText(channelCleanedName + "/" + log, "\tEntering WriteVideoList at: " + DateTime.Now + Environment.NewLine + Environment.NewLine);

                    WriteVideoLists(channelName, channelId, startIndex, videoDictionary, Enumeration.VideoRequestType.All);

                    //File.AppendAllText(channelCleanedName + "/" + log, "\t\tTotal Dictionary Items : " + videoDictionary.Count + Environment.NewLine);
                    //File.AppendAllText(channelCleanedName + "/" + log, "\r\n\tLeft WriteVideoList at: " + DateTime.Now + Environment.NewLine + Environment.NewLine);
                    //File.AppendAllText(channelCleanedName + "/" + "Count.txt", "Count After complete Request Response (Expected 1000) : " + recordCount + "\r\n");

                    //File.AppendAllText(channelCleanedName + "/" + log, "Leaving Parse Channel at : " + DateTime.Now);

                    ///Crawl Comments
                    ///
                    ChannelComment.CrawlComments(videoDictionary, channelName);
                    ///Done Crawling Comments
                    //ChannelVideo.parseVideo(videoDictionary, channelName);
                    ///Done Crawling video description

                    ///Remove All Temporary Files here
                    ///
                    Common.RemoveTempFiles(Constant.tempFiles, channelName);
                    ///Done
                    ///

                    ///ReInitialize All Data
                    ///
                    //channelName = "";
                    channelId   = "";
                    startIndex  = 1;
                    recordCount = 0;
                    updatedFlag = false;
                    ///ReInitializing Done
                }
                //Extract Playlists
                ExtractFromPlaylist(channelName, userId, 1);

                ///ReInitialize All Data
                ///
                //channelName = "";
                channelId   = "";
                startIndex  = 1;
                recordCount = 0;
                updatedFlag = false;
                ///ReInitializing Done

                //Extract Favourites

                ExtractFromUserFavourite(channelName, userId, 1);
            }
            catch (Exception ex)
            {
                Thread.Sleep(10000);
                ParseChannelLevel2(commentWrapper, pAppName, pDevKey);
            }
        }
Esempio n. 48
0
        /// <summary>
        /// Returns a list of tracks from one of the YouTube feeds
        /// </summary>
        /// <param name="feed">The feed</param>
        /// <returns>An observable collection of TrackData that represents the most viewed YouTube tracks</returns>
        public static ObservableCollection<TrackData> TopFeed(string feed = "top_rated")
        {
            ObservableCollection<TrackData> tracks = new ObservableCollection<TrackData>();

            try
            {
                YouTubeRequest request = new YouTubeRequest(settings);

                int maxFeedItems = 50;

                string filter = SettingsManager.YouTubeFilter;
                if (String.IsNullOrWhiteSpace(filter) || filter == "None")
                    filter = "";
                else
                    filter = String.Format("_{0}", filter);

                int i = 1;
                Feed<Video> videoFeed = request.Get<Video>(new Uri(uriBase + "/feeds/api/standardfeeds/" + feed + filter + "?format=5"));
                foreach (Video entry in videoFeed.Entries)
                {
                    if (i++ > maxFeedItems) break;
                    if (entry != null)
                        tracks.Add(CreateTrack(entry));
                }
            }
            catch (Exception e)
            {
                U.L(LogLevel.Warning, "YouTube", "Could not fetch top rated: " + e.Message);
                VerifyConnectivity();
            }

            TrackSource = tracks;
            return tracks;
        }
Esempio n. 49
0
 public static List<VideoBase> searchByKeyWord(string keyword)
 {
     List<VideoBase> list = new List<VideoBase>();
     try
     {
         YouTubeRequest ytRequest = new YouTubeRequest(new YouTubeRequestSettings(APP_NAME, DEV_KEY));
         Feed<Video> vid_feed = ytRequest.Get<Video>(new Uri("https://gdata.youtube.com/feeds/api/videos?q=" + keyword + "&max-results=20&v=2"));
         foreach (Video video in vid_feed.Entries)
         {
             VideoBase baseVideo = ConvertToVideoBase(video);
             list.Add(baseVideo);
         }
     }
     catch
     {
     }
     return list;
 }
Esempio n. 50
0
        private void getUploadedBw_DoWork(object sender, DoWorkEventArgs e)
        {
            List<object> genericlist = e.Argument as List<object>;
            String username = (String)genericlist.ElementAt(0);
            List<VideoBase> result = new List<VideoBase>();
            try
            {
                Uri uri = new Uri("http://gdata.youtube.com/feeds/api/users/" + username + "/uploads");
                YouTubeRequest req = new YouTubeRequest(new YouTubeRequestSettings("YouViewer", DEV_KEY));
                Feed<Video> videoFeeds = req.Get<Video>(uri);

                for (int i = 0; i < videoFeeds.Entries.Count(); i++)
                {
                    Video video = videoFeeds.Entries.ElementAt(i);
                    result.Add(YoutubeProvider.ConvertToVideoBase(video));
                }
            }
            catch (Google.GData.Client.GDataRequestException gdre)
            {
            }

            List<object> arg = new List<object>();
            arg.Add(result);
            e.Result = arg;
        }
Esempio n. 51
0
        /// <summary>
        /// Searches YouTube for tracks matching a certain query
        /// </summary>
        /// <param name="query">The query to search for</param>
        /// <returns>An observable collection of TrackData with all YouTube tracks that match query</returns>
        public static ObservableCollection<TrackData> Search(string query)
        {
            ObservableCollection<TrackData> tracks = new ObservableCollection<TrackData>();

            try
            {
                string filter = SettingsManager.YouTubeFilter;

                YouTubeQuery q = new YouTubeQuery(YouTubeQuery.DefaultVideoUri);
                q.OrderBy = "relevance";
                q.Query = query;
                q.Formats.Add(YouTubeQuery.VideoFormat.Embeddable);
                q.NumberToRetrieve = 50;
                q.SafeSearch = YouTubeQuery.SafeSearchValues.None;

                if (!String.IsNullOrWhiteSpace(filter) && filter != "None")
                {
                    AtomCategory category = new AtomCategory(filter, YouTubeNameTable.CategorySchema);
                    q.Categories.Add(new QueryCategory(category));
                }

                YouTubeRequest request = new YouTubeRequest(settings);

                Feed<Video> videoFeed = request.Get<Video>(q);
                foreach (Video entry in videoFeed.Entries)
                {
                    tracks.Add(YouTubeManager.CreateTrack(entry));
                }
            }
            catch (Exception exc)
            {
                U.L(LogLevel.Error, "YOUTUBE", "Error while performing search: " + exc.Message);
                VerifyConnectivity();
            }

            TrackSource = tracks;

            return tracks;
        }
Esempio n. 52
0
        private void VideolariGetir(string kanalAdi)
        {
            try
            {
                int toplam = 0;
                lstmanual.Items.Clear();
                string q;
                using (WebClient asd = new WebClient())
                {
                    asd.Encoding = Encoding.UTF8;
                    q = asd.DownloadString("http://gdata.youtube.com/feeds/api/users/" + kanalAdi + "/uploads?v=2&alt=jsonc&max-results=0");
                }
                string[] adet1 = q.Split(new string[] { "totalItems\":" }, StringSplitOptions.None);
                string[] adet2 = adet1[1].Split(',');
                string adet3 = adet2[0];
                lstmanual.Items.Add(adet3);

                YouTubeRequestSettings settings = new YouTubeRequestSettings("Contentor", dataGridView1.Rows[0].Cells[3].Value.ToString(), dataGridView1.Rows[0].Cells[1].Value.ToString(), dataGridView1.Rows[0].Cells[2].Value.ToString());
                YouTubeRequest request = new YouTubeRequest(settings);
                int index = 1;
                for (int i = 1; i <= Convert.ToInt16(adet3) / 50; i++)
                {
                    Uri uri = new Uri("http://gdata.youtube.com/feeds/api/users/" + kanalAdi + "/uploads?&max-results=50&start-index=" + index);
                    Feed<Video> videoFeed = request.Get<Video>(uri);
                    foreach (Video entry in videoFeed.Entries)
                    {
                        lstmanual.Items.Add("http://www.youtube.com/watch?v=" + entry.VideoId + "|" + kanal_sayisi++);
                        if (kanal_sayisi > 47)
                            kanal_sayisi = 0;
                    }
                    index += 50;
                }
                toplam = ((Convert.ToInt16(adet3) / 50) * 50) + 1;
                Uri uri2 = new Uri("http://gdata.youtube.com/feeds/api/users/" +kanalAdi+ "/uploads?&max-results=50&start-index=" + toplam);
                Feed<Video> videoFeed2 = request.Get<Video>(uri2);
                foreach (Video entry in videoFeed2.Entries)
                {
                    lstmanual.Items.Add("http://www.youtube.com/watch?v=" + entry.VideoId + "|" + kanal_sayisi++);
                    if (kanal_sayisi > 47)
                        kanal_sayisi = 0;
                }

            }
            catch
            {

            }
        }
Esempio n. 53
0
        public static bool ParseChannel(string pChannelName, string pAppName, string pDevKey, int pLevel)
        {
            ///ReInitialize All Data
            ///
            channelName = "";
            channelId = "";
            startIndex = 1;
            recordCount = 0;
            updatedFlag = false;
            ///ReInitializing Done
            ///

            multithreadingChannelName = pChannelName;
            string channelFileName = ConfigurationManager.AppSettings["channelsFileName"].ToString();
            string channelFileNameXML = ConfigurationManager.AppSettings["channelsFileNameXML"].ToString();
            //File.AppendAllText(pChannelName + "/" + log, "Entered Inside Parse Channel at : " + DateTime.Now + Environment.NewLine + Environment.NewLine);

            //This Request will give us 10 channels from index 1, which is searched by adding its name.

            //e.g.https://gdata.youtube.com/feeds/api/channels?q=" + pChannelName + "&start-index=1&max-results=10&v=2

            //q=<Channel Name>
            //start-index = <start Index of Search result> (by default 1st Index is '1')
            //max-result = <page size (containing number of channels)>
            //v = Not known yet. :S

            //e.g.https://gdata.youtube.com/feeds/api/channels?q=" + pChannelName + "&start-index=1&max-results=10&v=2
            string channelUrl = ConfigurationManager.AppSettings["ChannelSearchUrl"].ToString() + pChannelName + "&start-index=1&max-results=10&v=2";
            WebRequest nameRequest = WebRequest.Create(channelUrl);
            HttpWebResponse nameResponse = (HttpWebResponse)nameRequest.GetResponse();

            Stream nameStream = nameResponse.GetResponseStream();
            StreamReader nameReader = new StreamReader(nameStream);

            string xmlData = nameReader.ReadToEnd();

            File.WriteAllText(pChannelName + "/" + channelFileNameXML, xmlData);

            XmlDocument doc = new XmlDocument();
            doc.Load(pChannelName + "/" + channelFileNameXML);
            XmlNamespaceManager namespaceManager = new XmlNamespaceManager(doc.NameTable);
            namespaceManager.AddNamespace("Atom", "http://www.w3.org/2005/Atom");

            XmlNodeList listResult = doc.SelectNodes(channelTitleXPath, namespaceManager);
            int count = 0;
            foreach (XmlNode node in listResult)
            {
                count++;
                if (node.FirstChild.InnerText.Equals(pChannelName, StringComparison.InvariantCultureIgnoreCase))
                {
                    break;
                }
            }
            XmlNodeList entryNode = doc.SelectSingleNode(channelAtomEntry + "[" + count + "]", namespaceManager).ChildNodes;
            foreach (XmlNode n in entryNode)
            {
                if (n.Name.Equals("title"))
                {
                    File.AppendAllText(pChannelName + "/" + channelFileName, "Channel Name: " + n.InnerText + "\r\n");
                }
                else if (n.Name.Equals("yt:channelStatistics"))
                {
                    File.AppendAllText(pChannelName + "/" + channelFileName, "Subscribers Count: " + n.Attributes["subscriberCount"].Value + "\r\n");
                    File.AppendAllText(pChannelName + "/" + channelFileName, "Views Count: " + n.Attributes["viewCount"].Value + "\r\n");
                }
                else if (n.Name.Equals("link"))
                {
                    if (n.Attributes["rel"].Value.Equals("alternate", StringComparison.CurrentCultureIgnoreCase))
                    {
                        File.AppendAllText(pChannelName + "/" + channelFileName, "Channel URL: " + n.Attributes["href"].Value + "\r\n");
                        channelUrlMain = n.Attributes["href"].Value;
                    }
                }
                else if (n.Name.Equals("id"))
                {
                    string id = n.InnerText;
                    string[] arrId = n.InnerText.Split(new Char[] { ':' }, StringSplitOptions.RemoveEmptyEntries);
                    bool indexFound = false;
                    for (int i = 0; i < arrId.Length; i++)
                    {
                        if (arrId[i].Equals("Channel", StringComparison.CurrentCultureIgnoreCase))
                        {
                            indexFound = true;
                            continue;
                        }
                        if (indexFound)
                        {
                            channelId = arrId[i];
                            break;
                        }
                    }
                }
            }
            //"AI39si7SUChDwy6-ms_bz7rY-mzkqWc9vouhT_XZfh_xery5HjOujHc4USzQJ-M6XeWPCmGtaMzBgs3QP5S4O3vFBHoxmCfIjA"
            YouTubeRequestSettings settings = new YouTubeRequestSettings(pAppName, pDevKey);
            YouTubeRequest request = new YouTubeRequest(settings);

            Uri videoEntryUrl = new Uri("http://gdata.youtube.com/feeds/api/users/" + pChannelName);
            Feed<Video> videoFeed = request.Get<Video>(videoEntryUrl);
            foreach (Entry e in videoFeed.Entries)
            {
                File.AppendAllText(pChannelName + "/" + channelFileName, "Channel Description: " + e.Summary + "\r\n");
                break;
            }

            Constant.tempFiles.Add(channelFileNameXML);
            //Constant.tempFiles.Add(pChannelName + "/" + log);
            Dictionary<string, VideoWrapper> videoDictionary = new Dictionary<string, VideoWrapper>();

            File.AppendAllText(pChannelName + "/" + channelFileName, "Video Lists \r\n");

            startIndex = 1;

            //File.AppendAllText(pChannelName + "/" + log, "\tEntering WriteVideoList at: " + DateTime.Now + Environment.NewLine + Environment.NewLine);

            WriteVideoLists(pChannelName, channelId, startIndex, videoDictionary, Enumeration.VideoRequestType.All);

            //File.AppendAllText(pChannelName + "/" + log, "\t\tTotal Dictionary Items : " + videoDictionary.Count + Environment.NewLine);
            //File.AppendAllText(pChannelName + "/" + log, "\r\n\tLeft WriteVideoList at: " + DateTime.Now + Environment.NewLine + Environment.NewLine);
            //File.AppendAllText(pChannelName + "/" + "Count.txt", "Count After complete Request Response (Expected 1000) : " + recordCount + "\r\n");

            //File.AppendAllText(pChannelName + "/" + log, "Leaving Parse Channel at : " + DateTime.Now);

            //ChannelVideo.parseVideo(videoDictionary, pChannelName);
            ///Done Crawling video description

            ///Crawl Comments
            ///
            ChannelComment.CrawlComments(videoDictionary, pChannelName);
            ///Done Crawling Comments
            ///
            ///Remove All Temporary Files here
            ///
            Common.RemoveTempFiles(Constant.tempFiles, pChannelName);
            ///Done
            ///

            //Commenting Temporarily on Paolo Request.. <04/19/2013>

            if (ConfigurationManager.AppSettings["BothLevelsFlag"].ToString().Equals("true", StringComparison.CurrentCultureIgnoreCase))
            {

                /////ReInitialize All Data
                /////
                channelName = "";
                channelId = "";
                startIndex = 1;
                recordCount = 0;
                updatedFlag = false;
                /////ReInitializing Done

                dictionary = new Dictionary<string, VideoCommentWrapper>();
                dictionary = GlobalConstants.commentDictionary;
                int testCount = 0;
                foreach (KeyValuePair<string, VideoCommentWrapper> pair in dictionary)
                {
                    GlobalConstants.commentDictionary = new Dictionary<string, VideoCommentWrapper>();
                    VideoCommentWrapper videoComment = pair.Value;
                    ParseChannelLevel2(videoComment, pAppName, pDevKey);
                    testCount++;
                    //if (testCount > 3)
                    //    break;
                }
            }
            return true;
        }
Esempio n. 54
0
        private string[] getChannelVideos(int type,string channelUserName,string devKey,string userName, string pass)
        {
            List<string> videos = new List<string>();
            YouTubeRequestSettings settings = new YouTubeRequestSettings("Contentor", devKey, userName, pass);
            YouTubeRequest request = new YouTubeRequest(settings);
            try
            {
                int toplam = 0;
                string q;
                using (WebClient asd = new WebClient())
                {
                    asd.Encoding = Encoding.UTF8;
                    q = asd.DownloadString("http://gdata.youtube.com/feeds/api/users/" + channelUserName + "/uploads?v=2&alt=jsonc&max-results=0");
                }
                string[] adet1 = q.Split(new string[] { "totalItems\":" }, StringSplitOptions.None);
                string[] adet2 = adet1[1].Split(',');
                string adet3 = adet2[0];
                int index = 1;
                for (int i = 1; i <= Convert.ToInt16(adet3) / 50; i++)
                {
                    Uri uri = new Uri("http://gdata.youtube.com/feeds/api/users/" + channelUserName + "/uploads?&max-results=50&start-index=" + index);
                    Feed<Video> videoFeed = request.Get<Video>(uri);
                    foreach (Video entry in videoFeed.Entries)
                    {
                        videos.Add(entry.VideoId);
                    }
                    index += 50;
                }
                toplam = ((Convert.ToInt16(adet3) / 50) * 50) + 1;
                Uri uri2 = new Uri("http://gdata.youtube.com/feeds/api/users/" + channelUserName + "/uploads?&max-results=50&start-index=" + toplam);
                Feed<Video> videoFeed2 = request.Get<Video>(uri2);
                foreach (Video entry in videoFeed2.Entries)
                {
                    videos.Add(entry.VideoId);
                }
            }
            catch
            {
                MessageBox.Show("Sayfa Adında Sorun Var!");
            }
            if (type == 1)
            {
                List<string> checkedVideos = new List<string>();
                foreach (string s in videos)
                {
                    Uri videoEntryUrl = new Uri("http://gdata.youtube.com/feeds/api/videos/"+s);
                    Video video = request.Retrieve<Video>(videoEntryUrl);
                    if (video.Media != null && video.Media.Rating != null)
                    {
                        checkedVideos.Add(s+" restricted: "+video.Media.Rating.Country);
                    }

                    if (video.IsDraft)
                    {
                        string stateName = video.Status.Name;
                        checkedVideos.Add(s + " not live: "+stateName);
                        /*if (stateName == "processing")
                        {
                            checkedVideos.Add(s + " processing: " + video.Media.Rating.Country);
                        }
                        else if (stateName == "rejected")
                        {
                            checkedVideos.Add(s+" rejected: "+video.Status.Value);
                        }
                        else if (stateName == "failed")
                        {
                            checkedVideos.Add(s+" failed uploading: "+ video.Status.Value);
                        }*/
                    }
                }
                return checkedVideos.ToArray();
            }
                else
            return videos.ToArray();
        }