BackEnd/YTManager/Controllers/Videos.cs

99 lines
3.3 KiB
C#

using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
namespace YTManager.Controllers {
[Produces("application/json")]
[Route("api/Videos")]
[EnableCors("AllowAllOrigins")]
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 on youtube that owns this video
public string Channel;
// Duration of the video in seconds.
public int Seconds;
// What tags are relevant with this video.
public List<string> Tags;
// 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.Title;
Seconds = (int)video.Duration.TotalSeconds;
Tags = video.Tags?.Select(t => t.Name).ToList();
}
}
// Maximum number of entries to return per query.
private readonly int max_per_query = 18;
// 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<IActionResult> GetVideos() {
// Get all the relevant videos.
var vids = await db.Videos
.OrderByDescending(i => i.AddedToYT)
.Take(max_per_query)
.Include(v => v.Channel)
.Include(v => v.Tags)
.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/{channelName}")]
public async Task<IActionResult> Get_Channel_Videos([FromRoute] string channelName) {
// Get all the relevant videos.
var vids = await db.Videos
.Where(v => v.Channel.Title == channelName)
.OrderByDescending(i => i.AddedToYT)
.Take(max_per_query)
.Include(v => v.Channel)
.Include(v => v.Tags)
.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);
}
}
}