Improved logging and fixed queued failure handling.

This commit is contained in:
Roger Far 2020-04-18 08:07:06 -06:00
parent dc4992a360
commit 731daddc99
12 changed files with 184 additions and 305 deletions

View file

@ -53,7 +53,7 @@ namespace RdtClient.Data.Data
Status = DownloadStatus.PendingDownload Status = DownloadStatus.PendingDownload
}; };
_dataContext.Downloads.Add(download); await _dataContext.Downloads.AddAsync(download);
await _dataContext.SaveChangesAsync(); await _dataContext.SaveChangesAsync();

View file

@ -92,7 +92,7 @@ namespace RdtClient.Data.Data
AutoDelete = autoDelete AutoDelete = autoDelete
}; };
_dataContext.Torrents.Add(torrent); await _dataContext.Torrents.AddAsync(torrent);
await _dataContext.SaveChangesAsync(); await _dataContext.SaveChangesAsync();

View file

@ -0,0 +1,29 @@
using System;
using System.Net;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Http;
namespace RdtClient.Service.Middleware
{
public static class ExceptionMiddlewareExtensions
{
public static void ConfigureExceptionHandler(this IApplicationBuilder app)
{
app.UseExceptionHandler(appError =>
{
appError.Run(async context =>
{
context.Response.StatusCode = (Int32) HttpStatusCode.InternalServerError;
context.Response.ContentType = "application/json";
var contextFeature = context.Features.Get<IExceptionHandlerFeature>();
if (contextFeature != null)
{
await context.Response.WriteAsync(contextFeature.Error.Message);
}
});
});
}
}
}

View file

