using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; namespace YTManager.Controllers { [Produces("application/json")] [Route("api/Videos")] public class VideosController : Controller { // Custom return type for API accesses. Done this way to ensure we // always return the expected data regardless of the underlying model. struct Video_ForAPI { // Title of the video. public string Title; // Description of the video. public string Description; // Youtube ID of the video. public string ID; // Thumbnail URL. public string Thumbnail; // Channel youtube ID. public string Channel; // Populate this struct using a model video. public Video_ForAPI(Models.Video video) { Title = video.Title; Description = video.Description; ID = video.YoutubeID; Thumbnail = video.ThumbnailURL; Channel = video.channel?.YoutubeID; } } // Maximum number of entries to return per query. private readonly int max_per_query = 20; // DB context used for all these calls. private readonly MediaDB db; // Constructor to fetch the db context. public VideosController(MediaDB context) => db = context; // Returns the most recent videos. [HttpGet] public async Task GetVideos() { // Get all the relevant videos. var vids = await db.Videos .OrderByDescending(i => i.AddedtoDB) .Take(max_per_query) .ToListAsync(); // Convert them to what we will send out. var converted = vids .Select(v => new Video_ForAPI(v)) .ToList(); // Convert all the videos to what we will send back. return Ok(converted); } // Returns the most recent videos of a channel. [HttpGet("fromchannel/{channelID}")] public async Task Get_Channel_Videos([FromRoute] string channelID) { // Get all the relevant videos. var vids = await db.Videos .Include(v => v.channel) .Where(v => v.channel.YoutubeID == channelID) .OrderByDescending(i => i.AddedtoDB) .Take(max_per_query) .ToListAsync(); // Convert them to what we will send out. var converted = vids .Select(v => new Video_ForAPI(v)) .ToList(); // Convert all the videos to what we will send back. return Ok(converted); } } }