using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using System; namespace YTManager.Controllers { [Produces("application/json")] [Route("api/Channels")] public class ChannelsController : Controller { // Custom return type for API accesses. Done this way to ensure we // always return the expected data regardless of the underlying model. struct Channel_ForAPI { public string Title; public string Description; public string ID; public List User_Tags; public List Video_IDs; public Channel_ForAPI(Models.Channel c) { Title = c.Title; Description = c.Description; ID = c.YoutubeID; Video_IDs = c.Videos.Select(v => v.YoutubeID).ToList(); User_Tags = c.UserTags == null ? new List() : c.UserTags.ToList(); } } // DB context used for all these calls. private readonly MediaDB db; // Maximum number of channels to return per query. private readonly int max_per_query = 10; // Constructor to fetch the db context. public ChannelsController(MediaDB context) => db = context; // Returns the most recently added channels. [HttpGet] public async Task Get() { // Log this to the terminal. Console.WriteLine($"{DateTime.Now} == Channels GET"); // Get all the relevant channels. var chanels = await db.Channels .Include(c => c.Videos) .OrderByDescending(i => i.AddedtoDB) .Take(max_per_query) .ToListAsync(); // Convert them to what we will send out. var converted = chanels .Select(ch => new Channel_ForAPI(ch)) .ToList(); // Convert all the videos to what we will send back. return Ok(converted); } [HttpPost("{channelid}")] public async Task PostChannel([FromRoute] string channelid) { Console.WriteLine($"{DateTime.Now} == Channels POST -> {channelid}"); // Verify the channel looks resonable. var expected_len = "UCyS4xQE6DK4_p3qXQwJQAyA".Length; if (channelid.Length != expected_len) return BadRequest($"Length should be {expected_len} but is {channelid.Length}"); // Only add it to the databse if it's not in there already. if (db.Channels.Any(c => c.YoutubeID == channelid)) return BadRequest($"Channel {channelid} is already in DB!"); // Get the channel contents from youtube. var channel = await Tasks.FetchVideos.Get_YTChannel(channelid); // Add it to the databse. await db.Channels.AddAsync(channel); await db.SaveChangesAsync(); // Say all went ok. return Ok(); } } }