How can end My Youtube live stream API in c#? - c#

How to stop my livestream in YouTube while completed my live telecast using c#
How to stop the livestream Using c# Code, can you please give some suggestion
string[] scopes = { "https://www.googleapis.com/auth/youtube", "https://www.googleapis.com/auth/youtube.upload" };
var creadentails = GoogleWebAuthorizationBroker.AuthorizeAsync(
new ClientSecrets
{
ClientId = YTPublishSettings.PublisherClientId,
ClientSecret = YTPublishSettings.PublisherClientSecret,
},
scopes, "user", default).Result;
if (creadentails.Token.IsExpired(SystemClock.Default))
creadentails.RefreshTokenAsync(CancellationToken.None).Wait();
var secrets = new ClientSecrets
{
ClientId = YTPublishSettings.PublisherClientId,
ClientSecret = YTPublishSettings.PublisherClientSecret,
};
var token = new TokenResponse { RefreshToken = creadentails.Token.RefreshToken };
var credentials = new UserCredential(new GoogleAuthorizationCodeFlow(
new GoogleAuthorizationCodeFlow.Initializer { ClientSecrets = secrets }),
"user", token);
var service = new YouTubeService(new BaseClientService.Initializer
{
HttpClientInitializer = credentials,
ApplicationName = "**************",
});
var broadcast = new LiveStream
{
Cdn = new CdnSettings
{
FrameRate = "35fps",
IngestionType = "rtmp",
Resolution = "720p"
},
Snippet = new LiveStreamSnippet
{
Description = Description,
Title = Title,
},
};
var request = service.LiveStreams.Delete(YTPublishSettings.PublisherId);
var response = request.Execute();
return new YouTubeStreamDeleteStatus()
{
success = "Deleted",
};
How can end My YouTube live stream API in c#?

Related

How to refresh a Google OAuth2 AccessToken

I have seen a lot of questions about this with varying answers. Some are for different languages. It is not clear to me the correct way to handle this issue.
This is what I have come up with:
public bool Init()
{
UserCredential credential;
ClientSecrets secrets = new ClientSecrets()
{
ClientId = m_ClientID,
ClientSecret = m_ClientSecret
};
if (!m_LogFilePathSet)
return false;
try
{
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
secrets,
m_Scopes,
"user",
CancellationToken.None,
new FileDataStore("MSAToolsSoftware.GMail.Application")).Result;
if (credential.Token.IsExpired(Google.Apis.Util.SystemClock.Default))
{
var refreshResult = credential.RefreshTokenAsync(CancellationToken.None).Result;
}
var initializer = new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = m_ApplicationName
};
m_Service = new GmailService(initializer);
}
catch(Exception ex)
{
SimpleLog.Log(ex);
return false;
}
return true;
}
Is this the correct way to refresh the access token (if required)?
Thank you.

Uploading video using Youtube API using OAuth2

I am trying to upload videos using OAuth2. But I keep getting an error like this -
{Google.Apis.Requests.RequestErrorUnauthorized
[401]Errors
[ Message[Unauthorized] Location[Authorization - header]
Reason[youtubeSignupRequired] Domain[youtube.header]]}
I have my client id,secret key, access token, refresh token all set up. The token is still valid, refresh token not expired.
Here is how it looks.
UserCredential credential;
var token = new TokenResponse { AccessToken = accesstoken, RefreshToken = refreshToken };
using (var stream = new FileStream(System.Web.HttpContext.Current.Server.MapPath("~/client_id.json"), FileMode.Open, FileAccess.Read))
{
credential = new UserCredential(new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
{
ClientSecretsStream = stream,
//ClientSecrets = new ClientSecrets { ClientId = clientID, ClientSecret = clientSecret },
Scopes = new string[] { YouTubeService.Scope.YoutubeUpload }
}), "user", token);
}
var youtubeService = new YouTubeService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = Assembly.GetExecutingAssembly().GetName().Name
});
var video = new Video();
video.Snippet = new VideoSnippet();
video.Snippet.Title = name;
video.Snippet.Description = description;
video.Snippet.Tags = new string[] { "test" };
video.Snippet.CategoryId = "22"; // See https://developers.google.com/youtube/v3/docs/videoCategories/list
video.Status = new VideoStatus();
video.Status.PrivacyStatus = "public"; // or "private" or "public"
using (var fileStream = new FileStream(outputfile, FileMode.Open))
{
var videosInsertRequest = youtubeService.Videos.Insert(video, "snippet,status", fileStream, "video/*");
videosInsertRequest.ProgressChanged += videosInsertRequest_ProgressChanged;
videosInsertRequest.ResponseReceived += videosInsertRequest_ResponseReceived;
videosInsertRequest.Upload();
}

