using Microsoft.AspNetCore.Mvc; using PhilExampleCrawler.Common.Models; using PhilExampleCrawler.Core; using PhilExampleCrawler.DataBase; using PhilExampleCrawler.DataBase.Models; using WebAPI.Interfaces; using System.Linq; namespace WebAPI.Controllers { [ApiController] [Route("[controller]/[action]")] public class CrawlSessionController : ControllerBase { private readonly ILogger _logger; private readonly ICrawlScheduler> _scheduler; private readonly HttpClient _httpClient; public CrawlSessionController(ILogger logger, ICrawlScheduler> scheduler, IHttpClientFactory httpClientFactory) { _logger = logger; _scheduler = scheduler; _httpClient = httpClientFactory.CreateClient(); } [HttpGet] public async Task?> GetCrawlSessionsAsync(int userID) { if (userID < 1) return null; var user = await ThreadSafeCache.GetUserAsync(userID); return user?.CrawlSessions; } [HttpGet] public async Task?> GetLatestInsertionAsync(int userID, int? limit) { if (userID < 1) return null; var ins = await ThreadSafeCache.GetInsertions(userID, limit ?? 5); return ins; } [HttpPost] public async Task RegisterCrawlSessionAsync(int userID, CrawlSession cs) { if (userID < 1) return null; CrawlSession? sess = await ThreadSafeCache.AddCrawlSessionAsync(userID, cs); if (sess != null) _scheduler.AddTask(sess.ID, new BaseCrawler_Best(sess, _httpClient).CrawlAsync); return sess; } [HttpPost] public async Task UpdateCrawlSessionAsync(int userID, CrawlSession cs) { if (userID < 1) return false; bool updated = await ThreadSafeCache.UpdateCrawlSessionAsync(userID, cs); return updated; } [HttpDelete] public async Task DeleteCrawlSessionAsync(int crawlSessionID) { if (crawlSessionID < 1) return false; bool deleted = await ThreadSafeCache.RemoveCrawlSessionAsync(crawlSessionID); _scheduler.RemoveTask(crawlSessionID); return deleted; } } }