How to check if a YouTube channel is active

2019-03-01 14:52发布

问题:

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?

回答1:

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
    }
}