Domanda Youtube Data API v3 - problemi su credentials

Matty80

Utente Bronze
18 Settembre 2020
45
11
0
25
Ultima modifica:
Salve, sto cercando per la prima volta di utilizzare l'api di youtube Youtube Data API v3, precisamente il metodo Playlists: insert che opera nei dati privati dell'utente, per aggiungere un determinato video ad una determinata playlist mia personale. Per operare con i dati privati di ogni utente, ho bisogno dei permessi di OAuth e ho bisogno di Autorizzazioni dell'utente che comprendano almeno uno di questi scopes

42fYi.png


Le API keys invece funzionano per i dati pubblici, il che ho già utilizzato per ricavare l'ID del primo risultato di ricerca partendo da una qwery ( inserirò anche questo codice per mostrare le differenze )
Online, ho trovato dei GitHub samples in c# che ho convertito in vb.net e modificato il codice obsoleto tipo

GoogleClientSecrets.Load(stream).Secrets

in

GoogleClientSecrets.fromstream(stream).Secrets

Codice:
Imports System
Imports System.Collections.Generic
Imports System.IO
Imports System.Net
Imports System.Reflection
Imports System.Text
Imports System.Threading
Imports System.Threading.Tasks
Imports Google.Apis.Auth.OAuth2
Imports Google.Apis.Services
Imports Google.Apis.Upload
Imports Google.Apis.Util.Store
Imports Google.Apis.YouTube.v3
Imports Google.Apis.YouTube.v3.Data
Public Class Form1

    Private Async Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

        Try
            Await RetrieveID()
        Catch ex As AggregateException

            For Each inner In ex.InnerExceptions
                MsgBox("Error: " & inner.Message)
            Next
        End Try
    End Sub
    Private Async Function RetrieveID() As Task
        Dim youtubeService = New YouTubeService(New BaseClientService.Initializer() With {
            .ApiKey = "la mia api key",
            .ApplicationName = Me.[GetType]().ToString()
        })
       

        Dim searchListRequest = youtubeService.Search.List("snippet")
        searchListRequest.Q = TextBox1.Text
        searchListRequest.MaxResults = 1
        Dim searchListResponse = Await searchListRequest.ExecuteAsync()
        Dim videos As List(Of String) = New List(Of String)()
        Dim channels As List(Of String) = New List(Of String)()
        Dim playlists As List(Of String) = New List(Of String)()

        For Each searchResult In searchListResponse.Items

            videos.Add(String.Format("{0} ({1})", searchResult.Snippet.Title, searchResult.Id.VideoId))

        Next

        MsgBox(String.Format("Videos:" & vbLf & "{0}" & vbLf, String.Join(vbLf, videos)))

    End Function

    Private Async Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click

        Try
            Await PlaylistUpdates()
        Catch ex As AggregateException

            For Each inner In ex.InnerExceptions
                MsgBox("Error: " & inner.Message)
            Next
        End Try
    End Sub

   
Private Async Function PlaylistUpdates() As Task

        Dim credential As UserCredential


        Using stream = New FileStream("secret.json", FileMode.Open, FileAccess.Read)
            credential = Await GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.FromStream(stream).Secrets, {youtubeService.Scope.Youtube}, "user", CancellationToken.None, New FileDataStore(Me.[GetType]().ToString()))
        End Using

        Dim youtubeService = New YouTubeService(New BaseClientService.Initializer() With {
        .HttpClientInitializer = credential,
        .ApplicationName = [GetType]().ToString()
      })

        Dim newPlaylistItem = New PlaylistItem()
        newPlaylistItem.Snippet = New PlaylistItemSnippet()
        newPlaylistItem.Snippet.PlaylistId = "PL4_Dx88dpu7cEY_cBjTZFFM1tVKF5Plsx"
        newPlaylistItem.Snippet.ResourceId = New ResourceId()
        newPlaylistItem.Snippet.ResourceId.Kind = "youtube#video"
        newPlaylistItem.Snippet.ResourceId.VideoId = "GNRMeaz6QRI"
        newPlaylistItem = Await youtubeService.PlaylistItems.Insert(newPlaylistItem, "snippet").ExecuteAsync()
        Console.WriteLine("Playlist item id {0} was added to playlist id {1}.", newPlaylistItem.Id, "PL4_Dx88dpu7cEY_cBjTZFFM1tVKF5Plsx")
    End Function


