I am having problems loading a playlist of videos from Youtube. I follow this guide but cant figure out what is wrong because I don't get an error.
var YouTubeService = new YouTubeService(new BaseClientService.Initializer() { ApiKey = "MyAPIID"});
var ChannelListRequest = YouTubeService.Channels.List("contentDetails");
ChannelListRequest.ForUsername = "YoutubeUser";
var ListResponse = ChannelListRequest.Execute();
foreach (var channel in ListResponse.Items) //No content in ListResponse.Items
When I execute the request it returns a empty response. The API Id is correct because it becomes error if I use a old one. I have tried with the username and id from the channel but none worked. What am I missing?
Alright I tried some things and I managed to retrieve my playlists of my channel like so:
var service = new YouTubeService(new BaseClientService.Initializer()
{
ApiKey = "yourapikey",
ApplicationName = this.GetType().Name
});
var playListRequest = service.Playlists.List("snippet");
playListRequest.ChannelId = "yourchannelid";
var result = await playListRequest.ExecuteAsync();
With the playlist Id's you get from this response you can retrieve the video's like so:
var playListItemsRequest = service.PlaylistItems.List("snippet");
playListItemsRequest.PlaylistId = "yourplaylistid";
var result = await playListItemsRequest.ExecuteAsync();
Related
I' am creating dynamically some google sheet given an array of data on one of my endpoints.
it creates successfully, but when I open the generated url, I get the following:
The documentation is not very clear, but I wish to add permissions to a given domain (or set of people) every time I generate a new sheet.
code:
private static readonly string[] Scopes = { SheetsService.Scope.Drive, SheetsService.Scope.Spreadsheets };
public string Create(string templateName, List<IList<object>> values, int numberOfRows)
{
var sheetId = 0;
var spreadSheetId = string.Empty;
var initializer = new ServiceAccountCredential.Initializer(SheetsOptionsConstants.ServiceAccountEmail)
{
Scopes = Scopes
}.FromPrivateKey(SheetsOptionsConstants.PrivateKey);
var credential = new ServiceAccountCredential(initializer);
// Create Google Sheets API service.
var service = new SheetsService(new BaseClientService.Initializer
{
HttpClientInitializer = credential,
ApplicationName = applicationName
});
// Create a new sheet
var sheetTitle = $"[{templateName}] {_clock.Now:yyyy-MM-dd HH-mm}";
try
{
var sheet = new BatchUpdateSpreadsheetRequest
{
Requests = new List<Request>
{
new Request
{
AddSheet = new AddSheetRequest
{
Properties= new SheetProperties
{
Title = sheetTitle
}
}
}
}
};
var createRequest = new Spreadsheet
{
Properties = new SpreadsheetProperties
{
Title = sheetTitle
}
};
var spreadSheetCreate = service.Spreadsheets.Create(createRequest).Execute();
spreadSheetId = spreadSheetCreate.SpreadsheetId;
var request = service.Spreadsheets.BatchUpdate(sheet, spreadSheetId);
var result = request.Execute();
sheetId = result.Replies.First().AddSheet.Properties.SheetId.GetValueOrDefault(0);
// Add data in sheet
var range = $"'{sheetTitle}'!A1:X{numberOfRows + 1}";
var valueRange = new ValueRange
{
Range = range,
Values = values
};
var valuesRequest = service.Spreadsheets.Values.Update(valueRange, spreadSheetId, range);
valuesRequest.ValueInputOption = SpreadsheetsResource.ValuesResource.UpdateRequest.ValueInputOptionEnum.USERENTERED;
valuesRequest.Execute();
_logger.LogInformation("Create sheet with name {sheetTitle} and {count} lines", sheetTitle, numberOfRows);
}
catch (Exception exception)
{
_logger.LogError(exception, "Error to create sheet with name {sheetTitle}", sheetTitle);
}
return string.Format(TemplateUrl, spreadSheetId, sheetId);
}
Thanks in advance
You need to use the Drive API to create the permissions for the Sheet. To do so, initialize the Drive Service and create a permissions object. Then, apply it to the Sheet Id using the method create().
You should include the following to your code:
using Google.Apis.Drive.v3;
using Google.Apis.Drive.v3.Data; //This might be not necessary if you already use Drive.v3
The required scopes:
https://www.googleapis.com/auth/drive.file
Create the permissions object:
//(example to give writing permissions to a domain)
Permission perms = new Permission();
perms.Role = "writer";
perms.Type = "domain";
perms.Domain = "your_domain";
And then the request:
// Create Drive API service.
var service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
service.Permissions.Create(perms, sheetId).Execute();
References:
.NET Quickstart
Manage sharing
Permissions from the Drive Api
I'm trying to consume a Graphql Api from a C# client. For that I'm using the GraphQl.Net Nuget package. The problem is that, I have no idea how to set the Api Url as I don't have HttpRequest object and this results also with additional problems that I can't set the authentcation header and send the token with the request. My code looks like:
public void Post(TestGraphQl.GraphQLQuery query)
{
var inputs = query.Variables.ToInputs();
var queryToExecute = query.Query;
var result = _executer.ExecuteAsync(_ =>
{
_.Schema = _schema;
_.Query = queryToExecute;
_.OperationName = query.OperationName;
_.Inputs = inputs;
//_.ComplexityConfiguration = new ComplexityConfiguration { MaxDepth = 15 };
_.FieldMiddleware.Use<InstrumentFieldsMiddleware>();
}).Result;
var httpResult = result.Errors?.Count > 0
? HttpStatusCode.BadRequest
: HttpStatusCode.OK;
var json = _writer.Write(result);
}
And the caller looks like this:
var jObject = new Newtonsoft.Json.Linq.JObject();
jObject.Add("id", deviceId);
client.Post(new GraphQLQuery { Query = "query($id: String) { device (id: $id) { displayName, id } }", Variables = jObject });
I'm totally new to this topic and appreciate any help. Many thanks!!
This worked out for me. You will need the GraphQL.Client Package. My_class is the class for the deserialization.
var client = new GraphQLHttpClient(Api_Url, new NewtonsoftJsonSerializer());
var request = new GraphQLRequest
{
Query = {query}
};
var response = await client.SendQueryAsync<my_class>(request);
Not sure if you are still looking for it. One can always use GraphQl.Client nuget to achieve this. Sample code to consume is
var query = #"query($id: String) { device (id: $id) { displayName, id } }";
var request = new GraphQLRequest(){
Query = query,
Variables = new {id =123}
};
var graphQLClient = new GraphQLClient("http://localhost:8080/api/GraphQL");
graphQLClient.DefaultRequestHeaders.Add("Authorization", "yourtoken");
var graphQLResponse = await graphQLClient.PostAsync(request);
Console.WriteLine(graphQLResponse.Data);
When I try to list albums with the PhotosLibraryService API, I always return null, has anyone been able to use the new Google Photos API yet? The picasa API no longer works.
public void ListAlbums()
{
var json = File.ReadAllText(_diretorio + "/PhotoClient/" + "client.json");
var cr = JsonConvert.DeserializeObject<PersonalServiceAccountCred>(json);
var xCred = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(cr.client_email)
{
Scopes = this._scopes
}.FromPrivateKey(cr.private_key));
// Create the service.
var service = new PhotosLibraryService(new Google.Apis.Services.BaseClientService.Initializer()
{
HttpClientInitializer = xCred
});
var albums = service.Albums.List().Execute();
}
Thanks!
i try to get the livechat Messages vie the c# API from a different channel.
To achieve this i Need the liveboradcast id.
I managed to get the live Video and id via search, but it seems this id isnt the livebroadcast id.
This is my Code so far.
As i said it Returns a Video and the ID, but the Broadcast Response with this id is 0.
Example:
"[GER/HD] Boss Riesenaffe/Megapithecus Hard, oder auch nicht ;) ARK: Survival Evolved (t3CwM9MJSNI)"
Anyone know where i can get the livebroadcast id !?
Stream SStream = new FileStream("client_secrets.json", FileMode.Open);
UserCredential Credentials = await GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.Load(SStream).Secrets, new[] { YouTubeService.Scope.YoutubeForceSsl }, "user", CancellationToken.None, new FileDataStore(this.GetType().ToString()));
Service = new YouTubeService(new BaseClientService.Initializer
{
HttpClientInitializer = Credentials,
ApplicationName = "name"
});
var searchListRequest = Service.Search.List("snippet");
searchListRequest.EventType = SearchResource.ListRequest.EventTypeEnum.Live;
searchListRequest.Type = "video";
searchListRequest.ChannelId = "thechannelid";
searchListRequest.MaxResults = 50;
var searchListResponse = await searchListRequest.ExecuteAsync();
List<string> videos = new List<string>();
string ID = null;
foreach (var searchResult in searchListResponse.Items)
{
switch (searchResult.Id.Kind)
{
case "youtube#video":
ID = searchResult.Id.VideoId;
videos.Add(String.Format("{0} ({1})", searchResult.Snippet.Title, searchResult.Id.VideoId));
break;
}
}
Console.WriteLine(String.Format("Videos:\n{0}\n", string.Join("\n", videos)));
LiveBroadcastsResource.ListRequest Request = Service.LiveBroadcasts.List("id,snippet,contentDetails,status");
Request.BroadcastType = LiveBroadcastsResource.ListRequest.BroadcastTypeEnum.All;
//Request.BroadcastStatus = LiveBroadcastsResource.ListRequest.BroadcastStatusEnum.Active;
Request.MaxResults = 10;
Request.Id = ID;
Console.WriteLine("ID: " + Request.Id);
//Request.Mine = false;
var BroadCastResponse = Request.Execute();
Console.WriteLine(BroadCastResponse.Items.Count);
foreach (LiveBroadcast c in BroadCastResponse.Items)
{
Console.WriteLine("Title: " + c.Snippet.Title);
}
AFAIK, you can only search broadcasts that the channel you are authenticated has created.
Try using search.list:
Returns a collection of search results that match the query parameters specified in the API request.
As stated in this related SO post, search.list returns video from a particular channel, without being authenticated as that channel/user, if you know that channel's channelId.
HTTPS Request:
HTTP GET https://www.googleapis.com/youtube/v3/search?part=snippet&channelId={channelId}&eventType=live&type=video&key={YOUR_API_KEY}
https://www.youtube.com/channel/UC-9-kyTW8ZkZNDHQJ6FgpwQ
public async System.Threading.Tasks.Task<List<ViewModel.YoutubeVideo>> GetYoutubeMusic()
{
var youtubeService = new YouTubeService(new BaseClientService.Initializer()
{
ApiKey = "....",
ApplicationName = this.GetType().ToString()
});
var searchListRequest = youtubeService.Channels.List("snippet");
searchListRequest.Id= "UC-9-kyTW8ZkZNDHQJ6FgpwQ";
searchListRequest.MaxResults = 25;
//Call the search.list method to retrieve results...
var searchListResponse = await searchListRequest.ExecuteAsync();
List<ViewModel.YoutubeVideo> arrays = new List<ViewModel.YoutubeVideo>();
foreach (var searchResult in searchListResponse.Items)
{
product = new ViewModel.YoutubeVideo();
product.id = searchResult.Id;
product.Name = searchResult.Snippet.Title;
product.Thumb100Uri = searchResult.Snippet.Thumbnails.Default.Url;
product.Thumb200Uri = searchResult.Snippet.Thumbnails.Medium.Url;
arrays.Add(product);
}
return arrays;
}
just be get information from this channel but no video...
I don't understand about that. Please to solve it.
Because you are not calling the search.list method. You are calling the channels.list method in your code.
But if you already have the id of the channel, you should just retrieve that channel's uploaded videos.