ServiceCredentialImpl.cs 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. using System.IO;
  2. using System.Linq;
  3. using System.Security.Cryptography.X509Certificates;
  4. using Google.Apis.Auth.OAuth2;
  5. using Xamarin.Auth;
  6. using Xamarin.Forms;
  7. using XamarinFormsGoogleDriveAPI.Droid.DependencyService;
  8. using XamarinFormsGoogleDriveAPI.Model.DataModel;
  9. using XamarinFormsGoogleDriveAPI.Services;
  10. using XamarinFormsGoogleDriveAPI.Services.Service.Interface;
  11. [assembly: Dependency(typeof(ServiceCredentialImpl))]
  12. namespace XamarinFormsGoogleDriveAPI.Droid.DependencyService
  13. {
  14. public class ServiceCredentialImpl : IServiceCredential
  15. {
  16. private ServiceAccountCredential credential;
  17. public ServiceCredential Credential => credential;
  18. public string FileLocation => System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments);
  19. public ServiceCredentialImpl()
  20. {
  21. var certificate =
  22. new X509Certificate2(FileLocation + "/" + "your .p12 certificate or the json to read the private key for service account credentials",
  23. "notasecret", X509KeyStorageFlags.Exportable);
  24. var cache = AccountStore.Create().FindAccountsForService("Google").FirstOrDefault();
  25. credential =
  26. new ServiceAccountCredential(new ServiceAccountCredential.Initializer(
  27. "your client-id here")
  28. {
  29. //Scopes = Constants.Scopes,
  30. User = cache.Properties["Email"],
  31. }.FromCertificate(certificate));
  32. }
  33. public string SaveFile(string fileName, MemoryStream stream)
  34. {
  35. var filePath = FileLocation + "/" + fileName;
  36. using (var targetStream = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite))
  37. {
  38. stream.WriteTo(targetStream);
  39. targetStream.Close();
  40. }
  41. MessagingCenter.Send(new DownloadStatusModel() {DownloadStatus = "File Created in the local Memory"},
  42. "DownloadStatus");
  43. return filePath;
  44. }
  45. }
  46. }