Ma nonostante ciò, ricevo l'errore
" The service YouTube as thrown an exception. HttpStatusCode is Unauthorize. APi keys are not supported by this API. Expected OAuth 2 access token or other authentication credentials that assert a principal".
appena clicco il button 2 sulla linea

Codice:
Await PlaylistUpdates()

Ho provato a cambiare Me.[GetType]().ToString() con il nome dell'applicazione utilizzato in Google console ma non ho risolto il problema.
Ho notato però un warning

U9uMSh2.png


p.s.(non importa se si vede l'api key, è di prova su un account di prova).
Pertanto sono ritornato sullo sample di github e ho provato a seguire l'ordine del codice per evitare quel warning, dunque il codice della funzione PlaylistUpdates diventa

Codice:
Private Async Function PlaylistUpdates() As Task

        'Dim credential As UserCredential

        Dim credential As UserCredential

        Using stream = New FileStream("secret.json", FileMode.Open, FileAccess.Read)
            credential = Await GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.fromstream(stream).Secrets, {youtubeService.Scope.Youtube}, "user", CancellationToken.None, New FileDataStore(Me.[GetType]().ToString()))
        End Using

        Dim youtubeService = New YouTubeService(New BaseClientService.Initializer() With {
        .HttpClientInitializer = credential,
        .ApplicationName = Me.[GetType]().ToString()
    })
        Dim newPlaylistItem = New PlaylistItem()
        newPlaylistItem.Snippet = New PlaylistItemSnippet()
        newPlaylistItem.Snippet.PlaylistId = "PL4_Dx88dpu7cEY_cBjTZFFM1tVKF5Plsx"
        newPlaylistItem.Snippet.ResourceId = New ResourceId()
        newPlaylistItem.Snippet.ResourceId.Kind = "youtube#video"
        newPlaylistItem.Snippet.ResourceId.VideoId = "GNRMeaz6QRI"
        newPlaylistItem = Await youtubeService.PlaylistItems.Insert(newPlaylistItem, "snippet").ExecuteAsync()
        Console.WriteLine("Playlist item id {0} was added to playlist id {1}.", newPlaylistItem.Id, "PL4_Dx88dpu7cEY_cBjTZFFM1tVKF5Plsx")
    End Function

ma ora mostra l'errore Description
Local variable 'youtubeService' cannot be referred to before it is declared.
sulla linea

Codice:
 credential = Await GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.fromstream(stream).Secrets, {youtubeService.Scope.Youtube}, "user", CancellationToken.None, New FileDataStore(Me.[GetType]().ToString()))
Non so davvero come sbattermi.. Sono sicuro di aver attivato tutte le api, scopes e autorizzazioni necessarie, così come ho scaricato correttamente il file json per l'AOuth e di averlo messo nella cartella di debug..
Non capisco più come sbattermi la testa.
Vi do anche il contenuto OAuth del file json che ho inserito nella cartella debug del progetto, in quanto è un account di prova, in modo tale che possiate ricreare l'errore nel vostro compilatore.
Codice:
{"installed":{"client_id":"761263833850-l0j1dggfbhip3o0ueull9cs1v2icbclu.apps.googleusercontent.com","project_id":"fine-climber-360613","auth_uri":"https://accounts.google.com/o/oauth2/auth","token_uri":"https://oauth2.googleapis.com/token","auth_provider_x509_cert_url":"https://www.googleapis.com/oauth2/v1/certs","client_secret":"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","redirect_uris":["http://localhost"]}}

Qualche idea?
Grazie
Messaggio unito automaticamente:

Ho risolto semplicemente cambiando i nomi delle variabili locali. Evidentemente c# è diverso da vb.net il quale non permette di usare nomi di variabili uguali alla classe YouTubeService