Skip to content

Commit

Permalink
Merge pull request #1137 from pkuehnel/fix/backendTokenGeneration
Browse files Browse the repository at this point in the history
fix(TeslaFleetApiSerice): can get token from backend again
  • Loading branch information
pkuehnel authored Feb 21, 2024
2 parents c6a64ba + c7ad55e commit 9e03ac5
Show file tree
Hide file tree
Showing 4 changed files with 21 additions and 8 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,7 @@ public PossibleIssues(IssueKeys issueKeys)
issueKeys.FleetApiTokenRequestExpired, CreateIssue("The Tesla token could not be received.",
IssueType.Error,
"Open the <a href=\"/BaseConfiguration\">Base Configuration</a> and request a new token.",
"If this issue keeps occuring, feel free to open an issue <a href=\"https://github.com/pkuehnel/TeslaSolarCharger/issues\" target=\"_blank\">on Github</a> including the last 5 chars of your installation ID (bottom of the page). Do NOT include the whole ID."
"If this issue keeps occuring, feel free to open an issue <a href=\"https://github.com/pkuehnel/TeslaSolarCharger/issues\" target=\"_blank\">on Github</a> including the first 10 chars of your installation ID (bottom of the page). Do NOT include the whole ID."
)
},
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ public class FleetApiTokenRefreshJob(ILogger<FleetApiTokenRefreshJob> logger,
public async Task Execute(IJobExecutionContext context)
{
logger.LogTrace("{method}({context})", nameof(Execute), context);
await service.RefreshFleetApiRequestsAreAllowed().ConfigureAwait(false);
await service.GetNewTokenFromBackend().ConfigureAwait(false);
await service.RefreshTokensIfAllowedAndNeeded().ConfigureAwait(false);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,6 @@ public interface ITeslaFleetApiService
Task<bool> IsFleetApiProxyNeededInDatabase();
Task RefreshCarData();
Task RefreshTokensIfAllowedAndNeeded();
Task RefreshFleetApiRequestsAreAllowed();

}
24 changes: 17 additions & 7 deletions TeslaSolarCharger/Server/Services/TeslaFleetApiService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
using TeslaSolarCharger.Shared.Contracts;
using TeslaSolarCharger.Shared.Dtos;
using TeslaSolarCharger.Shared.Dtos.Contracts;
using TeslaSolarCharger.Shared.Dtos.Settings;
using TeslaSolarCharger.Shared.Enums;
using TeslaSolarCharger.SharedBackend.Contracts;
using TeslaSolarCharger.SharedBackend.Dtos;
Expand Down Expand Up @@ -578,7 +579,7 @@ public async Task GetNewTokenFromBackend()
logger.LogError("Token has not been requested. Fleet API currently not working");
return;
}
if (tokenRequestedDate < dateTimeProvider.UtcNow().Add(TimeSpan.MaxValue))
if (tokenRequestedDate < dateTimeProvider.UtcNow().Subtract(constants.MaxTokenRequestWaitTime))
{
logger.LogError("Last token request is too old. Request a new token.");
return;
Expand All @@ -605,7 +606,6 @@ public async Task GetNewTokenFromBackend()
public async Task RefreshTokensIfAllowedAndNeeded()
{
logger.LogTrace("{method}()", nameof(RefreshTokensIfAllowedAndNeeded));
settings.AllowUnlimitedFleetApiRequests = await CheckIfFleetApiRequestsAreAllowed().ConfigureAwait(false);
var tokens = await teslaSolarChargerContext.TeslaTokens.ToListAsync().ConfigureAwait(false);
if (tokens.Count < 1)
{
Expand All @@ -624,9 +624,17 @@ public async Task RefreshTokensIfAllowedAndNeeded()
logger.LogError("Due to rate limitations fleet api requests are not allowed. As this version can not handle rate limits try updating to the latest version.");
return;
}

foreach (var tokenToRefresh in tokensToRefresh)
{
logger.LogWarning("Token {tokenId} needs to be refreshed as it expires on {expirationDateTime}", tokenToRefresh.Id, tokenToRefresh.ExpiresAtUtc);

//DO NOTE REMOVE *2: As normal requests could result in reaching max unauthorized count, the max value is higher here, so even if token is unauthorized, refreshing it is still tried a couple of times.
if (tokenToRefresh.UnauthorizedCounter > (constants.MaxTokenUnauthorizedCount * 2))
{
logger.LogError("Token {tokenId} has been unauthorized too often. Do not refresh token.", tokenToRefresh.Id);
continue;
}
using var httpClient = new HttpClient();
var tokenUrl = "https://auth.tesla.com/oauth2/v3/token";
var requestData = new Dictionary<string, string>
Expand Down Expand Up @@ -661,11 +669,12 @@ await backendApiService.PostErrorInformation(nameof(TeslaFleetApiService), nameo
}
}

private async Task<bool> CheckIfFleetApiRequestsAreAllowed()
public async Task RefreshFleetApiRequestsAreAllowed()
{
logger.LogTrace("{method}()", nameof(RefreshFleetApiRequestsAreAllowed));
if (settings.AllowUnlimitedFleetApiRequests && (settings.LastFleetApiRequestAllowedCheck > dateTimeProvider.UtcNow().AddHours(-1)))
{
return true;
return;
}
settings.LastFleetApiRequestAllowedCheck = dateTimeProvider.UtcNow();
using var httpClient = new HttpClient();
Expand All @@ -678,15 +687,16 @@ private async Task<bool> CheckIfFleetApiRequestsAreAllowed()
var responseString = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
if (!response.IsSuccessStatusCode)
{
return true;
settings.AllowUnlimitedFleetApiRequests = true;
return;
}

var responseValue = JsonConvert.DeserializeObject<DtoValue<bool>>(responseString);
return responseValue?.Value != false;
settings.AllowUnlimitedFleetApiRequests = responseValue?.Value != false;
}
catch (Exception)
{
return true;
settings.AllowUnlimitedFleetApiRequests = true;
}

}
Expand Down

0 comments on commit 9e03ac5

Please sign in to comment.