youtube Add Subscription via C#

I am building a YouTube app for windows 8.1.
I am having a trouble with, add(Insert) subscription is fail
my code:
var credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
new Uri("ms-appx:///Assets/client_secrets.json"),
new[] { Uri.EscapeUriString(YouTubeService.Scope.Youtube) },
"user",
CancellationToken.None);
var youtubeService = new YouTubeService(new BaseClientService.Initializer()
{
ApiKey = "XXXXXXXXXXXXXXXXXXXXXXXXXXXX",
HttpClientInitializer = credential,
ApplicationName = "AppName"
});
Subscription body = new Subscription();
body.Snippet = new SubscriptionSnippet();
body.Snippet.ChannelId = "UC-kezFAw46x-9ctBUqVe86Q";
try
{
var addSubscriptionRequest = youtubeService.Subscriptions.Insert(body, "snippet");
var addSubscriptionResponse = await addSubscriptionRequest.ExecuteAsync();
}
catch (Exception e)
{
throw e;
}
When I set a breakpoint at the first line.
when execute to last line, breaks this function
Update(2015-11-14):
Error Message:
The subscription resource specified in the request must use the snippet.resorceId property to identify the channel that is being subscribed to [400]
Successful Code:
var credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
new Uri("ms-appx:///Assets/client_secrets.json"),
new[] { Uri.EscapeUriString(YouTubeService.Scope.Youtube) },
"user",
CancellationToken.None);
var youtubeService = new YouTubeService(new BaseClientService.Initializer()
{
//ApiKey = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
HttpClientInitializer = credential,
ApplicationName = "4GameTV"
});
try
{
Subscription body = new Subscription();
body.Snippet = new SubscriptionSnippet();
body.Snippet.ResourceId = new ResourceId();
body.Snippet.ResourceId.ChannelId = "UC-kezFAw46x-9ctBUqVe86Q"; //replace with specified channel id
var addSubscriptionRequest = youtubeService.Subscriptions.Insert(body, "snippet");
var addSubscriptionResponse = await addSubscriptionRequest.ExecuteAsync();
}
catch (Exception e)
{
throw e;
}
Your authentication seems a bit off from what I normally use. Also ApiKey is only needed if you want to access public data.
string[] scopes = new string[] { YouTubeService.Scope.Youtube };
// here is where we Request the user to give us access, or use the Refresh Token that was previously stored in %AppData%
UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets { ClientId = clientId, ClientSecret = clientSecret }
, scopes
, "test"
, CancellationToken.None
, new FileDataStore("Daimto.YouTube.Auth.Store")).Result;
YouTubeService service = new YouTubeService(new YouTubeService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "YouTube Data API Sample",
});

GoogleWebAuthorizationBroker.AuthorizeAsync throws an error

i was trying to create and run the sample project given in this link.
here is the code:
namespace GmailQuickstart
{
class Program
{
static string[] Scopes = { GmailService.Scope.GmailReadonly };
static string ApplicationName = "Gmail API Quickstart";
static void Main(string[] args)
{
UserCredential credential;
using (var stream =
new FileStream("client_secret.json", FileMode.Open, FileAccess.Read))
{
string credPath = System.Environment.GetFolderPath(
System.Environment.SpecialFolder.Personal);
credPath = Path.Combine(credPath, ".credentials");
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
Scopes,
"user",
CancellationToken.None,
new FileDataStore(credPath, true)).Result;
Console.WriteLine("Credential file saved to: " + credPath);
}
// Create Gmail API service.
var service = new GmailService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
// Define parameters of request.
UsersResource.LabelsResource.ListRequest request = service.Users.Labels.List("me");
// List labels.
IList<Label> labels= request.Execute().Labels;
Console.WriteLine("Labels:");
if (labels != null && labels.Count > 0)
{
foreach (var labelItem in labels)
{
Console.WriteLine("{0}", labelItem.Name);
}
}
else
{
Console.WriteLine("No labels found.");
}
Console.Read();
}
}
}
after i have done everything stated in google's documentation, including issuing a secrets.json file for my application/product, i ran it.
It fails with an exception, containing a "An invalid argument was supplied" inner exception.
I have retried everything with a new acocunt given new api credentials, etc., and still same error occurs. what am i doing wrong?
Try this
ClientSecrets secrets = new ClientSecrets()
{
ClientId = CLIENT_ID,
ClientSecret = CLIENT_SECRET
};
var token = new TokenResponse { RefreshToken = REFRESH_TOKEN };
var credentials = new UserCredential(new GoogleAuthorizationCodeFlow(
new GoogleAuthorizationCodeFlow.Initializer
{
ClientSecrets = secrets
}),
"user",
token);
var service = new GmailService(new BaseClientService.Initializer()
{
HttpClientInitializer = credentials,
ApplicationName = "ApplicationName"
});