@ -78,7 +78,7 @@ namespace RdtClient.Service.Services
while (fileStream.Length < response.ContentLength) while (fileStream.Length < response.ContentLength)
{ {
var read = stream.Read(buffer, 0, buffer.Length); var read = await stream.ReadAsync(buffer, 0, buffer.Length);
if (read > 0) if (read > 0)
{ {

View file

@ -231,59 +231,58 @@ namespace RdtClient.Service.Services
var prio = 0; var prio = 0;
foreach (var torrent in torrents) foreach (var torrent in torrents)
{ {
var result = new TorrentInfo var result = new TorrentInfo();
{ result.AddedOn = torrent.RdAdded.ToUnixTimeSeconds();
AddedOn = torrent.RdAdded.ToUnixTimeSeconds(), result.AmountLeft = (Int64) (torrent.RdSize * (100.0 - torrent.RdProgress) / 100.0);
AmountLeft = (Int64) (torrent.RdSize * (100.0 - torrent.RdProgress) / 100.0), result.AutoTmm = false;
AutoTmm = false, result.Availability = 2;
Availability = 2, result.Category = torrent.Category ?? "";
Category = torrent.Category ?? "", result.Completed = (Int64) (torrent.RdSize * (torrent.RdProgress / 100.0));
Completed = (Int64) (torrent.RdSize * (torrent.RdProgress / 100.0)), result.CompletionOn = torrent.RdEnded?.ToUnixTimeSeconds();
CompletionOn = torrent.RdEnded?.ToUnixTimeSeconds(), result.DlLimit = -1;
DlLimit = -1, result.Dlspeed = torrent.RdSpeed ?? 0;
Dlspeed = torrent.RdSpeed ?? 0, result.Downloaded = (Int64) (torrent.RdSize * (torrent.RdProgress / 100.0));
Downloaded = (Int64) (torrent.RdSize * (torrent.RdProgress / 100.0)), result.DownloadedSession = (Int64) (torrent.RdSize * (torrent.RdProgress / 100.0));
DownloadedSession = (Int64) (torrent.RdSize * (torrent.RdProgress / 100.0)), result.Eta = 0;
Eta = 0, result.FlPiecePrio = false;
FlPiecePrio = false, result.ForceStart = false;
ForceStart = false, result.Hash = torrent.Hash;
Hash = torrent.Hash, result.LastActivity = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
LastActivity = DateTimeOffset.UtcNow.ToUnixTimeSeconds(), result.MagnetUri = "";
MagnetUri = "", result.MaxRatio = -1;
MaxRatio = -1, result.MaxSeedingTime = -1;
MaxSeedingTime = -1, result.Name = torrent.RdName;
Name = torrent.RdName, result.NumComplete = 10;
NumComplete = 10, result.NumIncomplete = 0;
NumIncomplete = 0, result.NumLeechs = 100;
NumLeechs = 100, result.NumSeeds = 100;
NumSeeds = 100, result.Priority = ++prio;
Priority = ++prio, result.Progress = (Int64) (torrent.RdProgress / 100.0);
Progress = (Int64) (torrent.RdProgress / 100.0), result.Ratio = 1;
Ratio = 1, result.RatioLimit = 1;
RatioLimit = 1, result.SavePath = savePath;
SavePath = savePath, result.SeedingTimeLimit = 1;
SeedingTimeLimit = 1, result.SeenComplete = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
SeenComplete = DateTimeOffset.UtcNow.ToUnixTimeSeconds(), result.SeqDl = false;
SeqDl = false, result.Size = torrent.RdSize;
Size = torrent.RdSize, result.SuperSeeding = false;
SuperSeeding = false, result.Tags = "";
Tags = "", result.TimeActive = (Int64) (torrent.RdAdded - DateTimeOffset.UtcNow).TotalMinutes;
TimeActive = (Int64) (torrent.RdAdded - DateTimeOffset.UtcNow).TotalMinutes, result.TotalSize = torrent.RdSize;
TotalSize = torrent.RdSize, result.Tracker = "udp://tracker.opentrackr.org:1337";
Tracker = "udp://tracker.opentrackr.org:1337", result.UpLimit = -1;
UpLimit = -1, result.Uploaded = (Int64) (torrent.RdSize * (torrent.RdProgress / 100.0));
Uploaded = (Int64) (torrent.RdSize * (torrent.RdProgress / 100.0)), result.UploadedSession = (Int64) (torrent.RdSize * (torrent.RdProgress / 100.0));
UploadedSession = (Int64) (torrent.RdSize * (torrent.RdProgress / 100.0)), result.Upspeed = torrent.RdSpeed ?? 0;
Upspeed = torrent.RdSpeed ?? 0, result.State = torrent.Status switch
State = torrent.Status switch
{ {
TorrentStatus.RealDebrid => "downloading", TorrentStatus.RealDebrid => "downloading",
TorrentStatus.WaitingForDownload => "downloading", TorrentStatus.WaitingForDownload => "downloading",
TorrentStatus.DownloadQueued => "downloading",
TorrentStatus.Downloading => "downloading", TorrentStatus.Downloading => "downloading",
TorrentStatus.Finished => "pausedUP", TorrentStatus.Finished => "pausedUP",
TorrentStatus.Error => "error", TorrentStatus.Error => "error",
_ => throw new ArgumentOutOfRangeException() _ => throw new ArgumentOutOfRangeException()
}
}; };
results.Add(result); results.Add(result);

View file

@ -72,7 +72,7 @@ namespace RdtClient.Service.Services
{ {
var allTorrents = await torrents.Get(); var allTorrents = await torrents.Get();
allTorrents = allTorrents.Where(m => m.Status == TorrentStatus.WaitingForDownload && m.AutoDownload && m.Downloads.Count == 0) allTorrents = allTorrents.Where(m => (m.Status == TorrentStatus.WaitingForDownload && m.AutoDownload && m.Downloads.Count == 0) || m.Status == TorrentStatus.DownloadQueued)
.ToList(); .ToList();
foreach (var torrent in allTorrents) foreach (var torrent in allTorrents)

View file

@ -33,8 +33,6 @@ namespace RdtClient.Service.Services
{ {
private static RdNetClient _rdtClient; private static RdNetClient _rdtClient;
private static DateTime _rdtLastUpdate = DateTime.UtcNow;
private static readonly SemaphoreSlim SemaphoreSlim = new SemaphoreSlim(1, 1); private static readonly SemaphoreSlim SemaphoreSlim = new SemaphoreSlim(1, 1);
private readonly IDownloads _downloads; private readonly IDownloads _downloads;
private readonly ISettings _settings; private readonly ISettings _settings;
@ -72,13 +70,6 @@ namespace RdtClient.Service.Services
{ {
var torrents = await _torrentData.Get(); var torrents = await _torrentData.Get();
if (DateTime.UtcNow > _rdtLastUpdate)
{
_rdtLastUpdate = DateTime.UtcNow.AddSeconds(10);
torrents = await Update();
}
foreach (var torrent in torrents) foreach (var torrent in torrents)
{ {
foreach (var download in torrent.Downloads) foreach (var download in torrent.Downloads)
@ -204,7 +195,7 @@ namespace RdtClient.Service.Services
public async Task UploadFile(Byte[] bytes, Boolean autoDownload, Boolean autoDelete) public async Task UploadFile(Byte[] bytes, Boolean autoDownload, Boolean autoDelete)
{ {
var torrent = MonoTorrent.Torrent.Load(bytes); var torrent = await MonoTorrent.Torrent.LoadAsync(bytes);
var rdTorrent = await RdNetClient.AddTorrentFileAsync(bytes); var rdTorrent = await RdNetClient.AddTorrentFileAsync(bytes);
@ -233,10 +224,17 @@ namespace RdtClient.Service.Services
var rdTorrent = await RdNetClient.GetTorrentInfoAsync(torrent.RdId); var rdTorrent = await RdNetClient.GetTorrentInfoAsync(torrent.RdId);
var existingDownloads = await _downloads.GetForTorrent(id);
foreach (var link in rdTorrent.Links) foreach (var link in rdTorrent.Links)
{ {
var unrestrictedLink = await RdNetClient.UnrestrictLinkAsync(link); var unrestrictedLink = await RdNetClient.UnrestrictLinkAsync(link);
if (existingDownloads.Any(m => m.Link == unrestrictedLink.Download))
{
continue;
}
await _downloads.Add(torrent.TorrentId, unrestrictedLink.Download); await _downloads.Add(torrent.TorrentId, unrestrictedLink.Download);
} }
} }
@ -244,17 +242,16 @@ namespace RdtClient.Service.Services
public void Reset() public void Reset()
{ {
_rdtClient = null; _rdtClient = null;
_rdtLastUpdate = DateTime.UtcNow;
} }
public async Task<Profile> GetProfile() public async Task<Profile> GetProfile()
{ {
if (_rdtClient == null) if (RdNetClient == null)
{ {
return new Profile(); return new Profile();
} }
var user = await _rdtClient.GetUserAsync(); var user = await RdNetClient.GetUserAsync();
var profile = new Profile var profile = new Profile
{ {

View file

@ -21,8 +21,6 @@ namespace RdtClient.Web.Controllers
[Route("Login")] [Route("Login")]
[HttpPost] [HttpPost]
public async Task<ActionResult> Login([FromBody] AuthControllerLoginRequest request) public async Task<ActionResult> Login([FromBody] AuthControllerLoginRequest request)
{
try
{ {
var user = await _authentication.GetUser(); var user = await _authentication.GetUser();
@ -45,26 +43,14 @@ namespace RdtClient.Web.Controllers
return Ok(); return Ok();
} }
catch(Exception ex)
{
return BadRequest(ex.Message);
}
}
[Route("Logout")] [Route("Logout")]
[HttpPost] [HttpPost]
public async Task<ActionResult> Logout() public async Task<ActionResult> Logout()
{
try
{ {
await _authentication.Logout(); await _authentication.Logout();
return Ok(); return Ok();
} }
catch(Exception ex)
{
return BadRequest(ex.Message);
}
}
} }
public class AuthControllerLoginRequest public class AuthControllerLoginRequest

View file

@ -30,8 +30,6 @@ namespace RdtClient.Web.Controllers
[Route("auth/login")] [Route("auth/login")]
[HttpGet] [HttpGet]
public async Task<ActionResult> AuthLogin([FromQuery] QBAuthLoginRequest request) public async Task<ActionResult> AuthLogin([FromQuery] QBAuthLoginRequest request)
{
try
{ {
var result = await _qBittorrent.AuthLogin(request.UserName, request.Password); var result = await _qBittorrent.AuthLogin(request.UserName, request.Password);
@ -42,11 +40,6 @@ namespace RdtClient.Web.Controllers
return Ok("Fails."); return Ok("Fails.");
} }
catch (Exception ex)
{
return BadRequest(ex.Message);
}
}
[AllowAnonymous] [AllowAnonymous]
[Route("auth/login")] [Route("auth/login")]
@ -61,17 +54,10 @@ namespace RdtClient.Web.Controllers
[HttpGet] [HttpGet]
[HttpPost] [HttpPost]
public async Task<ActionResult> AuthLogout() public async Task<ActionResult> AuthLogout()
{
try
{ {
await _qBittorrent.AuthLogout(); await _qBittorrent.AuthLogout();
return Ok(); return Ok();
} }
catch (Exception ex)
{
return BadRequest(ex.Message);
}
}
[Route("app/version")] [Route("app/version")]
[HttpGet] [HttpGet]
@ -120,17 +106,10 @@ namespace RdtClient.Web.Controllers
[HttpGet] [HttpGet]
[HttpPost] [HttpPost]
public async Task<ActionResult<AppPreferences>> AppPreferences() public async Task<ActionResult<AppPreferences>> AppPreferences()
{
try
{ {
var result = await _qBittorrent.AppPreferences(); var result = await _qBittorrent.AppPreferences();
return Ok(result); return Ok(result);
} }
catch (Exception ex)
{
return BadRequest(ex.Message);
}
}
[Authorize] [Authorize]
[Route("app/setPreferences")] [Route("app/setPreferences")]
@ -146,41 +125,25 @@ namespace RdtClient.Web.Controllers
[HttpGet] [HttpGet]
[HttpPost] [HttpPost]
public async Task<ActionResult<AppPreferences>> AppDefaultSavePath() public async Task<ActionResult<AppPreferences>> AppDefaultSavePath()
{
try
{ {
var result = await _qBittorrent.AppDefaultSavePath(); var result = await _qBittorrent.AppDefaultSavePath();
return Ok(result); return Ok(result);
} }
catch (Exception ex)
{
return BadRequest(ex.Message);
}
}
[Authorize] [Authorize]
[Route("torrents/info")] [Route("torrents/info")]
[HttpGet] [HttpGet]
[HttpPost] [HttpPost]
public async Task<ActionResult<IList<TorrentInfo>>> TorrentsInfo() public async Task<ActionResult<IList<TorrentInfo>>> TorrentsInfo()
{
try
{ {
var result = await _qBittorrent.TorrentInfo(); var result = await _qBittorrent.TorrentInfo();
return Ok(result); return Ok(result);
} }
catch (Exception ex)
{
return BadRequest(ex.Message);
}
}
[Authorize] [Authorize]
[Route("torrents/properties")] [Route("torrents/properties")]
[HttpGet] [HttpGet]
public async Task<ActionResult<IList<TorrentInfo>>> TorrentsProperties([FromQuery] QBTorrentsHashRequest request) public async Task<ActionResult<IList<TorrentInfo>>> TorrentsProperties([FromQuery] QBTorrentsHashRequest request)
{
try
{ {
var result = await _qBittorrent.TorrentProperties(request.Hash); var result = await _qBittorrent.TorrentProperties(request.Hash);
@ -191,11 +154,6 @@ namespace RdtClient.Web.Controllers
return Ok(result); return Ok(result);
} }
catch (Exception ex)
{
return BadRequest(ex.Message);
}
}
[Authorize] [Authorize]
[Route("torrents/properties")] [Route("torrents/properties")]
@ -236,8 +194,6 @@ namespace RdtClient.Web.Controllers
[Route("torrents/delete")] [Route("torrents/delete")]
[HttpGet] [HttpGet]
public async Task<ActionResult> TorrentsDelete([FromQuery] QBTorrentsDeleteRequest request) public async Task<ActionResult> TorrentsDelete([FromQuery] QBTorrentsDeleteRequest request)
{
try
{ {
var hashes = request.Hashes.Split("|"); var hashes = request.Hashes.Split("|");
@ -248,11 +204,6 @@ namespace RdtClient.Web.Controllers
return Ok(); return Ok();
} }
catch (Exception ex)
{
return BadRequest(ex.Message);
}
}
[Authorize] [Authorize]
[Route("torrents/delete")] [Route("torrents/delete")]
@ -266,8 +217,6 @@ namespace RdtClient.Web.Controllers
[Route("torrents/add")] [Route("torrents/add")]
[HttpGet] [HttpGet]
public async Task<ActionResult> TorrentsAdd([FromQuery] QBTorrentsAddRequest request) public async Task<ActionResult> TorrentsAdd([FromQuery] QBTorrentsAddRequest request)
{
try
{ {
var urls = request.Urls.Split("\n"); var urls = request.Urls.Split("\n");
@ -278,11 +227,6 @@ namespace RdtClient.Web.Controllers
return Ok(); return Ok();
} }
catch (Exception ex)
{
return BadRequest(ex.Message);
}
}
[Authorize] [Authorize]
[Route("torrents/add")] [Route("torrents/add")]
@ -314,8 +258,6 @@ namespace RdtClient.Web.Controllers
[Route("torrents/setCategory")] [Route("torrents/setCategory")]
[HttpGet] [HttpGet]
public async Task<ActionResult> TorrentsSetCategory([FromQuery] QBTorrentsSetCategoryRequest request) public async Task<ActionResult> TorrentsSetCategory([FromQuery] QBTorrentsSetCategoryRequest request)
{
try
{ {
var hashes = request.Hashes.Split("|"); var hashes = request.Hashes.Split("|");
@ -326,11 +268,6 @@ namespace RdtClient.Web.Controllers
return Ok(); return Ok();
} }
catch (Exception ex)
{
return BadRequest(ex.Message);
}
}
[Authorize] [Authorize]
[Route("torrents/setCategory")] [Route("torrents/setCategory")]
@ -345,17 +282,10 @@ namespace RdtClient.Web.Controllers
[HttpGet] [HttpGet]
[HttpPost] [HttpPost]
public async Task<ActionResult<IDictionary<String, TorrentCategory>>> TorrentsCategories() public async Task<ActionResult<IDictionary<String, TorrentCategory>>> TorrentsCategories()
{
try
{ {
var categories = await _qBittorrent.TorrentsCategories(); var categories = await _qBittorrent.TorrentsCategories();
return Ok(categories); return Ok(categories);
} }
catch (Exception ex)
{
return BadRequest(ex.Message);
}
}
[Authorize] [Authorize]
[Route("torrents/createCategory")] [Route("torrents/createCategory")]

View file

@ -1,5 +1,4 @@
using System; using System.Collections.Generic;
using System.Collections.Generic;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
@ -25,49 +24,28 @@ namespace RdtClient.Web.Controllers
[HttpGet] [HttpGet]
[Route("")] [Route("")]
public async Task<ActionResult<IList<Setting>>> Get() public async Task<ActionResult<IList<Setting>>> Get()
{
try
{ {
var result = await _settings.GetAll(); var result = await _settings.GetAll();
return Ok(result); return Ok(result);
} }
catch (Exception ex)
{
return BadRequest(ex.Message);
}
}
[HttpPut] [HttpPut]
[Route("")] [Route("")]
public async Task<ActionResult> Update([FromBody] SettingsControllerUpdateRequest request) public async Task<ActionResult> Update([FromBody] SettingsControllerUpdateRequest request)
{
try
{ {
await _settings.Update(request.Settings); await _settings.Update(request.Settings);
_torrents.Reset(); _torrents.Reset();
return Ok(); return Ok();
} }
catch (Exception ex)
{
return BadRequest(ex.Message);
}
}
[HttpGet] [HttpGet]
[Route("Profile")] [Route("Profile")]
public async Task<ActionResult<Profile>> Profile() public async Task<ActionResult<Profile>> Profile()
{
try
{ {
var profile = await _torrents.GetProfile(); var profile = await _torrents.GetProfile();
return Ok(profile); return Ok(profile);
} }
catch (Exception ex)
{
return BadRequest(ex.Message);
}
}
} }
public class SettingsControllerUpdateRequest public class SettingsControllerUpdateRequest

View file

@ -25,23 +25,14 @@ namespace RdtClient.Web.Controllers
[HttpGet] [HttpGet]
[Route("")] [Route("")]
public async Task<ActionResult<IList<Torrent>>> Get() public async Task<ActionResult<IList<Torrent>>> Get()
{
try
{ {
var result = await _torrents.Get(); var result = await _torrents.Get();
return Ok(result); return Ok(result);
} }
catch (Exception ex)
{
return BadRequest(ex.Message);
}
}
[HttpGet] [HttpGet]
[Route("{id}")] [Route("{id}")]
public async Task<ActionResult<Torrent>> Get(Guid id) public async Task<ActionResult<Torrent>> Get(Guid id)
{
try
{ {
var result = await _torrents.GetById(id); var result = await _torrents.GetById(id);
@ -52,19 +43,12 @@ namespace RdtClient.Web.Controllers
return Ok(result); return Ok(result);
} }
catch (Exception ex)
{
return BadRequest(ex.Message);
}
}
[HttpPost] [HttpPost]
[Route("UploadFile")] [Route("UploadFile")]
public async Task<ActionResult> UploadFile([FromForm] IFormFile file, public async Task<ActionResult> UploadFile([FromForm] IFormFile file,
[ModelBinder(BinderType = typeof(JsonModelBinder))] [ModelBinder(BinderType = typeof(JsonModelBinder))]
TorrentControllerUploadFileRequest formData) TorrentControllerUploadFileRequest formData)
{
try
{ {
if (file == null || file.Length <= 0) if (file == null || file.Length <= 0)
{ {
@ -75,7 +59,7 @@ namespace RdtClient.Web.Controllers
await using var memoryStream = new MemoryStream(); await using var memoryStream = new MemoryStream();
fileStream.CopyTo(memoryStream); await fileStream.CopyToAsync(memoryStream);
var bytes = memoryStream.ToArray(); var bytes = memoryStream.ToArray();
@ -83,59 +67,33 @@ namespace RdtClient.Web.Controllers
return Ok(); return Ok();
} }
catch (Exception ex)
{
return BadRequest(ex.Message);
}
}
[HttpPost] [HttpPost]
[Route("UploadMagnet")] [Route("UploadMagnet")]
public async Task<ActionResult> UploadMagnet([FromBody] TorrentControllerUploadMagnetRequest request) public async Task<ActionResult> UploadMagnet([FromBody] TorrentControllerUploadMagnetRequest request)
{
try
{ {
await _torrents.UploadMagnet(request.MagnetLink, request.AutoDownload, request.AutoDelete); await _torrents.UploadMagnet(request.MagnetLink, request.AutoDownload, request.AutoDelete);
return Ok(); return Ok();
} }
catch (Exception ex)
{
return BadRequest(ex.Message);
}
}
[HttpDelete] [HttpDelete]
[Route("{id}")] [Route("{id}")]
public async Task<ActionResult> Delete(Guid id) public async Task<ActionResult> Delete(Guid id)
{
try
{ {
await _torrents.Delete(id); await _torrents.Delete(id);
return Ok(); return Ok();
} }
catch (Exception ex)
{
return BadRequest(ex.Message);
}
}
[HttpGet] [HttpGet]
[Route("Download/{id}")] [Route("Download/{id}")]
public async Task<ActionResult> Download(Guid id) public async Task<ActionResult> Download(Guid id)
{
try
{ {
await _torrents.Download(id); await _torrents.Download(id);
return Ok(); return Ok();
} }
catch (Exception ex)
{
return BadRequest(ex.Message);
}
}
} }
public class TorrentControllerUploadFileRequest public class TorrentControllerUploadFileRequest

View file

@ -12,6 +12,7 @@ using Microsoft.Extensions.Logging;
using RdtClient.Data; using RdtClient.Data;
using RdtClient.Data.Data; using RdtClient.Data.Data;
using RdtClient.Data.Models.Internal; using RdtClient.Data.Models.Internal;
using RdtClient.Service.Middleware;
namespace RdtClient.Web namespace RdtClient.Web
{ {
@ -89,9 +90,10 @@ namespace RdtClient.Web
if (env.IsDevelopment()) if (env.IsDevelopment())
{ {
app.UseCors("Dev"); app.UseCors("Dev");
app.UseDeveloperExceptionPage();
} }
app.ConfigureExceptionHandler();
app.Use(async (context, next) => app.Use(async (context, next) =>
{ {
await next.Invoke(); await next.Invoke();