Selector/Selector.CLI/Jobs/ScrobbleWatcherJob.cs

97 lines
3.1 KiB
C#
Raw Normal View History

2022-02-25 21:07:22 +00:00
using IF.Lastfm.Core.Api;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Quartz;
using Selector.Model;
using Selector.Model.Extensions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Selector.CLI.Jobs
{
[DisallowConcurrentExecution]
2022-02-25 21:07:22 +00:00
public class ScrobbleWatcherJob : IJob
{
private readonly ILogger<ScrobbleWatcherJob> logger;
private readonly ILoggerFactory loggerFactory;
private readonly IUserApi userApi;
private readonly IScrobbleRepository scrobbleRepo;
private readonly ApplicationDbContext db;
private readonly ScrobbleWatcherJobOptions options;
private static object databaseLock = new();
public bool IsFull { get; set; }
2022-02-25 21:07:22 +00:00
public ScrobbleWatcherJob(
IUserApi _userApi,
IScrobbleRepository _scrobbleRepo,
ApplicationDbContext _db,
IOptions<ScrobbleWatcherJobOptions> _options,
ILogger<ScrobbleWatcherJob> _logger,
ILoggerFactory _loggerFactory)
{
logger = _logger;
loggerFactory = _loggerFactory;
userApi = _userApi;
scrobbleRepo = _scrobbleRepo;
db = _db;
options = _options.Value;
}
public async Task Execute(IJobExecutionContext context)
{
try
2022-02-25 21:07:22 +00:00
{
logger.LogInformation("Starting scrobble watching job");
2022-02-25 21:07:22 +00:00
var users = db.Users
.AsEnumerable()
.Where(u => u.ScrobbleSavingEnabled())
.ToArray();
2022-02-25 21:07:22 +00:00
foreach (var user in users)
2022-02-25 21:07:22 +00:00
{
logger.LogInformation("Saving scrobbles for {}/{}", user.UserName, user.LastFmUsername);
2022-02-25 21:07:22 +00:00
DateTime? from = null;
if (options.From is not null && !IsFull)
2022-02-25 21:07:22 +00:00
{
from = options.From.Value.ToUniversalTime();
}
var saver = new ScrobbleSaver(
userApi,
new()
{
User = user,
InterRequestDelay = options.InterRequestDelay,
From = from,
PageSize = options.PageSize,
DontAdd = false,
DontRemove = false,
SimultaneousConnections = options.Simultaneous
},
scrobbleRepo,
loggerFactory.CreateLogger<ScrobbleSaver>(),
loggerFactory,
databaseLock);
2022-02-25 21:07:22 +00:00
await saver.Execute(context.CancellationToken);
2022-02-25 21:07:22 +00:00
logger.LogInformation("Finished scrobbles for {}/{}", user.UserName, user.LastFmUsername);
}
}
catch (Exception ex)
{
logger.LogError(ex, "Error occured while saving scrobbles");
2022-02-25 21:07:22 +00:00
}
}
}
}