72 lines
2.0 KiB
C#
72 lines
2.0 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Threading.Tasks;
|
|
using DBConnection;
|
|
using DBConnection.Models;
|
|
using DBConnection.Repositories;
|
|
using DBConnection.Repositories.Interfaces;
|
|
using Microsoft.AspNetCore.Http;
|
|
using Microsoft.AspNetCore.Mvc;
|
|
using WebNovelPortalAPI.DTO;
|
|
using WebNovelPortalAPI.Scrapers;
|
|
|
|
namespace WebNovelPortalAPI.Controllers
|
|
{
|
|
[Route("api/[controller]")]
|
|
[ApiController]
|
|
public class NovelController : ControllerBase
|
|
{
|
|
private readonly INovelRepository _novelRepository;
|
|
private readonly IEnumerable<IScraper> _scrapers;
|
|
|
|
public NovelController(IEnumerable<IScraper> scrapers, INovelRepository novelRepository)
|
|
{
|
|
_scrapers = scrapers;
|
|
_novelRepository = novelRepository;
|
|
}
|
|
|
|
private IScraper? MatchScraper(string novelUrl)
|
|
{
|
|
return _scrapers.FirstOrDefault(i => i.MatchesUrl(novelUrl));
|
|
}
|
|
|
|
[HttpGet]
|
|
[Route("{guid:guid}")]
|
|
public async Task<Novel?> GetNovel(Guid guid)
|
|
{
|
|
return await _novelRepository.GetNovel(guid);
|
|
}
|
|
|
|
[HttpGet]
|
|
public async Task<List<Novel>> GetNovels()
|
|
{
|
|
return (await _novelRepository.GetAllIncluded()).ToList();
|
|
}
|
|
|
|
[HttpPost]
|
|
[Route("scrapeNovel")]
|
|
public async Task<IActionResult> ScrapeNovel(ScrapeNovelRequest request)
|
|
{
|
|
var scraper = MatchScraper(request.NovelUrl);
|
|
if (scraper == null)
|
|
{
|
|
return BadRequest("Invalid url, no valid scraper configured");
|
|
}
|
|
|
|
Novel novel;
|
|
try
|
|
{
|
|
novel = scraper.ScrapeNovel(request.NovelUrl);
|
|
}
|
|
catch (Exception e)
|
|
{
|
|
return StatusCode(500, e);
|
|
}
|
|
|
|
var novelUpload = await _novelRepository.Upsert(novel);
|
|
return Ok(novelUpload);
|
|
}
|
|
}
|
|
}
|