Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Move CheckTraktToken to a Job #1201

Merged
merged 3 commits into from
Nov 17, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 5 additions & 3 deletions Shoko.Server/Providers/TraktTV/TraktTVHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -235,7 +235,7 @@ private Dictionary<string, string> BuildRequestHeaders()

#region Authorization

public void RefreshAuthToken()
public bool RefreshAuthToken()
{
var settings = _settingsProvider.GetSettings();
try
Expand All @@ -248,7 +248,7 @@ public void RefreshAuthToken()
settings.TraktTv.RefreshToken = string.Empty;
settings.TraktTv.TokenExpirationDate = string.Empty;

return;
return false;
}

var token = new TraktV2RefreshToken { refresh_token = settings.TraktTv.RefreshToken };
Expand All @@ -272,7 +272,7 @@ public void RefreshAuthToken()

settings.TraktTv.TokenExpirationDate = expireDate.ToString();

return;
return true;
}

settings.TraktTv.AuthToken = string.Empty;
Expand All @@ -286,11 +286,13 @@ public void RefreshAuthToken()
settings.TraktTv.TokenExpirationDate = string.Empty;

_logger.LogError(ex, "Error in TraktTVHelper.RefreshAuthToken");
return false;
revam marked this conversation as resolved.
Show resolved Hide resolved
}
finally
{
Utils.SettingsProvider.SaveSettings();
}
return false;
}

#endregion
Expand Down
70 changes: 70 additions & 0 deletions Shoko.Server/Scheduling/Jobs/Trakt/CheckTraktTokenJob.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Shoko.Server.Scheduling.Acquisition.Attributes;
using Shoko.Server.Scheduling.Attributes;
using Shoko.Server.Scheduling.Concurrency;
using Shoko.Server.Settings;
using Shoko.Server.Providers.TraktTV;

namespace Shoko.Server.Scheduling.Jobs.Trakt;

