BackEnd/YTManager/Controllers/Videos.cs

97 lines
3.3 KiB
C#
Raw Normal View History

using System.Collections.Generic;
using System.Linq;
2018-02-18 01:29:25 +00:00
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;
2018-02-24 06:10:12 +00:00
// Channel on youtube that owns this video
public string Channel;
2018-02-28 23:33:40 +00:00
// 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;
2018-02-24 06:10:12 +00:00
Channel = video.Channel.Title;
2018-02-28 23:33:40 +00:00
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;
2018-02-18 01:29:25 +00:00
// 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.
2018-02-18 01:29:25 +00:00
[HttpGet]
public async Task<IActionResult> GetVideos() {
// Get all the relevant videos.
var vids = await db.Videos
.OrderByDescending(i => i.AddedToYT)
.Take(max_per_query)
2018-02-28 23:33:40 +00:00
.Include(v => v.Channel)
.Include(v => v.Tags)
.ToListAsync();
2018-02-18 01:29:25 +00:00
// 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);
}
2018-02-18 01:29:25 +00:00
// Returns the most recent videos of a channel.
2018-02-24 06:10:12 +00:00
[HttpGet("fromchannel/{channelName}")]
public async Task<IActionResult> Get_Channel_Videos([FromRoute] string channelName) {
// Get all the relevant videos.
var vids = await db.Videos
2018-02-24 06:10:12 +00:00
.Where(v => v.Channel.Title == channelName)
.OrderByDescending(i => i.AddedToYT)
.Take(max_per_query)
2018-02-28 23:33:40 +00:00
.Include(v => v.Channel)
.Include(v => v.Tags)
.ToListAsync();
2018-02-18 01:29:25 +00:00
// Convert them to what we will send out.
var converted = vids
.Select(v => new Video_ForAPI(v))
.ToList();
2018-02-18 01:29:25 +00:00
// Convert all the videos to what we will send back.
return Ok(converted);
2018-02-18 01:29:25 +00:00
}
}
}