How do you get an RTMP key and associate it with LiveBroadcasts?
I would like to create RTMP keys and associate them with scheduled broadcasts.
When I create a LiveBroadcasts the default RTMP key is associated. I need to manage these keys to be able to program and broadcast several videos simultaneously.
The RTMP key information does not exist in the LiveBroadcast.insert response, but in YouTube Studio the default key is associated with the video schedule.
GoogleCredential cred = await auth.GetCredentialAsync();
var service = new YouTubeService(new BaseClientService.Initializer
{
HttpClientInitializer = cred
});
var liveBroadcast = new LiveBroadcast();
var snippet = new LiveBroadcastSnippet();
snippet.Title = "Video example 1";
snippet.ScheduledStartTime = new DateTime(2021, 7, 15, 9, 0, 0);
snippet.ScheduledEndTime = new DateTime(2021, 7, 15, 10, 30, 0);
liveBroadcast.Snippet = snippet;
var status = new LiveBroadcastStatus();
status.PrivacyStatus = "public";
status.SelfDeclaredMadeForKids = true;
liveBroadcast.Status = status;
var contentDetails = new LiveBroadcastContentDetails();
contentDetails.EnableAutoStart = true;
contentDetails.EnableAutoStop = true;
contentDetails.RecordFromStart = true;
contentDetails.EnableDvr = true;
liveBroadcast.ContentDetails = contentDetails;
var request = service.LiveBroadcasts.Insert(liveBroadcast, "snippet, contentDetails, status");
var response = await request.ExecuteAsync();
The answer is on LiveStreams and LiveBroadcasts: bind.
Once the LiveBroadcasts and LiveStreams have been created, you link them using LiveBroadcasts: bind
var liveStream = new LiveStream();
var snippet = new LiveStreamSnippet();
snippet.Title = "Key A";
liveStream.Snippet = snippet;
var cdn = new CdnSettings();
cdn.Format = "";
cdn.IngestionType = "rtmp";
cdn.FrameRate = "variable";
cdn.Resolution = "variable";
liveStream.Cdn = cdn;
var request = service.LiveStreams.Insert(liveStream, "snippet, cdn");
var response = await aux.ExecuteAsync();
var liveBroadcastsBind = service.LiveBroadcasts.Bind(IdLiveBroadcasts, "id, contentDetails");
liveBroadcastsBind.StreamId = IdLiveStream;
var response = await liveBroadcastsBind.ExecuteAsync();
Related
Using a service account, how to generate a google meet link by creating an event using google calendar API. I have my authorization all working fine. But I don't have any idea what. Here is my code, creating events successfully but not generating a google meet link. The response shows event creation details but nothing about google-meet. I'd really appreciate some help.
string calendarId = #"calendar-id";
string[] Scopes = { CalendarService.Scope.Calendar };
ServiceAccountCredential credential;
string path = Server.MapPath("~/file.json");
using (var stream =
new FileStream(path, FileMode.Open, FileAccess.Read))
{
var confg = Google.Apis.Json.NewtonsoftJsonSerializer.Instance.Deserialize<JsonCredentialParameters>(stream);
credential = new ServiceAccountCredential(
new ServiceAccountCredential.Initializer(confg.ClientEmail)
{
Scopes = Scopes
}.FromPrivateKey(confg.PrivateKey));
}
var service = new CalendarService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "Calendar API Sample",
});
var calendar = service.Calendars.Get(calendarId).Execute();
string token = credential.Token.AccessToken;
// Define parameters of request.
EventsResource.ListRequest listRequest = service.Events.List(calendarId);
listRequest.TimeMin = DateTime.Now;
listRequest.ShowDeleted = false;
listRequest.SingleEvents = true;
listRequest.MaxResults = 10;
listRequest.OrderBy = EventsResource.ListRequest.OrderByEnum.StartTime;
Event newEvent = new Event();
{
DateTime start = Convert.ToDateTime("2021-06-18T05:00:02.000Z");
DateTime end = Convert.ToDateTime("2021-06-18T06:00:02.000Z");
newEvent.Summary = "summary".ToString();
newEvent.Description = "description".ToString();
newEvent.Status = "confirmed";
newEvent.Creator = new Event.CreatorData
{
Email = " email-id",
Self = true
};
newEvent.Organizer = new Event.OrganizerData
{
Email = "email-id",
Self = true
};
newEvent.Start = new EventDateTime
{
DateTime = start,
TimeZone = "Asia/Kolkata"
};
newEvent.End = new EventDateTime
{
DateTime = end,
TimeZone = "Asia/Kolkata"
};
newEvent.HangoutLink = "";
newEvent.ConferenceData = new ConferenceData()
{
ConferenceSolution = new ConferenceSolution
{
Key = new ConferenceSolutionKey
{
Type = "hangoutsMeet"
}
},
CreateRequest = new CreateConferenceRequest()
{
ConferenceSolutionKey = new ConferenceSolutionKey()
{
Type = "hangoutsMeet"
},
RequestId = "some-random-string"
},
};
//newEvent.Attendees = new List<EventAttendee>()
//{
// new EventAttendee() { Email = "" }
//};
};
RestClient restClient = new RestClient();
RestRequest request = new RestRequest();
var serilaizeJson = JsonConvert.SerializeObject(newEvent, Formatting.None,
new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore
});
request.AddQueryParameter("key", "api-key");
request.AddHeader("Authorization", "Bearer " + token);
request.AddHeader("Accept", "application/json");
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", serilaizeJson, ParameterType.RequestBody);
restClient.BaseUrl = new System.Uri("https://www.googleapis.com/calendar/v3/calendars/calendar-id/events?conferenceDataVersion=1");
var response = restClient.Post(request);
if (response.StatusCode == System.Net.HttpStatusCode.OK)
{
dynamic returnFile = JObject.Parse(response.Content);
string link = returnFile["hangoutLink"];
}
Solution
Add the following object to the request body
conferenceData: {
createRequest: {
requestId: "sample123",
conferenceSolutionKey: { type: "hangoutsMeet" },
},
}
I have write a mail sending functionality using sendGrid in c#. It works properly but when attaching the generated pdf as attachement, it's not working.
var client = new SendGridClient(apiKey);
var msg = new SendGridMessage()
{
From = new EmailAddress(senderMailID, senderName),
Subject = "ABCD",
};
var attach = new Attachment();
attach.Filename = "ABC.pdf";
attach.Content = "~/Templates/output.pdf";
msg.AddAttachment(attach);
msg.AddTo(new EmailAddress(receiverMailID,receiverName));
var result = await client.SendEmailAsync(msg);
}
You should be converting the file to a base64 representation (as seen in examples here) of the file rather than adding a path to it.
A sample of the code needed:
var client = new SendGridClient(apiKey);
var msg = new SendGridMessage()
{
From = new EmailAddress(senderMailID, senderName),
Subject = "ABCD",
};
var bytes = File.ReadAllBytes("~/Templates/output.pdf");
var file = Convert.ToBase64String(bytes);
msg.AddAttachment("ABC.pdf", file);
var response = await client.SendEmailAsync(msg);
I am uploading a video to YouTube via their API with C#. I am using HttpClient.PostAsync() for that.
I get the following error after executing PostAsync(): Bad Request: Metadata part is too large.
I am not quite sure, if this error was generated by my code, or if the error happened on the YouTube API.
//Prepare the file from the form
var filePath = Path.GetTempFileName();
if (formFile.Length > 0)
{
using (var stream = new FileStream(filePath, FileMode.Create))
{
await formFile.CopyToAsync(stream);
}
}
//Application logic, not related to YouTube API
var user = await _userManager.FindByIdAsync(User.GetClaim(OpenIdConnectConstants.Claims.Subject));
var personalPot = await _context.PersonalPots.FirstOrDefaultAsync(i => i.Id == id);
if (user.Id != personalPot.Owner.Id)
{
return Unauthorized();
}
//Get the access token for the YouTube API
var accessToken = await _externalContentService.RefreshGoogleToken(personalPot.Id, new Guid(user.Id));
//Construct the properties, which will be send with the video file to upload
var properties = new Properties()
{
snippet = new Snippet()
{
title = title,
categoryId = categoryId,
defaultLanguage = defaultLanguage,
description = description,
tags = tags.Split(",")
},
status = new Status()
{
embeddable = embeddable == "true",
license = license,
privacyStatus = privacy,
publicStatsViewable = publicStatsViewable == "true"
}
};
//Construct the HttpClient to post the file to YouTube
var client = new HttpClient
{
BaseAddress = new Uri("https://www.googleapis.com/"),
Timeout = new TimeSpan(0, 0, 0, 0, Timeout.Infinite),
MaxResponseContentBufferSize = 2147483647
};
client.DefaultRequestHeaders.Add("Authorization", $"Bearer {accessToken}");
var requestContent = new MultipartFormDataContent();
var fileContent = new StreamContent(formFile.OpenReadStream());
var stringContent = new StringContent(JsonConvert.SerializeObject(properties), Encoding.UTF8, "application/json");
requestContent.Add(fileContent);
requestContent.Add(stringContent);
var result = await client.PostAsync("upload/youtube/v3/videos?part=snippet,status", requestContent);
//Result content will be "Bad Request; Metadata part too large"
if (!result.IsSuccessStatusCode)
{
return BadRequest(new {content = result.Content.ReadAsStringAsync(), reasonPhrase = result.ReasonPhrase});
}
I am trying to read a bucket at storage.googleapis.com, using the Amazon Web Services .Net SDK in C#.
Can anyone provide a working example of a S3 endpoint Config setup for google, just using the Auth. key/secret pair and a bucket name? Or using any other method to get this working?
According to this tutorial this should be a simple matter, but I get all sorts of exceptions when trying to follow the instructions given. Here is an extract of my current attempt - which throws a TrustFailure exception:
The remote certificate is invalid.
AmazonS3Config conf = new AmazonS3Config();
// Set regionEndpoint to null, or else the serviceURL will be ignored
conf.RegionEndpoint = null;
conf.ServiceURL = "https://s3.storage.googleapis.com";
conf.UseHttp = false;
conf.AuthenticationRegion = null;
conf.UseAccelerateEndpoint = false;
conf.UseDualstackEndpoint = false;
AWSCredentials cred = new BasicAWSCredentials("GOOG3LFXXXXXXXXXXXXX", "BQ6VeMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
IAmazonS3 client = new AmazonS3Client(cred, conf);
GetBucketVersioningRequest request = new GetBucketVersioningRequest { BucketName = "hisbucket" };
GetBucketVersioningResponse response = client.GetBucketVersioning(request);
I finally got the .NET SDK to upload to Google Cloud Storage with:
AWSConfigsS3.UseSignatureVersion4 = false;
AmazonS3Config config = new AmazonS3Config();
config.ServiceURL = "https://storage.googleapis.com";
config.SignatureVersion = "2";
AmazonS3Client client = new AmazonS3Client(accessKey, secretKey, config);
var transferUtilityConfig = new TransferUtilityConfig
{
ConcurrentServiceRequests = 1,
MinSizeBeforePartUpload = 6291456000,
};
var fileTransferUtilityRequest = new TransferUtilityUploadRequest
{
BucketName = bucketName,
FilePath = filePath,
PartSize = 6291456000,
Key = keyName,
};
TransferUtility fileTransferUtility = new TransferUtility(client, transferUtilityConfig);
fileTransferUtility.Upload(fileTransferUtilityRequest);
fileTransferUtility.Dispose();
You need a Amazon S3 service URL, an access key id, a secret access key id and the bucket name.
var s3Config = new AmazonS3Config
{
ServiceURL = Constants.AmazonS3ServiceUrl,
RegionEndpoint = Amazon.RegionEndpoint.EUWest1
};
string accessKeyId = Constants.AmazonAccessKeyId;
string secretAccessKey = Constants.AmazonSecretAccessKey;
var config = new AwsS3Config(){AmazonS3BucketName = Constants.AmazonS3BucketName};
var client = new AmazonS3Client(accessKeyId, secretAccessKey, s3Config);
Then, you should be able to make calls to the amazon client:
var request = new GetObjectRequest
{
BucketName = _bucketName,
Key = entity.Path
};
var response = _client.GetObjectAsync(request).Result;
The code above works on an S3 account, not particularly storage.googleapis.com, which is your case. Anyway, I hope this helps and answers your question.
I need to post Photos, Videos on Facebook walls from my MVC app. I'm getting below error
(OAuthException - #2500) An active access token must be used to query information about the current user.
Please help me. Please find below code which I'm using.
string appID = string.Empty;
string appSecretCode = string.Empty;
appID = "<<application Id>>";
appSecretCode = "<<app secretcode>>";
var fb = new FacebookClient();
dynamic result = fb.Get("oauth/access_token", new
{
client_id = appID,
client_secret = appSecretCode,
grant_type = "client_credentials",
scope = "publish_stream"
});
string accessToken = result.access_token;
var client = new FacebookClient(accessToken);
var postparameters = new Dictionary<string, object>();
var media = new FacebookMediaObject
{
FileName = #"Bday.jpg",
ContentType = "image/jpeg"
};
byte[] img = System.IO.File.ReadAllBytes(#"C:\Users\user\Desktop\Bday.jpg");
media.SetValue(img);
postparameters["source"] = media;
postparameters["access_token"] = result.access_token;
var result1 = client.Post(String.Format("https://graph.facebook.com/{0}/photos", "<<User ID>>"), postparameters);
You need to generate access token from https://developers.facebook.com/tools/explorer and try:
required AcccountId, pageid
dynamic parameters = new ExpandoObject();
parameters.message =modelList.message;
parameters.subject = modelList.subject;
parameters.account_id = modelList.AcccountId;
imageBytes = byte[] of image
parameters.source = new FacebookMediaObject{
ContentType = imageType,
FileName = Url
}.SetValue(imageBytes);
client.Post(pageid+ "/photos", parameters);
Hope it will help.