[DatabaseRequired]
[NetworkRequired]
[DisallowConcurrencyGroup(ConcurrencyGroups.Trakt)]
[JobKeyGroup(JobKeyGroup.Trakt)]
public class CheckTraktTokenJob : BaseJob
{
private readonly ISettingsProvider _settingsProvider;
private readonly TraktTVHelper _traktHelper;

public bool ForceRefresh;
public override string TypeName => "Check and Refresh Trakt Token";
public override string Title => "Checking and Refreshing Trakt Token";

public override Task Process()
{
try
{
_logger.LogInformation("Processing {Job} (ForceRefresh: {ForceRefresh})", nameof(CheckTraktTokenJob), ForceRefresh);
var settings = _settingsProvider.GetSettings();
if (!settings.TraktTv.Enabled || string.IsNullOrEmpty(settings.TraktTv.TokenExpirationDate))
{
_logger.LogInformation("Trakt is not enabled or no token expiration date is set");
return Task.CompletedTask;
}

// Convert the Unix timestamp to DateTime
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should also probably add a check if the date is in the past, and unset the token if it is instead of trying to refresh.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If everybody is okay with my reply below, I'll mark this as resolved

var expirationDate = DateTimeOffset.FromUnixTimeSeconds(long.Parse(settings.TraktTv.TokenExpirationDate)).DateTime;

// Check if the token needs refreshing
if (ForceRefresh || DateTime.Now.Add(TimeSpan.FromDays(45)) >= expirationDate)
{
if (_traktHelper.RefreshAuthToken())
{
var newExpirationDate = DateTimeOffset.FromUnixTimeSeconds(long.Parse(settings.TraktTv.TokenExpirationDate)).DateTime;
_logger.LogInformation("Trakt token refreshed successfully. New expiry date: {Date}", newExpirationDate);
}
revam marked this conversation as resolved.
Show resolved Hide resolved
}
else
{
_logger.LogInformation("Trakt token is still valid. Expiry date: {Date}", expirationDate);
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Error in {Job}: {Ex}", nameof(CheckTraktTokenJob), ex);
}

return Task.CompletedTask;
}

public CheckTraktTokenJob(ISettingsProvider settingsProvider, TraktTVHelper traktHelper)
{
_settingsProvider = settingsProvider;
_traktHelper = traktHelper;
}

protected CheckTraktTokenJob() { }
}
3 changes: 3 additions & 0 deletions Shoko.Server/Scheduling/QuartzStartup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
using Shoko.Server.Scheduling.Jobs;
using Shoko.Server.Scheduling.Jobs.Actions;
using Shoko.Server.Scheduling.Jobs.Shoko;
using Shoko.Server.Scheduling.Jobs.Trakt;
using Shoko.Server.Server;
using Shoko.Server.Utilities;

Expand All @@ -31,6 +32,8 @@ public static async Task ScheduleRecurringJobs(bool replace)
// StartJobNow gives a priority of 10. We'll give it 20 to be even higher priority
await ScheduleRecurringJob<CheckNetworkAvailabilityJob>(
triggerConfig: t => t.WithPriority(20).WithSimpleSchedule(tr => tr.WithIntervalInMinutes(30).RepeatForever()).StartNow(), replace: true, keepSchedule: false);
await ScheduleRecurringJob<CheckTraktTokenJob>(
triggerConfig: t => t.WithPriority(20).WithSimpleSchedule(tr => tr.WithIntervalInMinutes(720).RepeatForever()).StartNow(), replace: true, keepSchedule: false);

// TODO the other schedule-based jobs that are on timers
}
Expand Down
1 change: 0 additions & 1 deletion Shoko.Server/Server/ShokoServer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -412,7 +412,6 @@ private static void AutoUpdateTimer_Elapsed(object sender, ElapsedEventArgs e)
actionService.CheckForAnimeUpdate().GetAwaiter().GetResult();
actionService.CheckForMyListSyncUpdate(false).GetAwaiter().GetResult();
actionService.CheckForTraktAllSeriesUpdate(false).GetAwaiter().GetResult();
actionService.CheckForTraktTokenUpdate(false);
actionService.CheckForAniDBFileUpdate(false).GetAwaiter().GetResult();
}

Expand Down
35 changes: 0 additions & 35 deletions Shoko.Server/Services/ActionService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1018,41 +1018,6 @@ public async Task CheckForTraktAllSeriesUpdate(bool forceRefresh)
_traktHelper.ScanForMatches();
}

public void CheckForTraktTokenUpdate(bool forceRefresh)
{
try
{
var settings = _settingsProvider.GetSettings();
if (!settings.TraktTv.Enabled || string.IsNullOrEmpty(settings.TraktTv.TokenExpirationDate)) return;

// Convert the Unix timestamp to DateTime directly
var expirationDate = DateTimeOffset.FromUnixTimeSeconds(long.Parse(settings.TraktTv.TokenExpirationDate)).DateTime;

// Check if force refresh is requested or the token is expired
if (forceRefresh || DateTime.Now.Add(TimeSpan.FromDays(45)) >= expirationDate)
{
_traktHelper.RefreshAuthToken();

// Update the last token refresh timestamp
var schedule = RepoFactory.ScheduledUpdate.GetByUpdateType((int)ScheduledUpdateType.TraktToken)
?? new ScheduledUpdate { UpdateType = (int)ScheduledUpdateType.TraktToken, UpdateDetails = string.Empty };

schedule.LastUpdate = DateTime.Now;
RepoFactory.ScheduledUpdate.Save(schedule);

_logger.LogInformation("Trakt token refreshed successfully. Expiry date: {Date}", expirationDate);
}
else
{
_logger.LogInformation("Trakt token is still valid. Expiry date: {Date}", expirationDate);
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Error in CheckForTraktTokenUpdate: {Ex}", ex);
}
}

public async Task CheckForAniDBFileUpdate(bool forceRefresh)
{
var settings = _settingsProvider.GetSettings();
Expand Down