60 lines
2.3 KiB
C#
60 lines
2.3 KiB
C#
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()
|
|
{
|
|
Console.WriteLine("Startnig job ...");
|
|
|
|
// YT API access key
|
|
var youtubeService = new YouTubeService(new Google.Apis.Services.BaseClientService.Initializer()
|
|
{
|
|
ApiKey = "AIzaSyCuIYkMc5SktlnXRXNaDf2ObX-fQvtWCnQ",
|
|
ApplicationName = "testingapppp"
|
|
});
|
|
|
|
// Get all the channels to update.
|
|
var ops = new DbContextOptionsBuilder<MediaDB>();
|
|
ops.UseNpgsql(YTManager.Startup.dbstr);
|
|
using (var dbcontext = new MediaDB(ops.Options)) {
|
|
var channels = dbcontext.Channels.ToList();
|
|
|
|
// Get all the most recent videos for each channel.
|
|
channels.ForEach(ch => {
|
|
// Get channel videos from youtube.
|
|
var query = youtubeService.Activities.List("snippet");
|
|
query.ChannelId = ch.YTChannelID;
|
|
var response = query.Execute();
|
|
|
|
// Get all videos which aren't already in the DB.
|
|
var notindb = response.Items
|
|
.Where(i => !dbcontext.Videos.Any(dbvid => dbvid.YTVideoID != i.Id))
|
|
.Select(newvid =>
|
|
new Models.Video {
|
|
Title = newvid.Snippet.Title,
|
|
Description = newvid.Snippet.Description,
|
|
YTVideoID = newvid.Id,
|
|
Uploaded = newvid.Snippet.PublishedAt.GetValueOrDefault(),
|
|
AddedtoDB = DateTime.Now,
|
|
Channel = ch,
|
|
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();
|
|
});
|
|
}
|
|
}
|
|
}
|
|
}
|