BackEnd/YTManager/Tasks/FetchVideos.cs

68 lines
2.8 KiB
C#
Raw Normal View History

2017-09-01 08:55:02 +00:00
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Google.Apis.YouTube.v3;
using Microsoft.EntityFrameworkCore;
namespace YTManager.Tasks
{
public class FetchVideos
{
public static void run(string youtubechannelIDstr = "")
2017-09-01 08:55:02 +00:00
{
// YT API access key
var youtubeService = new YouTubeService(new Google.Apis.Services.BaseClientService.Initializer()
{
ApiKey = "AIzaSyCuIYkMc5SktlnXRXNaDf2ObX-fQvtWCnQ",
ApplicationName = "testingapppp"
});
2018-02-18 19:06:16 +00:00
// Get the interface to the database.
2017-09-01 08:55:02 +00:00
var ops = new DbContextOptionsBuilder<MediaDB>();
ops.UseInMemoryDatabase(databaseName: "testdb");
2018-02-18 19:06:16 +00:00
// Get all the channels to update.
2017-09-01 08:55:02 +00:00
using (var dbcontext = new MediaDB(ops.Options)) {
// Get all the potential relevant channels.
List<Models.Channel> channels;
if (youtubechannelIDstr == "")
channels = dbcontext.Channels.ToList();
else
channels = dbcontext.Channels.Where(c => c.YTChannelID == youtubechannelIDstr).ToList();
2017-09-01 08:55:02 +00:00
// Get all the most recent videos for each channel.
channels.ForEach(ch => {
// Get channel videos from youtube.
2017-09-03 01:05:50 +00:00
var query = youtubeService.Search.List("snippet");
2017-09-01 08:55:02 +00:00
query.ChannelId = ch.YTChannelID;
2017-09-03 07:24:00 +00:00
query.Order = SearchResource.ListRequest.OrderEnum.Date;
2017-09-03 01:05:50 +00:00
query.MaxResults = 50;
2017-09-01 08:55:02 +00:00
var response = query.Execute();
2018-02-18 01:29:25 +00:00
// Get all videos which aren't already in the DB based on the ytid.
2017-09-01 08:55:02 +00:00
var notindb = response.Items
2017-09-03 01:05:50 +00:00
.Where(i => i.Id.Kind == "youtube#video")
.Where(i => !dbcontext.Videos.Any(dbvid => dbvid.YTVideoID == i.Id.VideoId))
2017-09-01 08:55:02 +00:00
.Select(newvid =>
new Models.Video {
Title = newvid.Snippet.Title,
Description = newvid.Snippet.Description,
2017-09-03 01:05:50 +00:00
YTVideoID = newvid.Id.VideoId,
2018-02-18 01:29:25 +00:00
AddedToYT = newvid.Snippet.PublishedAt.GetValueOrDefault(),
2017-09-01 08:55:02 +00:00
AddedtoDB = DateTime.Now,
2018-02-18 01:29:25 +00:00
channel = ch,
2017-09-01 08:55:02 +00:00
ThumbnailURL = newvid.Snippet.Thumbnails.Medium.Url
}).ToList();
// Add all videos not already in the database over.
notindb.ForEach(newvid => dbcontext.Videos.Add(newvid));
// And save since we are done.
dbcontext.SaveChanges();
});
}
}
}
}