private async Task CompletePinFlow( TryCompletePlexPinFlow request, CancellationToken cancellationToken) { using IServiceScope scope = _serviceScopeFactory.CreateScope(); IMediator mediator = scope.ServiceProvider.GetRequiredService <IMediator>(); Either <BaseError, bool> result = await mediator.Send(request, cancellationToken); result.BiIter( success => _logger.LogInformation( success ? "Successfully authenticated with plex" : "Plex authentication timeout"), error => _logger.LogWarning("Unable to poll plex token: {Error}", error.Value)); }
Handle(TryCompletePlexPinFlow request, CancellationToken cancellationToken) { var cts = new CancellationTokenSource(TimeSpan.FromMinutes(2)); CancellationToken token = cts.Token; while (!token.IsCancellationRequested) { bool result = await _plexTvApiClient.TryCompletePinFlow(request.AuthPin); if (result) { await _channel.WriteAsync(new SynchronizePlexMediaSources(), cancellationToken); return(true); } await Task.Delay(TimeSpan.FromSeconds(1), token); } return(false); }
protected override async Task ExecuteAsync(CancellationToken cancellationToken) { if (!File.Exists(FileSystemLayout.PlexSecretsPath)) { await File.WriteAllTextAsync(FileSystemLayout.PlexSecretsPath, "{}", cancellationToken); } _logger.LogInformation( "Plex service started; secrets are at {PlexSecretsPath}", FileSystemLayout.PlexSecretsPath); // synchronize sources on startup await SynchronizeSources(new SynchronizePlexMediaSources(), cancellationToken); await foreach (IPlexBackgroundServiceRequest request in _channel.ReadAllAsync(cancellationToken)) { try { Task requestTask = request switch { TryCompletePlexPinFlow pinRequest => CompletePinFlow(pinRequest, cancellationToken), SynchronizePlexMediaSources sourcesRequest => SynchronizeSources( sourcesRequest, cancellationToken), SynchronizePlexLibraries synchronizePlexLibrariesRequest => SynchronizeLibraries( synchronizePlexLibrariesRequest, cancellationToken), _ => throw new NotSupportedException($"Unsupported request type: {request.GetType().Name}") }; await requestTask; } catch (Exception ex) { _logger.LogWarning(ex, "Failed to process plex background service request"); } } }