Unable to upload CSV file using google analytics API in C#

I'm trying to upload a CSV file using google analytics api and it gives me a status failed.
The error that I'm getting is variable is null: parameter name base uri
I have given the permissions for google analytics api in developer console and I'm using service account to generate the key and the id's.
This is my code snippet
const string serviceAccountEmail = "716698526626-6s61a3tbe1m5mofo9#developer.gserviceaccount.com";
const string serviceAccountPKCSP12FilePath = #"C:\SVN\GAPforInboundandWeb-1f6bfb.p12";
X509Certificate2 certificate = new X509Certificate2(serviceAccountPKCSP12FilePath, "notasecret", X509KeyStorageFlags.Exportable);
ServiceAccountCredential credential = new ServiceAccountCredential(
new ServiceAccountCredential.Initializer(serviceAccountEmail)
{
Scopes = new[] { AnalyticsService.Scope.Analytics }
}.FromCertificate(certificate));
var service = new AnalyticsService(new BaseClientService.Initializer
{
HttpClientInitializer = credential,
ApplicationName = "GAPforInboundandWeb"
});
FileStream realCsv = new FileStream("c:\\real.csv", FileMode.Open);
// Create the service.
try
{
var upload = service.Management.DailyUploads.Upload("50288725", "UA-50288725-1", "Oy_0JTPvRGCB3Vg5OKVIMQ",
"2014-09-22", 1, ManagementResource.DailyUploadsResource.UploadMediaUpload.TypeEnum.Cost, realCsv,
"application/octet-stream");
upload.Reset = true;
var res = upload.Upload();
res.BytesSent.ToString();
res.Status.ToString();
}
           
I resolved the same problem. In my case, its a wrong DataSourceId.
Try this:
const string serviceAccountEmail = "716698526626-6s61a3tbe1m5mofo9#developer.gserviceaccount.com";
const string serviceAccountPKCSP12FilePath = #"C:\SVN\GAPforInboundandWeb-1f6bfb.p12";
X509Certificate2 certificate = new X509Certificate2(serviceAccountPKCSP12FilePath, "notasecret", X509KeyStorageFlags.Exportable);
ServiceAccountCredential credential = new ServiceAccountCredential(
new ServiceAccountCredential.Initializer(serviceAccountEmail)
{
Scopes = new[] { AnalyticsService.Scope.Analytics }
}.FromCertificate(certificate));
var service = new AnalyticsService(new BaseClientService.Initializer
{
HttpClientInitializer = credential,
ApplicationName = "GAPforInboundandWeb"
});
FileStream realCsv = new FileStream("c:\\real.csv", FileMode.Open);
// Create the service.
try
{
var dataSource = srv.Management.CustomDataSources.List(AccountId, WebId).Execute();
var strDataSourceId = "Oy_0JTPvRGCB3Vg5OKVIMQ";
if(dataSource!=null && dataSource.Items.Length>0)
strDataSourceId =dataSource.Items[0].Id;
var upload = service.Management.DailyUploads.Upload("50288725", "UA-50288725-1", strDataSourceId,
"2014-09-22", 1, ManagementResource.DailyUploadsResource.UploadMediaUpload.TypeEnum.Cost, realCsv,
"application/octet-stream");
upload.Reset = true;
var res = upload.Upload();
res.BytesSent.ToString();
res.Status.ToString();
}
Use List methods on service.Management.CustomDataSources and service.Management.Uploads in this order for check your config.

Categories

Resources