Joined
·
19,572 Posts
It's been a Long time since i last posted here so i guess is time to post again... here is the code i wrote few minutes ago:
Youtube query Feeds:
YoutubeQuery class:
Enjoy!
Youtube query Feeds:
Code:
/// <summary>
/// Query Youtube feeds
/// </summary>
/// <param name="keyWord">keyword to search</param>
/// <param name="startIndex">index to start from</param>
/// <param name="isHD">load HD only on demand</param>
/// <param name="isChannel">specified if the keyword is a channel name</param>
/// <returns>YoutubeQuery class containing the Youtube feeds</returns>
public async static Task<YoutubeQuery> GetYoutubeQuery(string keyWord, int startIndex, bool isHD = false, bool isChannel = false)
{
var queryResult = new YoutubeQuery(100);
// Replace any empty spaces
if (!string.IsNullOrEmpty(keyWord))
keyWord = keyWord.Replace(' ', '+');
// Get website
var s = await ReadWebContent(string.Format(SEARCH, keyWord, startIndex) + (isChannel == true
? AUTHOR + keyWord
: string.Empty));
var doc = XDocument.Load(new StringReader(s));
////////////////////////////////////////////////////////////////////
// Namespaces
XNamespace xmlns = "http://www.w3.org/2005/Atom";
XNamespace media = "http://search.yahoo.com/mrss/";
XNamespace yt = "http://gdata.youtube.com/schemas/2007";
XNamespace opensearch = "http://a9.com/-/spec/opensearch/1.1/";
XNamespace gd = "http://schemas.google.com/g/2005";
///////////////////////////////////////////////////////////////////
queryResult.TotalResult = doc.Root.Element(opensearch + "totalResults").Value;
///////////////////////////////////////////////////////////////////
// Items query
var query =
from entry in doc.Root.Elements(xmlns + "entry")
let grp = entry.Element(media + "group")
select new OnlineItem
{
Provider = "Youtube Stream",
Title = (string)grp.Element(media + "title"),
Description = (string)grp.Element(media + "description"),
File = (string)grp.Element(media + "player").Attribute("url"),
ID = (string)grp.Element(yt + "videoid"),
Image = GetThumbnailUri((string)grp.Element(yt + "videoid"), YouTubeThumbnailSize.Medium).AbsoluteUri,
ImageLarge = GetThumbnailUri((string)grp.Element(yt + "videoid"), YouTubeThumbnailSize.Large).AbsoluteUri,
Duration = ParseDuration((string)grp.Element(yt + "duration").Attribute("seconds")),
Rating = ParseRating((string)entry.Element(gd + "rating").Attribute("average")),
ViewCount = (string)entry.Element(yt + "statistics").Attribute("viewCount"),
Uploaded = ParseUploaded((string)grp.Element(yt + "uploaded"))
};
///////////////////////////////////////////////////////////////////
// Fill items list
if(query.Count() > 0)
queryResult.Items = new ObservableList<OnlineItem>(query.ToList());
// Return results
return queryResult;
}
/// <summary>
/// Parse video uploaded date
/// </summary>
/// <param name="value">date string to parse</param>
/// <returns>uploaded date if available</returns>
private static DateTime? ParseUploaded(string value)
{
DateTime? result = null;
var ulDate = DateTime.MinValue;
DateTime.TryParse(value, CultureInfo.CurrentUICulture, DateTimeStyles.None, out ulDate);
if (ulDate != DateTime.MinValue)
result = ulDate;
return result;
}
/// <summary>
/// Parse video duration
/// </summary>
/// <param name="value">duration string to parse</param>
/// <returns>duration if available</returns>
private static string ParseDuration(string value)
{
string result = string.Empty;
if (!string.IsNullOrEmpty(value))
result = Tools.FormatTime(TimeSpan.FromSeconds(Convert.ToDouble(value)));
return result;
}
/// <summary>
/// Parse video rating
/// </summary>
/// <param name="value">rating string to parse</param>
/// <returns>rating if available</returns>
private static decimal ParseRating(string value)
{
decimal result = 0;
if (!string.IsNullOrEmpty(value))
result = Convert.ToDecimal(value, CultureInfo.InvariantCulture);
return result;
}
/// <summary>
/// Get a specified thumbnail size
/// </summary>
/// <param name="youTubeId">id of the video</param>
/// <param name="size">size of the thumbnail</param>
/// <returns>url of the thumbnail requested</returns>
public static Uri GetThumbnailUri(string youTubeId, YouTubeThumbnailSize size = YouTubeThumbnailSize.Medium)
{
switch (size)
{
case YouTubeThumbnailSize.Small:
return new Uri("http://img.youtube.com/vi/" + youTubeId + "/default.jpg", UriKind.Absolute);
case YouTubeThumbnailSize.Medium:
return new Uri("http://img.youtube.com/vi/" + youTubeId + "/mqdefault.jpg", UriKind.Absolute);
case YouTubeThumbnailSize.HighQuality:
return new Uri("http://img.youtube.com/vi/" + youTubeId + "/hqdefault.jpg", UriKind.Absolute);
case YouTubeThumbnailSize.Large:
return new Uri("http://img.youtube.com/vi/" + youTubeId + "/maxresdefault.jpg", UriKind.Absolute);
case YouTubeThumbnailSize.Standard:
return new Uri("http://img.youtube.com/vi/" + youTubeId + "/sddefault.jpg", UriKind.Absolute);
default:
return new Uri(string.Empty);
}
}
Code:
using AruanTuber_DarkMoon.Lists;
using AruanTuber_DarkMoon.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AruanTuber_DarkMoon.Online
{
public class YoutubeQuery : ViewModelBase
{
private ObservableList<OnlineItem> items;
private string totalResult;
private int totalPages;
private int currentPage;
private int pageItemCount;
/// <summary>
/// Get or Set the current query page
/// </summary>
public int CurrentPage
{
get { return currentPage; }
set { SetProperty(ref currentPage, value); }
}
/// <summary>
/// Get or Set the total of pages available
/// </summary>
public int TotalPages
{
get { return totalPages; }
set { SetProperty(ref totalPages, value); }
}
/// <summary>
/// Get or Set the total amount of items
/// </summary>
public string TotalResult
{
get { return totalResult; }
set { SetProperty(ref totalResult, value); ParseTotalResult(); }
}
/// <summary>
/// Get or Set the items collection
/// </summary>
public ObservableList<OnlineItem> Items
{
get { return items; }
set { SetProperty(ref items, value); }
}
/// <summary>
/// Parse the current amount pages based in the total amount of items
/// </summary>
/// <returns></returns>
private int ParseTotalResult()
{
int result = 0;
if (string.IsNullOrEmpty(TotalResult))
{
int.TryParse(TotalResult, out result);
if (result >= pageItemCount)
TotalPages = result / pageItemCount;
}
return result;
}
/// <summary>
/// Default contructor
/// </summary>
/// <param name="itemCount"></param>
public YoutubeQuery(int itemCount)
{
CurrentPage = 1;
pageItemCount = itemCount;
}
/// <summary>
/// Open next page
/// </summary>
public void NextPage()
{
// TODO: Write logic
}
/// <summary>
/// Open previous page
/// </summary>
public void PreviousPage()
{
// TODO: Write logic
}
}
}