Add YouTube data api to Google Client Api on android - youtube-data-api

How do I create a YouTube API class that I can pass on to the GoogleApiClient builder?
mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
.addApi(Plus.API)
.addApi(null)//<========================================INSERT YOUTUBE API HERE
.addScope(Plus.SCOPE_PLUS_LOGIN)
.addScope(Plus.SCOPE_PLUS_PROFILE)
.addScope(CustomScopes.VIEW_YOUTUBE)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();

Related

Upload photos to Google Photos API - Error 500

I'm getting the error below while trying to upload media to Google Photos API, following the docs
This is how i retrieve my bytes array:
And this is how i make the request:
I've tried a lot of things and none of it work...
Note: I'm consuming other Google Photos API endpoints, such as Get Albums, Create Albums, Get Media and everything work as expected. The upload media is the only one i'm having trouble with.
Note 2: The token is being sent correctly.
Note 3: All the origin endpoints were configured in the google console (localhost included) so much so that other endpoints are working correctly.
Anyone can give me a light?
I am writing something similar in C# and was able to work with the photo api. My best advice is to double check headers. I hope this helps, additionally I added a postman screenshot of a successful call to the api:
public async Task<GoogleApiResponse> UploadPhoto(StorageFile photo)
{
var userInfo = UserInfoVault.GetUserInfo();
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", userInfo.AccessToken);
client.DefaultRequestHeaders.Add("X-Goog-Upload-File-Name", photo.DisplayName);
var fileStream = await photo.OpenAsync(FileAccessMode.Read);
var reader = new DataReader(fileStream.GetInputStreamAt(0));
await reader.LoadAsync((uint)fileStream.Size);
byte[] pixels = new byte[fileStream.Size];
reader.ReadBytes(pixels);
var httpContent = new ByteArrayContent(pixels);
httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
HttpResponseMessage photoResponse = client.PostAsync(ApiEdnpoints.UploadPhoto, httpContent).Result;
string strResponse = await photoResponse.Content.ReadAsStringAsync();
return null;
}
Postman screenshot of successful call to upload a photo

Error in using YouTube Reporting Services with Service Account

I'm getting below error when I try to accessing YouTube Reporting Services API using Service Account.
Google.GoogleApiException HResult=0x80131500
Message=Google.Apis.Requests.RequestError The caller does not have
permission [403] Errors [ Message[The caller does not have
permission] Location[ - ] Reason[forbidden] Domain[global] ]
When I searched online, somewhere I saw we need to have GSuite subscription in order to use service account with API, is it correct?
Here is my code snippet:
String serviceAccountEmail = "xxxxxxxxxxxxx#youtubereportingapi.iam.gserviceaccount.com";
var certificate = new X509Certificate2(#"xxxxxxxx.p12", "notasecret", X509KeyStorageFlags.Exportable);
ServiceAccountCredential credential = new ServiceAccountCredential(
new ServiceAccountCredential.Initializer(serviceAccountEmail)
{
Scopes = new[] { YouTubeReportingService.Scope.YtAnalyticsReadonly, YouTubeReportingService.Scope.YtAnalyticsMonetaryReadonly }
}.FromCertificate(certificate));
var youtubeReportingService = new YouTubeReportingService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = Assembly.GetExecutingAssembly().GetName().Name
});
var jobsListResponse = youtubeReportingService.Jobs.List().Execute(); // Here its throwing error
In order to use a service account you must share data with it. I have never heard of using GSuite with a YouTube account you can have the admin try and set up domain wide delegation to the service account. However to my knowledge there is no way to share YouTube data with a service account.
Service accounts are not supported by the YouTube APIs. You will need to use Oauth2 and save your refresh token for access later. The docs only mention OAuth2.

How to upload videos to YouTube [Xamarin.Forms (Portable) ]

I am trying to upload videos to YouTube but somehow it's not working in Xamarin.Forms (Portable) project. Is there any way to upload the Videos in YouTube through Xamarin.Forms (Portable)
var initializer = new GoogleAuthorizationCodeFlow.Initializer
{
ClientSecrets = new ClientSecrets
{
ClientId = Constants.API.Google.ClientID,
ClientSecret = Constants.API.Google.ClientSecret
},
Scopes = new[] { YouTubeService.Scope.Youtube }
};
var flow = new AuthorizationCodeFlow(initializer);
TokenResponse token = flow.LoadTokenAsync("user", CancellationToken.None).Result;
but every time I am getting null in TokenResponse token, I am not sure what should I pass in place of user in flow.LoadTokenAsync("user", CancellationToken.None)
Thank You.
As I had feared the Google .Net client library does not currently support Xamarin. Please see issue: Unable to Google.Apis.Auth.PlatformServices in Xamarin.Forms
It's because GoogleWebAuthorizationBroker requires several classes from Google.Apis.Auth.PlatformServices, and Google.Apis.Auth.PlatformServices is not compatible with Xamarin.

Xamarin.Forms REST Web service Call - POST & GET

I'm new to Xamarin.Forms But I'm okay with UI modules development But I need to config the Web service in the project. I preferred REST service, How can I manage rest service in Xamarin.Forms. I've existing service details from the native iOS application. Can you please help me to config the POST and GET service call in Xamarin.Forms. If you share the example of each POST and Get, It would be more helpful for me.
We have a detailed documentation to access the RESTful webservice to help you. You can find the documentation here: https://developer.xamarin.com/guides/xamarin-forms/web-services/consuming/rest/
Add HttpClient Nuget Package
And Json Package
Using below snippet to consume the REST web service.
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://Host/Service.svc/");
string jsonData = #"{""Password"" : ""test#123"", ""UserId"" : ""$test#demo"", ""format"" : ""json""}";
var content = new StringContent(jsonData, Encoding.UTF8, "application/json");
var response = await client.PostAsync("login", content);
var result = response.Content.ReadAsStringAsync().Result;
if (result != "")
{
var sessionResponseJson = JsonConvert.DeserializeObject<sessionResponse>(result);
}

Reusing Google API credentials in GData API

I am trying to make a web application is ASP.NET MVC 5 with which I can authenticate a user with a Google Account and then read data from his/her spreadsheets stored in Google Drive/Google Sheets.
I am using Google API to authenticate a user. After a user is successfully authenticated, I get the credentials back from Google in an object which is of type Google.Apis.Auth.OAuth2.Web AuthResult.UserCredential
I can then successfully create a service to list files from Drive using code similar to
var driveService = new DriveService(new BaseClientService.Initializer
{
HttpClientInitializer = result.Credential,
ApplicationName = "ASP.NET MVC Sample"
});
Now, I want to use GData API to read content from spreadsheets in Drive. For this to work, I need to have a SpreadsheetsService object and then set it's RequestFactory parameter to an instance of GOAuth2RequestFactory and this in turn needs OAuth2 parameters to be specified in an instance of class OAuth2Parameters.
How can I reuse the credentials obtained using the Google Api in GData API?
I am already doing the thing you want to do,
Code for how I passed the GData tokens
Issue with OAuth2 authentication with google spreadsheet
i.e. I use a single OAuth2 access/refresh token set. Using the same tokens for both gdata calls & drive API calls.
This is the code that finally worked for me
public class AppFlowMetadata : FlowMetadata
{
private static readonly IAuthorizationCodeFlow flow =
new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
{
ClientSecrets = new ClientSecrets
{
ClientId = "randomstring.apps.googleusercontent.com",
ClientSecret = "shhhhhh!"
},
Scopes = new[] { DriveService.Scope.Drive, "https://spreadsheets.google.com/feeds", "https://docs.google.com/feeds", "https://www.googleapis.com/auth/userinfo.email", "https://www.googleapis.com/auth/userinfo.profile" },
DataStore = new FileDataStore("Drive.Api.Auth.Store")
});
public override string GetUserId(Controller controller)
{
var user = controller.Session["user"];
if (user == null)
{
user = Guid.NewGuid();
controller.Session["user"] = user;
}
return user.ToString();
}
public override IAuthorizationCodeFlow Flow { get { return flow; } }
}
And then, in the controller, OAuth2 parameters were copied to GData
var result = await new AuthorizationCodeMvcApp(this, new AppFlowMetadata()).
AuthorizeAsync(cancellationToken);
OAuth2Parameters parameters = new OAuth2Parameters();
parameters.ClientId = "somestring.apps.googleusercontent.com";
parameters.ClientSecret = "shhhhhh!";
parameters.Scope = result.Credential.Token.Scope;
parameters.AccessToken = result.Credential.Token.AccessToken;
parameters.RefreshToken = result.Credential.Token.RefreshToken;
GOAuth2RequestFactory requestFactory = new GOAuth2RequestFactory(null, "MySpreadsheetIntegration-v1", parameters);
SpreadsheetsService service = new SpreadsheetsService("MySpreadsheetIntegration-v1");
service.RequestFactory = requestFactory;

Resources