Added duration and tags to videos

This commit is contained in:
2018-02-28 18:33:40 -05:00
parent e140cae317
commit ccef5fee0c
7 changed files with 192 additions and 10 deletions

View File

@ -8,7 +8,7 @@ using Microsoft.EntityFrameworkCore;
namespace YTManager.Tasks {
public class FetchVideos {
// Get a bunch of videos from youtube that the channel generated.
private static async Task<List<Models.Video>> Get_YTVideos(string channelID) {
public static async Task<List<Models.Video>> Get_YTVideos(string channelID, int max = 50) {
// YT API access key
var youtubeService = new YouTubeService(new Google.Apis.Services.BaseClientService.Initializer()
{
@ -16,15 +16,18 @@ namespace YTManager.Tasks {
ApplicationName = "testingapppp"
});
// Max cannot be larger than 50, so clamp it.
max = max > 50 ? 50 : max;
// Search youtube for all the relevant data of the channel.
var query = youtubeService.Search.List("snippet");
query.ChannelId = channelID;
query.Order = SearchResource.ListRequest.OrderEnum.Date;
query.MaxResults = 50;
var response = await query.ExecuteAsync();
var videos_query = youtubeService.Search.List("snippet");
videos_query.ChannelId = channelID;
videos_query.Order = SearchResource.ListRequest.OrderEnum.Date;
videos_query.MaxResults = max;
var videos_response = await videos_query.ExecuteAsync();
// Convert the response into models.
return response.Items?
var videos = videos_response.Items?
.Where(i => i.Id.Kind == "youtube#video")
.Select(newvid => new Models.Video
{
@ -35,6 +38,28 @@ namespace YTManager.Tasks {
AddedtoDB = DateTime.Now,
ThumbnailURL = newvid.Snippet.Thumbnails.Medium.Url
}).ToList();
// Search youtube to get the length and tags for each video.
var duration_query = youtubeService.Videos.List("contentDetails,snippet");
duration_query.Id = string.Join(',', videos.Select(v => v.YoutubeID));
var duration_response = await duration_query.ExecuteAsync();
// Pair each video with the result.
foreach(var contentdetail in duration_response.Items.Where(i => i.Kind == "youtube#video")){
var vid = videos.Single(v => v.YoutubeID == contentdetail.Id);
// Yes, really, ISO8601 time span => c#'s TimeSpan is not in TimeSpan, it's in xmlconvert! Wtf?!
vid.Duration = System.Xml.XmlConvert.ToTimeSpan(contentdetail.ContentDetails.Duration);
// Copy over all the created tags if any tags were provided.
if (contentdetail.Snippet.Tags == null)
vid.Tags = new List<Models.Tag>();
else
vid.Tags = contentdetail.Snippet.Tags.Select(t => new Models.Tag { Name = t }).ToList();
}
// Send back the parsed vids.
return videos;
}
// Gets some info about a youtube channel.