Skip to content

Instantly share code, notes, and snippets.

@chsami
Last active January 14, 2019 21:14
Show Gist options
  • Save chsami/5d12741aa2d4e22f0f57d81cb54122a7 to your computer and use it in GitHub Desktop.
Save chsami/5d12741aa2d4e22f0f57d81cb54122a7 to your computer and use it in GitHub Desktop.
Pagination Class
public class AuthenticationHelper : IAuthenticationHelper
{
static string ApplicationName = "APPLICATIONNAME";
static string RefreshToken = "YOURREFRESHTOKEN";
public DriveService Authenticate()
{
var token = new TokenResponse
{
RefreshToken = RefreshToken
};
UserCredential credentials;
using (var stream = File.OpenRead("credentials.json"))
{
credentials = new UserCredential(new GoogleAuthorizationCodeFlow(
new GoogleAuthorizationCodeFlow.Initializer()
{
ClientSecretsStream = stream,
Scopes = new List<string>()
{
DriveService.Scope.Drive
}
}), Environment.UserName, token);
}
// Create Drive API service.
var service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credentials,
ApplicationName = ApplicationName,
});
return service;
}
}
public class FileHandler
{
private readonly DriveService _driveService;
public FileHandler(DriveService driveService)
{
_driveService = driveService;
}
public IEnumerable<File> FetchFiles(string mimeType, int pageSize = 20)
{
FilesResource.ListRequest listRequest = _driveService.Files.List();
listRequest.PageToken = Pagination.NextPageToken;
listRequest.Q = mimeType;
listRequest.PageSize = pageSize;
listRequest.Fields = "nextPageToken, files(id, name, mimeType)";
FileList execute = listRequest.Execute();
Pagination.NextPageToken = execute.NextPageToken;
IList<File> files = execute.Files;
return files;
}
}
[Route("api/[controller]")]
[ApiController]
public class FilesController : ControllerBase
{
private readonly IAuthenticationHelper _authenticationHelper;
public FilesController(IAuthenticationHelper authenticationHelper)
{
_authenticationHelper = authenticationHelper;
}
// GET api/files
[HttpGet]
public IEnumerable<File> Get()
{
var service = _authenticationHelper.Authenticate();
var fileHandler = new FileHandler(service);
var files = fileHandler.FetchFiles("mimeType='audio/mpeg'");
return files;
}
}
public interface IAuthenticationHelper
{
DriveService Authenticate();
}
public static class Pagination
{
public static string NextPageToken { get; set; }
}
services.AddTransient<IAuthenticationHelper, AuthenticationHelper>();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment