How to check if a YouTube channel is active - youtube

It looks regardless of whether a channel has been created by a user, the youtube api will return a channel for that particular user.
Java API
YouTube.Channels.List search = youTube.get().channels().list("id);
search.setPart("id");
ChannelListResponse res = search.execute();
List<Channel> searchResultList = search.getItems()
Channel channel = searchResultList.get(0); // there is always a channel
For the authenticated user, the channel seems to exist but when going to the YouTube profile, it states "You must create a channel to upload videos. Create a channel" or if going to the url without the user being authenticated, it'll say "This channel is not available at the moment. Please try again later."
How do check that a youtube channel is active or not. do i have to attempt to upload to it?

There are two ways to do this:
When you make an API call such as playlist management or video uploading, if there is no linked channel, the API will throw a GoogleJsonResponseException. Here's a code snippet showing you what happens when you try to make a playlist update API call and there's no channel:
try {
yt.playlistItems().insert("snippet,contentDetails", playlistItem).execute();
} catch (GoogleJsonResponseException e) {
GoogleJsonError error = e.getDetails();
for(GoogleJsonError.ErrorInfo errorInfo : error.getErrors()) {
if(errorInfo.getReason().equals("youtubeSignupRequired")) {
// Ask the user to create a channel and link their profile
}
}
}
You'll want to do something when you get "youtubeSignupRequired" as the reason for the error.
The other way is to check ahead of time. Make a Channel.List call and check for "items/status". You're looking for the boolean value "isLinked" to equal "true". Note that I've inserted a cast in this sample code because in the version of this sample, the client was returning a String value instead of a typed Boolean:
YouTube.Channels.List channelRequest = youtube.channels().list("status");
channelRequest.setMine("true");
channelRequest.setFields("items/status");
ChannelListResponse channelResult = channelRequest.execute();
List<Channel> channelsList = channelResult.getItems();
for (Channel channel : channelsList) {
Map<String, Object> status = (Map<String, Object>) channel.get("status");
if (true == (Boolean) status.get("isLinked")) {
// Channel is linked to a Google Account
} else {
// Channel is NOT linked to a Google Account
}
}

Related

Sending messages to specific users in Teams using Graph API

Any endpoint for sending messages to specific users in Teams via the Graph API?
(Edited because of clarity and added Custom-Requests)
You can send messages via Graph API to private users BUT there is a problem that you can't create a new chat between two users via the Graph API. This means that if you want to send a message from a user to a user, the chat must already exist. (Messages must first have been exchanged via the MSTeams client for a chat to exist)
So make sure that you have a open chat!
If so, have a look at this MSDoc (This document explains how you can list chats from a user):
https://learn.microsoft.com/en-us/graph/api/chat-list?view=graph-rest-beta&tabs=http
After you have all your chats listed, you can have a look at this MSDoc (This document explains how you can send a message to a user):
https://learn.microsoft.com/en-us/graph/api/chat-post-messages?view=graph-rest-beta&tabs=http
Pay attention to the permissions! For sending messages and listing chats there are only delegated permissions so far AND these calls are only available in BETA, so be carefull with it.
I can only provide you Java code for an example.
(For everything I do I use ScribeJava to get an Auth-Token)
For delegated permissions you need to have a "User-Auth-Token". That means you have to use a Password-Credential-Grant like this:
private void _initOAuth2Service()
{
oAuth2Service = new ServiceBuilder(clientId)
.apiSecret(clientSecret)
.defaultScope(GRAPH_SCOPE)
.build(MicrosoftAzureActiveDirectory20Api.custom(tenantId));
//PASSWORD CREDENTIALS FLOW
try
{
oAuth2Token = oAuth2Service.getAccessTokenPasswordGrant(username, password);
}
catch (IOException e) { e.printStackTrace(); }
catch (InterruptedException e) { e.printStackTrace(); }
catch (ExecutionException e) { e.printStackTrace(); }
}
username and password are the credentials from the user you want to send a message (sender).
Initial situation
This is my TeamsClient:
ScribeJava
Get all open chats
("me" in the URL is the user from above (sender).)
private Response _executeGetRequest()
{
final OAuthRequest request = new OAuthRequest(Verb.GET, "https://graph.microsoft.com/beta/me/chats");
oAuth2Service.signRequest(oAuth2Token, request);
return oAuth2Service.execute(request);
}
The response I get from this request looks like this:
{"#odata.context":"https://graph.microsoft.com/beta/$metadata#chats","value":[{"id":"{PartOfTheID}_{firstHalfOfUserID}-e52a55572b49#unq.gbl.spaces","topic":null,"createdDateTime":"2020-04-25T09:22:19.86Z","lastUpdatedDateTime":"2020-04-25T09:22:20.46Z"},{"id":"{secondUserChatID}#unq.gbl.spaces","topic":null,"createdDateTime":"2020-03-27T08:19:29.257Z","lastUpdatedDateTime":"2020-03-27T08:19:30.255Z"}]}
You can see that I have two open chats and get two entries back from the request.
Get the right conversatonID
You have to know that the id can be split in three sections. {JustAPartOfTheId}_{userId}#{EndOfTheId}. The {userId} is the id from your chatpartner (recipient).
This is a GraphExplorer response which gives me all users and all informations about them.
Now you can see that the first ID:
"id":"{PartOfTheID}_{firstHalfOfUserID}-e52a55572b49#unq.gbl.spaces"
matches the UserID after the "_".
You can split the ID at the "_" filter and find the ID you need.
Send Message to user
Now you know the right Id and can send a new request for the message like this:
final OAuthRequest request = new OAuthRequest(Verb.POST, "https://graph.microsoft.com/beta/chats/{PartOfTheID}_{firstHalfOfUserID}-e52a55572b49#unq.gbl.spaces/messages");
oAuth2Service.signRequest(oAuth2Token, request);
request.addHeader("Accept", "application/json, text/plain, */*");
request.addHeader("Content-Type", "application/json");
request.setPayload("{\"body\":{\"content\":\" " + "Hi Hi Daniel Adu-Djan" + "\"}}");
oAuth2Service.execute(request);
GraphAPI-Custom-Requests
In the Graph-SDK is no opportunity to use the beta endpoint except for Custom-Requests. (For these requests I also use ScribeJava to get an Auth-Token)
Set the BETA-Endpoint
When you want to use the BETA-Endpoint you have to use the setEndpoint() function like this:
IGraphServiceClient graphUserClient = _initGraphServiceUserClient();
//Set Beta-Endpoint
graphUserClient.setServiceRoot("https://graph.microsoft.com/beta");
Get all chats
try
{
JsonObject allChats = graphUserClient.customRequest("/me/chats").buildRequest().get();
}
catch(ClientException ex) { ex.printStacktrace(); }
Same response like above
Same situation with the userId => split and filter
Send message
IGraphServiceClient graphUserClient = _initGraphServiceUserClient();
//Set Beta-Endpoint again
graphUserClient.setServiceRoot("https://graph.microsoft.com/beta");
try
{
JsonObject allChats = graphUserClient.customRequest("/chats/{PartOfTheID}_{firstHalfOfUserID}-e52a55572b49#unq.gbl.spaces/messages").buildRequest().post({yourMessageAsJsonObject});
}
catch(ClientException ex) { ex.printStacktrace();
}
Here is a little GIF where you can see that I didn't type anything. I just started my little application and it sends messages automatically.
I hope this helps you. Feel free to comment if you don't understand something! :)
Best regards!
As of now, We do not have any endpoint to send messages to specific users via Graph API.
You may submit/vote a feature request in the UserVoice or just wait for the update from the Product Team.
You can vote for a below feature requests which are already created. All you have to do is enter your email ID and vote.
https://microsoftteams.uservoice.com/forums/555103-public/suggestions/40642198-create-new-1-1-chat-using-graph-api
https://microsoftteams.uservoice.com/forums/555103-public/suggestions/39139705-is-there-any-way-to-generate-chat-id-by-using-grap
Update:
Please find below one more user voice created for the same in Microsoft Graph user voices and vote for it.
https://microsoftgraph.uservoice.com/forums/920506-microsoft-graph-feature-requests/suggestions/37802836-add-support-for-creating-chat-messages-on-the-user

how to get youtube live api stream key

How can I bind my YouTube stream key to match previous video.
I'm trying to use java to do it but getting no where.
I'm looking at the example given to create the broadcast stream but it doesn't have the keeping same key.
I've gotten help on this before. Please try do some research on Google and then ask the question. You can see How can I change the stream my event uses via the YouTube live api?. Which will help you as it did me.
In short this was the code i received for help.
Credit to #M. Prokhorov
YouTube yt = ... // your reference to YouTube
String broadcastId = ... // your broadcast Id
String newStreamId = ... // identifier of stream you want to bind
String apiKEy = ... // your API key
// you can define other response parts if you want more or don't want some of these
String responseParts = "id,status,contentDetails.boundStreamId";
yt.liveBroadcasts().bind(broadcastId, responseParts)
.setApiKey(apiKey)
.setStreamId(streamId)
// other data you might want in request
.execute()

Twilio Video - How to get current number of participants in a room?

I would like to know how many people are currently connected to a room when using Twilio Video.
Twilio has a REST API to get a room resource, but it does not return current number of participants.
https://www.twilio.com/docs/api/video/rooms-resource#get-by-sid
Only way i see is to subscribe to status callback to "participant connected" and disconnected events and manually keep track of how many participants are connected or left the room.
Is there a better way to do this ?
You can use twilio server side sdk, Let me share NodeJS example so you get better idea on implementation.
First lets define function that init twilio client and fetch connected participants of room.
async function getConnectedParticipants(roomName) {
var Twilio = require('twilio');
var apiKeySid = "YOUR_TWILIO_API_KEY_SID_HERE";
var apiKeySecret = "YOUR_TWILIO_API_SECRET_HERE";
var accountSid = "YOUR_TWILIO_ACCOUNT_SID_HERE";
var client = new Twilio(apiKeySid, apiKeySecret, {accountSid: accountSid});
var list = await client.video.rooms(roomName)
.participants
.list({status: 'connected'});
return list;
}
Now let's use our function that return you connected participants.
var connectedParticipants = await getConnectedParticipants("YourRoomName");
// print all connected participants
console.log('connectedParticipants', connectedParticipants);
Note: I have used async and await in this example, please check more on that before implementation.
Twilio developer evangelist here.
Keeping a server side list of the participants' identities based on the participant connected and disconnected events is probably the best way to work this out right now.
One alternative is to get this information from the front end. The JavaScript library allows you to query the participants in a room. You could periodically, or based on events, query that property and send it to your server via Ajax too.
Let me know if that helps.
Update
The Rooms API now allows you to retrieve information on participants that have connected to a room. To get the currently connected users in a room using Node.js, for example, the code would look like:
var client = new Twilio(apiKeySid, apiKeySecret, {accountSid: accountSid});
client.video.rooms(roomSid).participants
.list({status: 'connected'}, (err, participants) => {
if (err) { console.error(err); return; }
console.log(participants.length);
});

Live stream using Youtube's Livestreaming API to someone else's channel

I tried youtube's watchme app for live streaming and I understand the code fairly. In my use case the user needs to be able to live stream to another channel. I understand there is a need of Stream key here, but I need a rough guidance on where I need to change in the code. Any hints or a rough idea would do too. I just need headstart.
If you are using Youtube WatchMe app for Android, it will create live events on your Youtube account. If you want the user to type a Stream Key from a Live stream issued from another Youtube account you will have to create a function similar to the startStreaming method :
public void startStreaming(EventData event) {
//the event is already started on your external live stream
//String broadcastId = event.getId();
//new StartEventTask().execute(broadcastId);
Intent intent = new Intent(getApplicationContext(),
StreamerActivity.class);
intent.putExtra(YouTubeApi.RTMP_URL_KEY, event.getIngestionAddress());
// we don't need this since it's only used to end the live event
intent.putExtra(YouTubeApi.BROADCAST_ID_KEY, "");
startActivityForResult(intent, REQUEST_STREAMER);
}
Note that broadcast id is sent to StreamerActivity in order to be able to finish the event (endEvent) which you won't be able to do using an external live stream.
event.getIngestionAddress() is the Stream Key url eg :
rtmp://a.rtmp.youtube.com/live2/<Stream key>
So you can create a method like the following :
public void startStreaming(String streamKey) {
String url = "rtmp://a.rtmp.youtube.com/live2/" + streamKey;
Intent intent = new Intent(getApplicationContext(), StreamerActivity.class);
intent.putExtra(YouTubeApi.RTMP_URL_KEY, url);
intent.putExtra(YouTubeApi.BROADCAST_ID_KEY, "");
startActivityForResult(intent, REQUEST_STREAMER);
}

How can I get all my subscribed channel using youtube api v3

I'm new to youtube api v3, and I have a problem when get all my subscribed channel. I've subscribed 65 channel but I can only get 50 each api call. So, Is there any way to get all?
Another thing is, I have a channelID, is there any api to check this channel in a list of my subscribed channel?
Youtube API restricts 50 results per call. In case you were asking whether you can get all 65 in the same call, then the answer is no. However, if you meant whether all 65 can be retrieved then, yes. You'll need to use the nextPageToken paramter value and pass it to the pageToken parameter which will take you to the next page. In code, it can be handled in the following way(as shown in the documentation):
var nextPageToken = '';
// This loop retrieves a set of playlist items and checks the nextPageToken
// in the response to determine whether the list contains additional items.
// It repeats that process until it has retrieved all of the items in the list.
while (nextPageToken != null) {
var playlistResponse = YouTube.PlaylistItems.list('snippet', {
playlistId: playlistId,
maxResults: 25,
pageToken: nextPageToken
});
Regarding your ChannelID problem, from your description I understand you want to check whether you are subscribed to a particular channel in case you have it's ID. I believe the Activities method of Youtube API should be able to help you out. Look at contentDetails.subscription property. I hope that resolves your problem.

Resources