elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: Estamos en la red social de Mastodon


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación General
| | |-+  .NET (C#, VB.NET, ASP) (Moderador: kub0x)
| | | |-+  C# - Leer un documento de texto en Gmail
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: C# - Leer un documento de texto en Gmail  (Leído 2,681 veces)
TickTack


Desconectado Desconectado

Mensajes: 428


CipherX


Ver Perfil
C# - Leer un documento de texto en Gmail
« en: 19 Septiembre 2017, 18:51 pm »

Hola,

hay una forma de que se pueda programar leer el contenido de este documento de texto: https://drive.google.com/file/d/0B04WDU5Df8zYN2NxMlRlMlhYbm8/view?usp=sharing


Gracias y saludos


En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.788



Ver Perfil
Re: C# - Leer un documento de texto en Gmail
« Respuesta #1 en: 20 Septiembre 2017, 03:33 am »

Hola TickTack.

Bueno, hay dos maneras.

La primera y más sencilla sería suficiente con adaptar la url:

Código
  1. Uri uri = new Uri("https://drive.google.com/uc?export=download&id=0B04WDU5Df8zYN2NxMlRlMlhYbm8");
  2.  
  3. using (WebClient wc = new WebClient()) {
  4.    string content = wc.DownloadString(uri);
  5. }

Si eso para ti te es suficiente, entonces no hay necesidad de que sigas leyendo aquí abajo.





La segunda manera, suponiendo que el documento esté almacenado en tu cuenta personal de Google Drive, es decir, si eres el propietario y/o es de otro usuario pero lo tienes compartido DENTRO de tu cuenta y quieres administrar el archivo de forma avanzada y obtener control total sobre tus acciones, entonces la solución más sofisticada sería utilizar la API de Google Drive para .NET.

Paquete NuGet:

Documentación y samples:



Aquí te dejo un cliente que escribí de la API Google Drive v3 para administrar archivos (listar, descargar, subir, reemplazar, eliminar) en nuestra propia cuenta.

El código es un extracto reducido de mi framework comercial ElektroKit, el cual se puede usar tanto desde C# como VB.NET. Tan solo he dejado los miembros necesarios para la autentificación, enumeración de archivos y directorios, y descarga de archivos.

Si alguien desea obtener más información con respecto a ElektroKit Framework, les invito a mirar mi firma de usuario aquí abajo del todo de mi post.

Espero que esto le sirva de ayuda a alguien, aparte de los samples oficiales de Google.

PD: Me sabe mal recortar tanto el código, pero además el foro tiene un límite de caracteres muy corto y no cabe ni un cacho.

Código
  1. ' ***********************************************************************
  2. ' Author   : Elektro
  3. ' Modified : 22-July-2017
  4. ' ***********************************************************************
  5.  
  6. #Region " Drive Scopes "
  7. Namespace ElektroKit.ThirdParty.Google.Drive.Enums
  8.    ''' <summary>
  9.    ''' Specifies the OAuthv2 scopes for use with the Google Drive API.
  10.    ''' </summary>
  11.    <Flags>
  12.    Public Enum DriveScopes As Integer
  13.  
  14.        ''' <summary>
  15.        ''' Reffers to the <see href="https://www.googleapis.com/auth/drive"/> scope.
  16.        ''' <para></para>
  17.        ''' View and manage the files in your Google Drive.
  18.        ''' </summary>
  19.        Full = 2
  20.  
  21.        ''' <summary>
  22.        ''' Reffers to the <see href="https://www.googleapis.com/auth/drive.appfolder"/> scope.
  23.        ''' <para></para>
  24.        ''' View and manage its own configuration data in your Google Drive.
  25.        ''' </summary>
  26.        ApplicationData = 4
  27.  
  28.        ''' <summary>
  29.        ''' Reffers to the <see href="https://www.googleapis.com/auth/drive.file"/> scope.
  30.        ''' <para></para>
  31.        ''' View and manage Google Drive files and folders that you have opened or created with this application.
  32.        ''' </summary>
  33.        Files = 8
  34.  
  35.        ''' <summary>
  36.        ''' Reffers to the <see href="https://www.googleapis.com/auth/drive.metadata"/> scope.
  37.        ''' <para></para>
  38.        ''' View and manage metadata of files in your Google Drive.
  39.        ''' </summary>
  40.        Metadata = 16
  41.  
  42.        ''' <summary>
  43.        ''' Reffers to the <see href="https://www.googleapis.com/auth/drive.scripts"/> scope.
  44.        ''' <para></para>
  45.        ''' Modify your Google Apps Script scripts' behavior.
  46.        ''' </summary>
  47.        Scripts = 32
  48.  
  49.        ''' <summary>
  50.        ''' Reffers to the <see href="https://www.googleapis.com/auth/drive.readonly"/> scope.
  51.        ''' <para></para>
  52.        ''' View the files in your Google Drive.
  53.        ''' </summary>
  54.        [ReadOnly] = 64
  55.  
  56.        ''' <summary>
  57.        ''' Reffers to the <see href="https://www.googleapis.com/auth/drive.metadata.readonly"/> scope.
  58.        ''' <para></para>
  59.        ''' View metadata for files in your Google Drive.
  60.        ''' </summary>
  61.        MetadataReadonly = 128
  62.  
  63.        ''' <summary>
  64.        ''' Reffers to the <see href="https://www.googleapis.com/auth/drive.photos.readonly"/> scope.
  65.        ''' <para></para>
  66.        ''' View the photos, videos and albums in your Google Photos.
  67.        ''' </summary>
  68.        PhotosReadonly = 256
  69.  
  70.    End Enum
  71. End Namespace
  72. #End Region

+

Código
  1. [code=vbnet]' ***********************************************************************
  2. ' Author   : Elektro
  3. ' Modified : 22-July-2017
  4. ' ***********************************************************************
  5.  
  6. #Region " Imports "
  7.  
  8. Imports System.IO
  9. Imports System.Threading
  10. Imports System.Threading.Tasks
  11.  
  12. Imports ElektroKit.ThirdParty.Google.Drive.Enums
  13.  
  14. ' #If NET45 OrElse NET46 Then
  15.  
  16. Imports Google.Apis.Auth.OAuth2
  17. Imports Google.Apis.Download
  18. Imports Google.Apis.Drive.v3
  19. Imports Google.Apis.Drive.v3.Data
  20. Imports Google.Apis.Services
  21. Imports Google.Apis.Upload
  22. Imports Google.Apis.Util.Store
  23.  
  24. ' #End If
  25.  
  26. #End Region
  27.  
  28. #Region " Drive Client "
  29.  
  30. Namespace ElektroKit.ThirdParty.Google.Drive.Types
  31.  
  32. ' #If NET45 OrElse NET46 Then
  33.  
  34.    ''' <summary>
  35.    ''' A client for Google Drive service.
  36.    ''' </summary>
  37.    Public NotInheritable Class DriveClient : Implements IDisposable
  38.  
  39. #Region " Private Fields "
  40.  
  41. dim demoMessage as string = "Buy ElektroKit Framework to have access to the full version."
  42.  
  43.        ''' <summary>
  44.        ''' The Google Drive service client.
  45.        ''' </summary>
  46.        Private client As DriveService
  47.  
  48.        ''' <summary>
  49.        ''' OAuthv2 credential for accessing protected resources using an access token,
  50.        ''' as well as optionally refreshing the access token when it expires using a refresh token.
  51.        ''' </summary>
  52.        Private credential As UserCredential
  53.  
  54.        ''' <summary>
  55.        ''' A message for an exception that will be thrown when the user has not authorized the app.
  56.        ''' </summary>
  57.        Private ReadOnly authExceptionMessage As String =
  58.            "The user has not yet authorized the usage of this application.
  59.             Call 'DriveClient.Authorize()' or 'DriveClient.AuthorizeAsync()' methods."
  60.  
  61.        ''' <summary>
  62.        ''' The Google Drive OAuthv2 scope urls.
  63.        ''' </summary>
  64.        Private scopeDict As New Dictionary(Of DriveScopes, String)(StringComparison.Ordinal) From
  65.        {
  66.            {DriveScopes.Full, DriveService.Scope.Drive},
  67.            {DriveScopes.ApplicationData, DriveService.Scope.DriveAppdata},
  68.            {DriveScopes.Files, DriveService.Scope.DriveFile},
  69.            {DriveScopes.Metadata, DriveService.Scope.DriveMetadata},
  70.            {DriveScopes.MetadataReadonly, DriveService.Scope.DriveMetadataReadonly},
  71.            {DriveScopes.PhotosReadonly, DriveService.Scope.DrivePhotosReadonly},
  72.            {DriveScopes.ReadOnly, DriveService.Scope.DriveReadonly},
  73.            {DriveScopes.Scripts, DriveService.Scope.DriveScripts}
  74.        }
  75.  
  76. #End Region
  77.  
  78. #Region " Properties "
  79.  
  80.        ''' <summary>
  81.        ''' Gets the client credentials.
  82.        ''' </summary>
  83.        ''' <value>
  84.        ''' The client credentials.
  85.        ''' </value>
  86.        Public ReadOnly Property Secrets As ClientSecrets
  87.  
  88.        ''' <summary>
  89.        ''' Gets the mail address to authorize Drive service. (e.g: "yourmail@gmail.com")
  90.        ''' </summary>
  91.        ''' <value>
  92.        ''' The mail address to authorize Drive service. (e.g: "yourmail@gmail.com")
  93.        ''' </value>
  94.        Public ReadOnly Property MailAddress As String
  95.  
  96.        ''' <summary>
  97.        ''' Gets the current Drive OAuthv2 scopes.
  98.        ''' </summary>
  99.        ''' <value>
  100.        ''' The current Drive OAuthv2 scopes.
  101.        ''' </value>
  102.        Public ReadOnly Property Scope As DriveScopes
  103.  
  104.        ''' <summary>
  105.        ''' Gets a value that determines whether Google Drive API authorization was done.
  106.        ''' </summary>
  107.        ''' <value>
  108.        ''' A value that determines whether Google Drive API authorization was done.
  109.        ''' </value>
  110.        Public ReadOnly Property IsAuthorized As Boolean
  111.            Get
  112.                Return Me.isAuthorizedB
  113.            End Get
  114.        End Property
  115.        ''' <summary>
  116.        ''' ( Backing field )
  117.        ''' A value that determines whether Google Drive API authorization was done.
  118.        ''' </summary>
  119.        Private isAuthorizedB As Boolean = False
  120.  
  121. #End Region
  122.  
  123. #Region " Constructors "
  124.  
  125.        Private Sub New()
  126.        End Sub
  127.  
  128.        ''' <summary>
  129.        ''' Initializes a new instance of the <see cref="DriveClient"/> class.
  130.        ''' </summary>
  131.        ''' <param name="apiFile">
  132.        ''' The <c>client_secrets.json</c> file generated by Drive API console that contains the OAuthv2 login data
  133.        ''' such as the client id, client secret, and redirection URI.
  134.        ''' </param>
  135.        ''' <param name="mailAddress">
  136.        ''' The mail address to authorize Drive service. (e.g: "yourmail@gmail.com")
  137.        ''' </param>
  138.        ''' <param name="scopes">
  139.        ''' The Drive OAuthv2 scope.
  140.        ''' </param>
  141.        Public Sub New(apiFile As String, mailAddress As String, scopes As DriveScopes)
  142.            Me.MailAddress = mailAddress
  143.            Me.Scope = scopes
  144.  
  145.            Using stream As FileStream = New FileInfo(apiFile).OpenRead()
  146.                Me.Secrets = GoogleClientSecrets.Load(stream).Secrets
  147.            End Using
  148.        End Sub
  149.  
  150. #End Region
  151.  
  152. #Region " Public Methods "
  153.  
  154. #Region " Authorization "
  155.  
  156.        ''' <summary>
  157.        ''' Authorizes this instance to use Google Drive API services.
  158.        ''' </summary>
  159.        ''' <example>
  160.        ''' <code>
  161.        ''' Dim client As New DriveClient("C:\GoogleSecrets.json", "yourmail@gmail.com", DriveScopes.Full)
  162.        ''' Dim credential As UserCredential = client.Authorize()
  163.        ''' </code>
  164.        ''' </example>
  165.        <DebuggerStepThrough>
  166.        Public Function Authorize() As UserCredential
  167.            Dim t As Task(Of UserCredential) = Task.Run(AddressOf Me.AuthorizeAsync)
  168.            t.Wait(Timeout.Infinite)
  169.            Return t.Result
  170.        End Function
  171.  
  172.        ''' <summary>
  173.        ''' Authorizes this instance to use Google Drive API services.
  174.        ''' </summary>
  175.        ''' <example>
  176.        ''' <code>
  177.        ''' Dim client As New DriveClient("C:\GoogleSecrets.json", "yourmail@gmail.com", DriveScopes.Full)
  178.        ''' Dim credential As UserCredential = Await client.AuthorizeAsync()
  179.        ''' </code>
  180.        ''' </example>
  181.        Public Async Function AuthorizeAsync() As Task(Of UserCredential)
  182.  
  183.            Dim scopeUrls As String() = Me.GetScopeUrls(Me.Scope)
  184.  
  185.            Me.credential =
  186.                 Await GoogleWebAuthorizationBroker.AuthorizeAsync(Me.Secrets,
  187.                                                                   scopeUrls.ToArray(),
  188.                                                                   Me.MailAddress,
  189.                                                                   CancellationToken.None,
  190.                                                                   New FileDataStore("Test_Name", fullPath:=False))
  191.  
  192.            Me.client = New DriveService(New BaseClientService.Initializer() With {
  193.                                         .HttpClientInitializer = Me.credential,
  194.                                         .ApplicationName = "Test_Name"
  195.            })
  196.  
  197.            Me.isAuthorizedB = True
  198.            Return Me.credential
  199.  
  200.        End Function
  201.  
  202. #End Region
  203.  
  204. #Region " Get Files "
  205.  
  206.        ''' <summary>
  207.        ''' Gets all the files stored in the current user account.
  208.        ''' </summary>
  209.        ''' <example>
  210.        ''' <code>
  211.        '''     Dim client As New DriveClient("C:\GoogleSecrets.json", "yourmail@gmail.com", DriveScopes.Full)
  212.        '''     Dim credential As UserCredential = client.Authorize()
  213.        '''     Dim files As List(Of Data.File) = client.GetFiles()
  214.        '''     Dim fileCount As Integer
  215.        '''
  216.        '''     For Each file As Data.File In files
  217.        '''         Dim sb As New Global.System.Text.StringBuilder()
  218.        '''         With sb
  219.        '''             .AppendLine(String.Format("Id: {0}", file.Id))
  220.        '''             .AppendLine(String.Format("Name: {0}", file.Name))
  221.        '''             .AppendLine(String.Format("Url: {0}", If(file.WebContentLink, file.WebViewLink)))
  222.        '''         End With
  223.        '''         Console.WriteLine(sb.ToString())
  224.        '''     Next file
  225.        ''' </code>
  226.        ''' </example>
  227.        <DebuggerStepThrough>
  228.        Public Function GetFiles() As List(Of Data.File)
  229.  
  230.            If Not (Me.isAuthorizedB) Then
  231.                Throw New InvalidOperationException(Me.authExceptionMessage)
  232.  
  233.            Else
  234.                Dim t As Task(Of List(Of Data.File)) = Task.Run(AddressOf Me.GetFilesAsync)
  235.                t.Wait(Timeout.Infinite)
  236.                Return t.Result
  237.  
  238.            End If
  239.  
  240.        End Function
  241.  
  242.        Public Function GetFiles(predicate As Func(Of Data.File, Boolean)) As List(Of Data.File)
  243.             'Buy ElektroKit Framework to have access to this member.
  244.        End Function
  245.  
  246.        ''' <summary>
  247.        ''' Asynchronously gets all the files stored in the current user account.
  248.        ''' </summary>
  249.        ''' <example>
  250.        ''' <code>
  251.        '''     Dim client As New DriveClient("C:\GoogleSecrets.json", "yourmail@gmail.com", DriveScopes.Full)
  252.        '''     Dim credential As UserCredential = Await client.AuthorizeAsync()
  253.        '''     Dim files As List(Of Data.File) = Await client.GetFilesAsync()
  254.        '''     Dim fileCount As Integer
  255.        '''
  256.        '''     For Each file As Data.File In files
  257.        '''         Dim sb As New Global.System.Text.StringBuilder()
  258.        '''         With sb
  259.        '''             .AppendLine(String.Format("Id: {0}", file.Id))
  260.        '''             .AppendLine(String.Format("Name: {0}", file.Name))
  261.        '''             .AppendLine(String.Format("Url: {0}", If(file.WebContentLink, file.WebViewLink)))
  262.        '''         End With
  263.        '''         Console.WriteLine(sb.ToString())
  264.        '''     Next file
  265.        ''' </code>
  266.        ''' </example>
  267.        <DebuggerStepThrough>
  268.        Public Async Function GetFilesAsync() As Task(Of List(Of Data.File))
  269.  
  270.            If Not (Me.isAuthorizedB) Then
  271.                Throw New InvalidOperationException(Me.authExceptionMessage)
  272.  
  273.            Else
  274.                Dim request As FilesResource.ListRequest = Me.client.Files.List()
  275.                With request
  276.                    .PageSize = 100
  277.                    .IncludeTeamDriveItems = False
  278.                    .SupportsTeamDrives = False
  279.                    .Fields = "nextPageToken, files"
  280.                    .Q = "not mimeType contains 'folder'"
  281.                End With
  282.  
  283.                Dim response As FileList = Await request.ExecuteAsync()
  284.  
  285.                Dim files As New List(Of Data.File)
  286.                Do While True
  287.  
  288.                    For Each file As Data.File In response.Files
  289.                        Dim getRequest As FilesResource.GetRequest = Me.client.Files.Get(file.Id)
  290.                        With getRequest
  291.                            .SupportsTeamDrives = False
  292.                            .Fields = "*"
  293.                        End With
  294.  
  295.                        Dim getResponse As Data.File = Await getRequest.ExecuteAsync()
  296.                        getRequest.AcknowledgeAbuse = True
  297.                        files.Add(getResponse)
  298.                    Next file
  299.  
  300.                    If Not String.IsNullOrEmpty(response.NextPageToken) Then
  301.                        request.PageToken = response.NextPageToken
  302.                        response = Await request.ExecuteAsync()
  303.                    Else
  304.                        Exit Do
  305.                    End If
  306.  
  307.                Loop
  308.  
  309.                Return files
  310.  
  311.            End If
  312.  
  313.        End Function
  314.  
  315.        Public Async Function GetFilesAsync(predicate As Func(Of Data.File, Boolean)) As Task(Of List(Of Data.File))
  316.             'Buy ElektroKit Framework to have access to this member.
  317.        End Function
  318.  
  319.        ''' <summary>
  320.        ''' Gets a file stored in the current user account that matches the specified file id.
  321.        ''' </summary>
  322.        ''' <example>
  323.        ''' <code>
  324.        '''     Dim client As New DriveClient("C:\GoogleSecrets.json", "yourmail@gmail.com", DriveScopes.Full)
  325.        '''     Dim credential As UserCredential = client.Authorize()
  326.        '''     Dim file As Data.File) = client.GetFileById(" File Id. ")
  327.        '''
  328.        '''     Dim sb As New Global.System.Text.StringBuilder()
  329.        '''     With sb
  330.        '''          .AppendLine(String.Format("Id: {0}", file.Id))
  331.        '''          .AppendLine(String.Format("Name: {0}", file.Name))
  332.        '''          .AppendLine(String.Format("Url: {0}", If(file.WebContentLink, file.WebViewLink)))
  333.        '''     End With
  334.        '''     Console.WriteLine(sb.ToString())
  335.        ''' </code>
  336.        ''' </example>
  337.        <DebuggerStepThrough>
  338.        Public Function GetFileById(id As String) As Data.File
  339.            If Not (Me.isAuthorizedB) Then
  340.                Throw New InvalidOperationException(Me.authExceptionMessage)
  341.  
  342.            Else
  343.                Dim t As Task(Of Data.File) = Task.Run(Function() Me.GetFileByIdAsync(id))
  344.                t.Wait(Timeout.Infinite)
  345.                Return t.Result
  346.  
  347.            End If
  348.        End Function
  349.  
  350.        Public Async Function GetFileByIdAsync(id As String) As Task(Of Data.File)
  351.             'Buy ElektroKit Framework to have access to this member.
  352.        End Function
  353.  
  354.        Public Function GetFilesByName(displayName As String) As List(Of Data.File)
  355.             'Buy ElektroKit Framework to have access to this member.
  356.        End Function
  357.  
  358.        Public Async Function GetFilesByNameAsync(displayName As String) As Task(Of List(Of Data.File))
  359.             'Buy ElektroKit Framework to have access to this member.
  360.        End Function
  361.  
  362.        Public Function GetOwnedFiles() As List(Of Data.File)
  363.             'Buy ElektroKit Framework to have access to this member.
  364.        End Function
  365.  
  366.        Public Function GetOwnedFiles(predicate As Func(Of Data.File, Boolean)) As List(Of Data.File)
  367.             'Buy ElektroKit Framework to have access to this member.
  368.        End Function
  369.  
  370.        Public Async Function GetOwnedFilesAsync() As Task(Of List(Of Data.File))
  371.             'Buy ElektroKit Framework to have access to this member.
  372.        End Function
  373.  
  374.        Public Async Function GetOwnedFilesAsync(predicate As Func(Of Data.File, Boolean)) As Task(Of List(Of Data.File))
  375.             'Buy ElektroKit Framework to have access to this member.
  376.        End Function
  377.  
  378.        Public Function GetOwnedFilesByName(displayName As String) As List(Of Data.File)
  379.             'Buy ElektroKit Framework to have access to this member.
  380.        End Function
  381.  
  382.        Public Async Function GetOwnedFilesByNameAsync(displayName As String) As Task(Of List(Of Data.File))
  383.             'Buy ElektroKit Framework to have access to this member.
  384.        End Function
  385.  
  386.        Public Function GetOwnedFileById(id As String) As Data.File
  387.             'Buy ElektroKit Framework to have access to this member.
  388.        End Function
  389.  
  390.        Public Async Function GetOwnedFileByIdAsync(id As String) As Task(Of Data.File)
  391.             'Buy ElektroKit Framework to have access to this member.
  392.        End Function
  393.  
  394. #End Region
  395.  
  396. #Region " Get Folders "
  397.  
  398.        Public Function GetFolders() As List(Of Data.File)
  399.             'Buy ElektroKit Framework to have access to this member.
  400.        End Function
  401.  
  402.        Public Function GetFolders(predicate As Func(Of Data.File, Boolean)) As List(Of Data.File)
  403.             'Buy ElektroKit Framework to have access to this member.
  404.        End Function
  405.  
  406.        Public Async Function GetFoldersAsync() As Task(Of List(Of Data.File))
  407.             'Buy ElektroKit Framework to have access to this member.
  408.        End Function
  409.  
  410.        Public Async Function GetFoldersAsync(predicate As Func(Of Data.File, Boolean)) As Task(Of List(Of Data.File))
  411.             'Buy ElektroKit Framework to have access to this member.
  412.        End Function
  413.  
  414.        Public Function GetFolderById(id As String) As Data.File
  415.             'Buy ElektroKit Framework to have access to this member.
  416.        End Function
  417.  
  418.        Public Async Function GetFolderByIdAsync(id As String) As Task(Of Data.File)
  419.             'Buy ElektroKit Framework to have access to this member.
  420.        End Function
  421.  
  422.        Public Function GetFoldersByName(displayName As String) As List(Of Data.File)
  423.             'Buy ElektroKit Framework to have access to this member.
  424.        End Function
  425.  
  426.        Public Async Function GetFoldersByNameAsync(displayName As String) As Task(Of List(Of Data.File))
  427.             'Buy ElektroKit Framework to have access to this member.
  428.        End Function
  429.  
  430.        Public Function GetOwnedFolders() As List(Of Data.File)
  431.             'Buy ElektroKit Framework to have access to this member.
  432.        End Function
  433.  
  434.        Public Function GetOwnedFolders(predicate As Func(Of Data.File, Boolean)) As List(Of Data.File)
  435.             'Buy ElektroKit Framework to have access to this member.
  436.        End Function
  437.  
  438.        Public Async Function GetOwnedFoldersAsync() As Task(Of List(Of Data.File))
  439.             'Buy ElektroKit Framework to have access to this member.
  440.        End Function
  441.  
  442.        Public Async Function GetOwnedFoldersAsync(predicate As Func(Of Data.File, Boolean)) As Task(Of List(Of Data.File))
  443.             'Buy ElektroKit Framework to have access to this member.
  444.        End Function
  445.  
  446.        Public Function GetOwnedFoldersByName(displayName As String) As List(Of Data.File)
  447.             'Buy ElektroKit Framework to have access to this member.
  448.        End Function
  449.  
  450.        Public Async Function GetOwnedFoldersByNameAsync(displayName As String) As Task(Of List(Of Data.File))
  451.             'Buy ElektroKit Framework to have access to this member.
  452.        End Function
  453.        Public Function GetOwnedFolderById(id As String) As Data.File
  454.             'Buy ElektroKit Framework to have access to this member.
  455.        End Function
  456.  
  457.        Public Async Function GetOwnedFolderByIdAsync(id As String) As Task(Of Data.File)
  458.             'Buy ElektroKit Framework to have access to this member.
  459.        End Function
  460.  
  461. #End Region
  462.  
  463. #Region " Download File "
  464.  
  465.        Public Sub DownloadFile(srcFile As Data.File,dstFilePath As String)
  466.             'Buy ElektroKit Framework to have access to this member.
  467.        End Sub
  468.  
  469.        ''' <summary>
  470.        ''' Downloads the specified file.
  471.        ''' </summary>
  472.        ''' <example>
  473.        ''' <code>
  474.        ''' Dim client As New DriveClient("C:\GoogleSecrets.json", "yourmail@gmail.com", DriveScopes.Full)
  475.        ''' Dim credential As UserCredential = client.Authorize()
  476.        ''' Dim url As String = "https://drive.google.com/uc?export=download&amp;id=1B04WDF5Df8zYN2NXMlRlMlhYbm8"
  477.        '''          
  478.        ''' client.DownloadFile(url, dstFile)
  479.        ''' </code>
  480.        ''' </example>
  481.        ''' <param name="url">
  482.        ''' A Google Drive url that points to the file to download.
  483.        ''' </param>
  484.        '''
  485.        ''' <param name="dstFilePath">
  486.        ''' The destination file path where to save the downloaded file.
  487.        ''' </param>
  488.        <DebuggerStepThrough>
  489.        Public Sub DownloadFile(url As String,
  490.                                dstFilePath As String)
  491.  
  492.            If Not (Me.isAuthorizedB) Then
  493.                Throw New InvalidOperationException(Me.authExceptionMessage)
  494.  
  495.            Else
  496.                Dim t As Task(Of IDownloadProgress) =
  497.                    Task.Run(Function() Me.DownloadFileAsync(url, dstFilePath, Nothing, Nothing))
  498.                t.Wait(Timeout.Infinite)
  499.  
  500.                If (t.Result.Status = DownloadStatus.Failed) Then
  501.                    Throw t.Result.Exception
  502.                End If
  503.  
  504.            End If
  505.  
  506.        End Sub
  507.  
  508.        Public Sub DownloadFile(uri As Uri,dstFilePath As String)
  509.             'Buy ElektroKit Framework to have access to this member.
  510.        End Sub
  511.  
  512.        Public Async Function DownloadFileAsync(srcFile As Data.File,dstFilePath As String) As Task(Of IDownloadProgress)
  513.             'Buy ElektroKit Framework to have access to this member.
  514.        End Function
  515.  
  516.        ''' <summary>
  517.        ''' Asynchronously downloads the specified file.
  518.        ''' </summary>
  519.        ''' <example>
  520.        ''' <code>
  521.        ''' Dim client As New DriveClient("C:\GoogleSecrets.json", "yourmail@gmail.com", DriveScopes.Full)
  522.        ''' Dim credential As UserCredential = Await client.AuthorizeAsync()
  523.        ''' Dim url As String = "https://drive.google.com/uc?export=download&amp;id=1B04WDF5Df8zYN2NXMlRlMlhYbm8"
  524.        '''          
  525.        ''' Dim progress As IDownloadProgress = Await client.DownloadFileAsync(url, dstFile)
  526.        ''' Dim status As DownloadStatus = progress.Status
  527.        ''' Console.WriteLine(status)
  528.        ''' </code>
  529.        ''' </example>
  530.        ''' <param name="url">
  531.        ''' A Google Drive url that points to the file to download.
  532.        ''' </param>
  533.        '''
  534.        ''' <param name="dstFilePath">
  535.        ''' The destination file path where to save the downloaded file.
  536.        ''' </param>
  537.        Public Async Function DownloadFileAsync(url As String,
  538.                                                dstFilePath As String) As Task(Of IDownloadProgress)
  539.  
  540.            Return Await Me.DownloadFileAsync(url, dstFilePath, Nothing, Nothing)
  541.  
  542.        End Function
  543.  
  544.        Public Async Function DownloadFileAsync(uri As Uri,dstFilePath As String) As Task(Of IDownloadProgress)
  545.             'Buy ElektroKit Framework to have access to this member.
  546.        End Function
  547.  
  548.        Public Async Function DownloadFileAsync(srcFile As Data.File,dstFilePath As String,progressHandler As Action(Of IDownloadProgress),cancellationToken As CancellationToken) As Task(Of IDownloadProgress)
  549.             'Buy ElektroKit Framework to have access to this member.
  550.        End Function
  551.  
  552.        ''' <summary>
  553.        ''' Asynchronously downloads the specified file.
  554.        ''' </summary>
  555.        ''' <example>
  556.        ''' <code>
  557.        ''' Dim client As New DriveClient("C:\GoogleSecrets.json", "yourmail@gmail.com", DriveScopes.Full)
  558.        ''' Dim credential As UserCredential = Await client.AuthorizeAsync()
  559.        ''' Dim url As String = "https://drive.google.com/uc?export=download&amp;id=1B04WDF5Df8zYN2NXMlRlMlhYbm8"
  560.        '''          
  561.        ''' Dim progress As IDownloadProgress =
  562.        '''     Await client.DownloadFileAsync(url, dstFile, AddressOf Me.Download_ProgressChanged, Nothing)
  563.        '''
  564.        ''' Public Sub Download_ProgressChanged(e As IDownloadProgress)
  565.        '''
  566.        '''     Select Case e.Status
  567.        '''
  568.        '''         Case DownloadStatus.Downloading
  569.        '''             Console.WriteLine("Bytes downloaded: {0}", e.BytesDownloaded)
  570.        '''
  571.        '''         Case DownloadStatus.Completed
  572.        '''             Console.WriteLine("Download completed.")
  573.        '''
  574.        '''         Case DownloadStatus.Failed
  575.        '''             Console.WriteLine("Download failed. Reason: {0}", e.Exception.Message)
  576.        '''
  577.        '''     End Select
  578.        '''
  579.        ''' End Sub
  580.        ''' </code>
  581.        ''' </example>
  582.        ''' <param name="url">
  583.        ''' A Google Drive url that points to the file to download.
  584.        ''' </param>
  585.        '''
  586.        ''' <param name="dstFilePath">
  587.        ''' The destination file path where to save the downloaded file.
  588.        ''' </param>
  589.        '''
  590.        ''' <param name="progressHandler">
  591.        ''' A event handler that will receive progress changes of the download operation.
  592.        ''' </param>
  593.        '''
  594.        ''' <param name="cancellationToken">
  595.        ''' A cancellation token to cancel the download operation.
  596.        ''' </param>
  597.        Public Async Function DownloadFileAsync(url As String,
  598.                                                dstFilePath As String,
  599.                                                progressHandler As Action(Of IDownloadProgress),
  600.                                                cancellationToken As CancellationToken) As Task(Of IDownloadProgress)
  601.  
  602.            If Not (Me.isAuthorizedB) Then
  603.                Throw New InvalidOperationException(Me.authExceptionMessage)
  604.  
  605.            Else
  606.                Dim downloader As New MediaDownloader(Me.client)
  607.                ' downloader.ChunkSize = 262144
  608.  
  609.                Dim progress As IDownloadProgress
  610.                Using fs As New FileStream(dstFilePath, FileMode.Create, FileAccess.Write, FileShare.Read)
  611.                    AddHandler downloader.ProgressChanged, progressHandler
  612.                    progress = Await downloader.DownloadAsync(url, fs)
  613.                    RemoveHandler downloader.ProgressChanged, progressHandler
  614.                End Using
  615.  
  616.                Return progress
  617.  
  618.            End If
  619.  
  620.        End Function
  621.  
  622.        Public Async Function DownloadFileAsync(uri As Uri,dstFilePath As String,progressHandler As Action(Of IDownloadProgress),cancellationToken As CancellationToken) As Task(Of IDownloadProgress)
  623.             'Buy ElektroKit Framework to have access to this member.
  624.        End Function
  625.  
  626. #End Region
  627.  
  628. #Region " Upload File "
  629.  
  630.        Public Function UploadFile(srcFile As FileInfo,ParamArray parentFolderIds As String()) As KeyValuePair(Of ResumableUpload, Data.File)
  631.             'Buy ElektroKit Framework to have access to this member.
  632.        End Function
  633.  
  634.        Public Function UploadFile(srcFile As FileInfo,dstFile As Data.File,ParamArray parentFolderIds As String()) As KeyValuePair(Of ResumableUpload, Data.File)
  635.             'Buy ElektroKit Framework to have access to this member.
  636.        End Function
  637.  
  638.        Public Async Function UploadFileAsync(srcFile As FileInfo,progressHandler As Action(Of IUploadProgress),cancellationToken As CancellationToken,ParamArray parentFolderIds As String()) As Task(Of KeyValuePair(Of ResumableUpload, Data.File))
  639.             'Buy ElektroKit Framework to have access to this member.
  640.        End Function
  641.  
  642.        Public Async Function UploadFileAsync(srcFile As FileInfo,dstFile As Data.File,progressHandler As Action(Of IUploadProgress),cancellationToken As CancellationToken,ParamArray parentFolderIds As String()) As Task(Of KeyValuePair(Of ResumableUpload, Data.File))
  643.             'Buy ElektroKit Framework to have access to this member.
  644.        End Function
  645.  
  646. #End Region
  647.  
  648. #Region " Update (replace) File "
  649.  
  650.        Public Function UpdateFile(srcFile As FileInfo,dstFile As Data.File) As KeyValuePair(Of ResumableUpload, Data.File)
  651.             'Buy ElektroKit Framework to have access to this member.
  652.        End Function
  653.  
  654.        Public Function UpdateFile(srcFile As FileInfo,dstFileId As String) As KeyValuePair(Of ResumableUpload, Data.File)
  655.             'Buy ElektroKit Framework to have access to this member.
  656.        End Function
  657.  
  658.        Public Async Function UpdateFileAsync(srcFile As FileInfo,dstFile As Data.File,progressHandler As Action(Of IUploadProgress),cancellationToken As CancellationToken) As Task(Of KeyValuePair(Of ResumableUpload, Data.File))
  659.             'Buy ElektroKit Framework to have access to this member.
  660.        End Function
  661.  
  662.        Public Async Function UpdateFileAsync(srcFile As FileInfo,dstFileId As String,progressHandler As Action(Of IUploadProgress),cancellationToken As CancellationToken) As Task(Of KeyValuePair(Of ResumableUpload, Data.File))
  663.             'Buy ElektroKit Framework to have access to this member.
  664.        End Function
  665.  
  666. #End Region
  667.  
  668. #Region " Create Folder "
  669.  
  670.        Public Function CreateFolder(dstName As String, ParamArray parentFolderIds As String()) As Data.File
  671.             'Buy ElektroKit Framework to have access to this member.
  672.        End Function
  673.  
  674.        Public Async Function CreateFolderAsync(dstName As String, ParamArray parentFolderIds As String()) As Task(Of Data.File)
  675.             'Buy ElektroKit Framework to have access to this member.
  676.        End Function
  677.  
  678. #End Region
  679.  
  680. #Region " Delete File "
  681.  
  682.        Public Function DeleteFile(file As Data.File) As String
  683.             'Buy ElektroKit Framework to have access to this member.
  684.        End Function
  685.  
  686.        Public Function DeleteFile(fileId As String) As String
  687.             'Buy ElektroKit Framework to have access to this member.
  688.        End Function
  689.  
  690.        Public Async Function DeleteFileAsync(file As Data.File) As Task(Of String)
  691.             'Buy ElektroKit Framework to have access to this member.
  692.        End Function
  693.  
  694.        Public Async Function DeleteFileAsync(fileId As String) As Task(Of String)
  695.             'Buy ElektroKit Framework to have access to this member.
  696.        End Function
  697.  
  698. #End Region
  699.  
  700. #Region " Delete Folder "
  701.  
  702.        Public Function DeleteFolder(folder As Data.File) As String
  703.             'Buy ElektroKit Framework to have access to this member.
  704.        End Function
  705.  
  706.        Public Function DeleteFolder(folderId As String) As String
  707.             'Buy ElektroKit Framework to have access to this member.
  708.        End Function
  709.  
  710.        Public Async Function DeleteFolderAsync(folder As Data.File) As Task(Of String)
  711.             'Buy ElektroKit Framework to have access to this member.
  712.        End Function
  713.  
  714.        Public Async Function DeleteFolderAsync(folderId As String) As Task(Of String)
  715.             'Buy ElektroKit Framework to have access to this member.
  716.        End Function
  717.  
  718. #End Region
  719.  
  720. #End Region
  721.  
  722. #Region " Private Methods "
  723.        Private Function GetScopeUrls(scopes As DriveScopes) As String()
  724.            Return (From scope As KeyValuePair(Of DriveScopes, String) In Me.scopeDict
  725.                    Where Me.Scope.HasFlag(scope.Key)
  726.                    Select scope.Value).ToArray()
  727.        End Function
  728. #End Region
  729.  
  730. #Region " IDisposable Implementation "
  731.        Private isDisposed As Boolean = False
  732.  
  733.        Public Sub Dispose() Implements IDisposable.Dispose
  734.            Me.Dispose(isDisposing:=True)
  735.            GC.SuppressFinalize(obj:=Me)
  736.        End Sub
  737.  
  738.        Private Sub Dispose(isDisposing As Boolean)
  739.            If (Not Me.isDisposed) AndAlso (isDisposing) Then
  740.                If (Me.client IsNot Nothing) Then
  741.                    Me.client.Dispose()
  742.                    Me.client = Nothing
  743.                End If
  744.            End If
  745.            Me.isDisposed = True
  746.        End Sub
  747. #End Region
  748.  
  749.    End Class
  750.  
  751. ' #End If
  752.  
  753. End Namespace
  754.  
  755. #End Region
[/code]


« Última modificación: 20 Septiembre 2017, 04:11 am por Eleкtro » En línea

Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines