Youtube API List channels other than Google - c#

I am sitting hours and cannot find the answer for issue I have. I am using latest Youtube API for .NET
The problem I wanna solve is to take information - mostly id from any channel for Youtube channel I give the name.
var youtubeService = new YouTubeService(new BaseClientService.Initializer()
{
ApiKey = "key",
ApplicationName = "appName"
});
var asd = youtubeService.Channels.List(new Repeatable<string>(new List<string> { "snippet,contentDetails,statistics" }));
asd.ForUsername = "Mauzer";
var dsa = await asd.ExecuteAsync();
To achieve that I am using ForUsername property. However the result of call does not always return the result.
For example if I type "Google" as Username it return the Google`s channel. However it doesn't work for all channels I can find exploring Youtube.
Anyone is familiar and know what I am missing?

Related

Youtube v3 API captions downloading

I'm trying to download captions from some videos on Youtube using their nuget package. Here's some code:
var request = _youtube.Search.List("snippet,id");
request.Q = "Bill Gates";
request.MaxResults = 50;
request.Type = "video";
var results = request.Execute();
foreach (var result in results.Items)
{
var captionListRequest = _youtube.Captions.List("id,snippet", result.Id.VideoId);
var captionListResponse = captionListRequest.Execute();
var russianCaptions =
captionListResponse.Items.FirstOrDefault(c => c.Snippet.Language.ToLower() == "ru");
if (russianCaptions != null)
{
var downloadRequest = _youtube.Captions.Download(russianCaptions.Id);
downloadRequest.Tfmt = CaptionsResource.DownloadRequest.TfmtEnum.Srt;
var ms = new MemoryStream();
downloadRequest.Download(ms);
}
}
When the Download method is called I'm getting a weird Newtonsoft.JSON Exception that says:
Newtonsoft.Json.JsonReaderException: 'Unexpected character encountered while parsing value: T. Path '', line 0, position 0.'
at Newtonsoft.Json.JsonTextReader.ParseValue()
I've read some other threads on captions downloading problems and have tried to change my authorization workflow: first I've tried to use just the ApiKey but then also tried OAuth. Here's how it looks now:
var credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
new ClientSecrets
{
ClientId = "CLIENT_ID",
ClientSecret = "CLIENT_SECRET"
},
new[] { YouTubeService.Scope.YoutubeForceSsl },
"user",
CancellationToken.None,
new FileDataStore("Youtube.CaptionsCrawler")).Result;
_youtube = new YouTubeService(new BaseClientService.Initializer
{
ApplicationName = "LKS Captions downloader",
HttpClientInitializer = credential
});
So, is it even possible to do what I'm trying to achieve?
P.S. I was able to dig deep into the youtube nuget package and as I see, the actual message, that I get (that Newtonsoft.JSON is trying to deserialize, huh!) is "The permissions associated with the request are not sufficient to download the caption track. The request might not be properly authorized, or the video order might not have enabled third-party contributions for this caption."
So, do I have to be the video owner to download captions? But if so, how do other programs like Google2SRT work?
Found this post How to get "transcript" in youtube-api v3
You can get them via GET request on: http://video.google.com/timedtext?lang={LANG}&v={VIDEOID}
Example:
http://video.google.com/timedtext?lang=en&v=-osCkzoL53U
Note that they should have subtitles added, will not work if auto-generated.

Get youtube playlist by ID in youtube api .net

I am trying to download the most recent items from a YouTube playlist in a C# .NET program. Right now I have a program that successfully gets the necessary data from my channel's Uploads playlist using "channel.ContentDetails.RelatedPlaylists.Uploads;", which I got from the sample program on the API page. But I can't find any information in the api docs about how to switch that line or lines around it to get a playlist by ID rather than my own uploads.
This is not a duplicate because other examples on this page explain how to find it through an http link, as in "http://gdata.youtube.com/feeds/api/playlists/..." etc. I want to do it directly through the API's methods. The part of my code that downloads the data is included below.
private async Task Run()
{
var youtubeService = new YouTubeService(new BaseClientService.Initializer()
{
ApiKey = "API KEY HERE",
ApplicationName = this.GetType().ToString()
});
//MAYBE I NEED TO CHANGE THIS? SOMETHING LIKE
//'youtubeservice.Playlists.IDUNNOWHAT'
var channelsListRequest = youtubeService.Channels.List("contentDetails");
channelsListRequest.Id = "CHANNEL ID HERE";
// Retrieve the contentDetails part of the channel resource for the authenticated user's channel.
var channelsListResponse = await channelsListRequest.ExecuteAsync();
foreach (var channel in channelsListResponse.Items)
{
//OR MAYBE I NEED TO CHANGE THIS PART?
//LIKE 'channel.ContentDetails.SOMETHING
var uploadsListId = channel.ContentDetails.RelatedPlaylists.Uploads;
var nextPageToken = "";
while (nextPageToken != null)
{
var playlistItemsListRequest = youtubeService.PlaylistItems.List("snippet");
playlistItemsListRequest.PlaylistId = uploadsListId;
playlistItemsListRequest.MaxResults = 50;
playlistItemsListRequest.PageToken = nextPageToken;
// Retrieve the list of videos uploaded to the authenticated user's channel.
var playlistItemsListResponse = await playlistItemsListRequest.ExecuteAsync();
/*
* DO A BUNCH OF STUFF WITH THE YOUTUBE DATA
*/
nextPageToken = playlistItemsListResponse.NextPageToken;
}
}
}
In the documentation, it lists the playlists you can get by using ContentDetails.RelatedPlaylists:
likes
favorites
uploads
watchHistory
watchLater
Therefore, if you want to get the items for a playlist you created you won't be able to do it using ContentDetails.RelatedPlaylists, you'll have to provide the playlist ID. I believe it should work with the code you provided (might need a few tweaks) if you change
playlistItemsListRequest.PlaylistId = uploadsListId;
to use the ID of the playlist whose videos you want to get.

YouTube Data API v3: deleting videos using a service account: Unauthorized client or scope in request

I'm trying to delete one or more videos using a simple C# app (I intend to use a Windows Service later) and I'm getting this error:
Google.Apis.Auth.OAuth2.Responses.TokenResponseException: Error:"unauthorized_client", Description:"Unauthorized client or scope in request.", Uri:""
at Google.Apis.Requests.ClientServiceRequest`1.Execute() in c:\code\google.com\google-api-dotnet-client\default\Tools\Google.Apis.Release\bin\Debug\test\default\Src\GoogleApis\Apis\Requests\ClientServiceRequest.cs:line 93
Uploading videos works perfectly. For both operations, I use the same initialization method:
private static YouTubeService AuthorizeYoutubeService()
{
string serviceAccountEmail = "...#developer.gserviceaccount.com";
string keyFilePath = "Warehouse<...>.p12";
string userAccountEmail = "login#gmail.com";
if (!File.Exists(keyFilePath))
{
System.Windows.Forms.MessageBox.Show("Secret file not found!");
return null;
}
var scope = new string[] { YouTubeService.Scope.Youtube };
var cert = new X509Certificate2(keyFilePath, "notasecret", X509KeyStorageFlags.Exportable);
try
{
ServiceAccountCredential credential = new ServiceAccountCredential
(new ServiceAccountCredential.Initializer(serviceAccountEmail)
{
Scopes = scope,
User = userAccountEmail
}.FromCertificate(cert));
var service = new YouTubeService(new BaseClientService.Initializer
{
HttpClientInitializer = credential,
ApplicationName = "warehouse"
});
return service;
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.Message);
return null;
}
}
The difference compared to simply uploading videos, is the defined Scope: YouTubeService.Scope.YoutubeUpload. When I try to delete a video using it, I get an insufficientPermissions (403) error.
So after looking in the documentation I've changed it to YouTubeService.Scope.Youtube.
Here's the code I'm trying to use:
var youtubeService = AuthorizeYoutubeService();
foreach (string id in deleteIds)
{
var videoDeleteRequest = youtubeService.Videos.Delete(id);
var result = videoDeleteRequest.Execute();
}
Where deleteIds is a list of 11 character strings containing IDs of existing videos.
I have YouTube Data API enabled in the developers console.
I've installed the API via NuGet, I don't think there's anything wrong with the packages.
I'm quite new to Google development, and all similar questions were about the calendar API.
I appreciate any help.
What I ended up doing is reseting the list of apps connected to the Google account and setting it up again from scratch. My app was added 2 times for some reason.

Google Translate Api V2 C# with multiple phrases

Can anyone show me an example of how to make multiple phrase translation with google translate api?
I am using the following now:
var service = new TranslateService(new BaseClientService.Initializer()
{
ApiKey = "my-key-here",
ApplicationName = "something"
});
string[] translatelist = new string[] { contentToTranslate, "en" };
var response = service.Translations.List(translatelist, "tr").ExecuteAsync();
string translatedtext = response.Result.Translations[0].TranslatedText;
I tried making translatelist 2 dimensional but it didn't work. Thanks in advance.

Google plus language programming using people.list

as a new researcher I am trying to get information about relations among people on G+. I want to get other's circle list for some research purpose. It seems that the G+ API offers a web version to use people.list with a OAuth2 token. My question is, does people.list support programming language such as c#, java? I tried with c# but it seems to be blocked by the server.
Is there is a way to apply people.list in c#,java etc? If yes, are there some samples? Or someone provide some open codes to fullfill similar functions?
thanks very much.
the following is my related c# code:
var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description)
{
ClientIdentifier = credentials.ClientId,
ClientSecret = credentials.ClientSecret
};
var auth = new OAuth2Authenticator<NativeApplicationClient>(provider, GetAuthorization);
var servicelist = new PlusService(new BaseClientService.Initializer()
{
Authenticator = auth
});
string userId = "********************";
PeopleResource.ListRequest circle = servicelist.People.List(userId, new PeopleResource.Collection());
circle.MaxResults = 5;
PeopleFeed danielfeed = circle.Fetch();
private static IAuthorizationState GetAuthorization(NativeApplicationClient arg)
{
IAuthorizationState state = new AuthorizationState(new[] { TasksService.Scopes.Tasks.GetStringValue() });
state.Callback = new Uri(NativeApplicationClient.OutOfBandCallbackUrl);
Uri authUri = arg.RequestUserAuthorization(state);
Process.Start(authUri.ToString());
Console.Write(" Authorization Code: ");
string authCode = Console.ReadLine();
Console.WriteLine();
return arg.ProcessUserAuthorization(authCode, state);
}
}
The program goes wrong at "PeopleFeed danielfeed = circle.Fetch();" I think I have already passed the OAuth token to the people.list function by variable "auth". Can you give me some advices?
Google's People:list API's documentation is here. The entire API is RESTful, and does not block any language.
You can use C#, and just need to learn how to consume a REST API in C#. The C# class you will want to use is the HttpClient class. It is very well documented here and there are plenty of tutorials online, as well as here on SO.

Categories