80 lines
2.6 KiB
C#
80 lines
2.6 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Threading.Tasks;
|
|
using Microsoft.AspNetCore.Http;
|
|
using Microsoft.AspNetCore.Mvc;
|
|
using Microsoft.EntityFrameworkCore;
|
|
using YTManager;
|
|
using YTManager.Models;
|
|
|
|
namespace YTManager.Controllers {
|
|
[Produces("application/json")]
|
|
[Route("api/Videos")]
|
|
public class VideosController : Controller {
|
|
// DB context used for all these calls.
|
|
private readonly MediaDB db;
|
|
|
|
// Constructor to fetch the db context.
|
|
public VideosController(MediaDB context) => db = context;
|
|
|
|
// GET: api/Videos
|
|
[HttpGet]
|
|
public async Task<List<Video>> GetVideos() {
|
|
return await db.Videos.OrderByDescending(i => i.AddedtoDB).ToListAsync();
|
|
}
|
|
|
|
// GET: api/Videos/5
|
|
[HttpGet("{id}")]
|
|
public async Task<IActionResult> GetVideo([FromRoute] long id){
|
|
// Check if we were able to parse.
|
|
if (!ModelState.IsValid) return BadRequest(ModelState);
|
|
|
|
// Attempt to get the video from the database.
|
|
var video = await db.Videos.SingleOrDefaultAsync(m => m.key == id);
|
|
|
|
// If the video wasn't found then send back not foud.
|
|
if (video == null)
|
|
return NotFound();
|
|
else
|
|
return Ok(video);
|
|
}
|
|
|
|
// POST: api/Videos
|
|
[HttpPost]
|
|
public async Task<IActionResult> PostVideo([FromBody] Video video){
|
|
// Check if we were able to parse.
|
|
if (!ModelState.IsValid) return BadRequest(ModelState);
|
|
|
|
// Check if such a database exists already.
|
|
if (await db.Videos.AnyAsync(d => d.YTVideoID == video.YTVideoID))
|
|
return BadRequest();
|
|
|
|
// Add our video to the database and tell db to update.
|
|
db.Videos.Add(video);
|
|
await db.SaveChangesAsync();
|
|
|
|
// Say that the creation was succesfull.
|
|
return Ok();
|
|
}
|
|
|
|
// DELETE: api/Videos/alfkeo4f5
|
|
[HttpDelete("{ytid}")]
|
|
public async Task<IActionResult> DeleteVideo([FromRoute] string YTVideoID){
|
|
// Check if we were able to parse.
|
|
if (!ModelState.IsValid) return BadRequest(ModelState);
|
|
|
|
// Attempt to find the video.
|
|
var video = await db.Videos.SingleOrDefaultAsync(m => m.YTVideoID == YTVideoID);
|
|
|
|
// Check if such a database exists already.
|
|
if (video == null)
|
|
return NotFound();
|
|
|
|
// Remove.
|
|
db.Videos.Remove(video);
|
|
await db.SaveChangesAsync();
|
|
return Ok(video);
|
|
}
|
|
}
|
|
} |