使用YouTube Data API v3确定YouTube频道的上传速度

huangapple go评论65阅读模式
英文:

Determine a YouTube channel's upload rate using YouTube Data API v3

问题

我正在编写一个使用YouTube Data API v3的Java应用程序。我希望能够确定频道的上传速度。例如,如果一个频道成立一周,已经发布了2个视频,我希望有一种方法来确定该频道的上传速度为每周2个视频。我如何使用YouTube API实现这一点?

import com.google.api.client.googleapis.json.GoogleJsonResponseException;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.youtube.YouTube;
import com.google.api.services.youtube.model.Channel;
import com.google.api.services.youtube.model.ChannelListResponse;

import java.io.IOException;
import java.io.InputStream;
import java.security.GeneralSecurityException;
import java.util.Collection;
import java.util.Collections;
import java.util.Properties;

public class ApiExample {
    public static void main(String[] args)
            throws GeneralSecurityException, IOException, GoogleJsonResponseException {
        Properties properties = new Properties();
        try {
            InputStream in = ApiExample.class.getResourceAsStream("/" + "youtube.properties");
            properties.load(in);

        } catch (IOException e) {
            System.err.println("There was an error reading " + "youtube.properties" + ": " + e.getCause()
                    + " : " + e.getMessage());
            System.exit(1);
        }
        YouTube youtubeService = new YouTube.Builder(new NetHttpTransport(), new JacksonFactory(), new HttpRequestInitializer() {
            public void initialize(HttpRequest request) throws IOException {
            }
        }).setApplicationName("API Demo").build();
        // Define and execute the API request
        YouTube.Channels.List request = youtubeService.channels()
                .list("snippet,contentDetails,statistics");
        String apiKey = properties.getProperty("youtube.apikey");
        request.setKey(apiKey);
        ChannelListResponse response = request.setId("UC_x5XG1OV2P6uZZ5FSM9Ttw").execute();
        for (Channel channel : response.getItems()) {
            /* What do I do here to get the individual channel's upload rate? */
        }
    }
}

上面的示例使用了YouTube Developers频道,但我希望能够在任何频道上执行这个操作。

英文:

I am writing a Java application that uses YouTube Data API v3. I want to be able to determine a channel's upload rate. For example, if a channel is one week old, and has published 2 videos, I want some way to determine that the channel's upload rate is 2 videos/week. How would I do this using the YouTube API?

import com.google.api.client.googleapis.json.GoogleJsonResponseException;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.youtube.YouTube;
import com.google.api.services.youtube.model.Channel;
import com.google.api.services.youtube.model.ChannelListResponse;

import java.io.IOException;
import java.io.InputStream;
import java.security.GeneralSecurityException;
import java.util.Collection;
import java.util.Collections;
import java.util.Properties;

public class ApiExample {
    public static void main(String[] args)
            throws GeneralSecurityException, IOException, GoogleJsonResponseException {
        Properties properties = new Properties();
        try {
            InputStream in = ApiExample.class.getResourceAsStream("/" + "youtube.properties");
            properties.load(in);

        } catch (IOException e) {
            System.err.println("There was an error reading " + "youtube.properties" + ": " + e.getCause()
                    + " : " + e.getMessage());
            System.exit(1);
        }
        YouTube youtubeService = new YouTube.Builder(new NetHttpTransport(), new JacksonFactory(), new HttpRequestInitializer() {
            public void initialize(HttpRequest request) throws IOException {
            }
        }).setApplicationName("API Demo").build();
        // Define and execute the API request
        YouTube.Channels.List request = youtubeService.channels()
                .list("snippet,contentDetails,statistics");
        String apiKey = properties.getProperty("youtube.apikey");
        request.setKey(apiKey);
        ChannelListResponse response = request.setId("UC_x5XG1OV2P6uZZ5FSM9Ttw").execute();
        for (Channel channel : response.getItems()) {
            /* What do I do here to get the individual channel's upload rate? /
        }
    }
}

The above example uses the YouTube Developers channel, but I want to be able to do this with any channel.

答案1

得分: 2

根据官方文档,一旦调用 Channels.list API 端点,该端点会返回指定频道的元数据,一个 Channels 资源 ,您可以使用以下属性:

> statistics.videoCount(无符号长整型)
> 上传到频道的公共视频数量。

因此,事情几乎是显而易见的:使此属性返回的值持久化(例如保存到文件中),并安排您的程序每周发出一次,以计算您所需的上传率


现在,关于您上面的代码,您应该首先摆脱:

for (Channel channel : response.getItems()) {
    /* What do I do here to get the individual channel's upload rate? */
}

因为 items 属性最多只会包含 一个 项目。一个好的做法是断言这个条件:

assert response.getItems().size() <= 1;

所需的 videoCount 属性的值将在 ChannelStatistics 类的 getVideoCount 方法下可访问:

response.getItems().get(0).getStatistics().getVideoCount()

当然,由于只向 API 请求真正有用的信息总是一个好习惯,我还建议您使用参数 fields(方法 setFields)的形式:

request.setFields("items(statistics(videoCount))")

例如在 request.setKey(apiKey) 之后插入。

这样,API 将仅返回您所需的属性。


附加信息

我还必须提到,上述断言仅在您将仅一个频道 ID 传递给 API 端点时才是正确的。如果将来您想要一次性计算 N 个频道(其中 N <= 50)的上传率,那么上述条件将变为 size() <= N

一次性调用 Channels.list 在多个频道上是可能的,因为此端点的 id 属性允许指定为逗号分隔的频道 ID 列表。

英文:

According to the official docs, once you invoke the Channels.list API endpoint -- that returns the specified channel's meta-data, a Channels resource --, you have at your disposal the following property:

> statistics.videoCount (unsigned long)
> The number of public videos uploaded to the channel.

Therefore, things are almost obvious: make the value returned by this property persistent (e.g. save it into a file) and arrange your program such that to be issued weekly for to compute your desired upload rate.


Now, for what concerns your code above, you should first get rid of:

for (Channel channel : response.getItems()) {
/* What do I do here to get the individual channel&#39;s upload rate? /
}

since the items property will contain at most one item. A good practice would be to assert this condition:

assert response.getItems().size() &lt;= 1;

The value of the needed videoCount property will be accessible under the method getVideoCount of ChannelStatistics class:

response.getItems().get(0).getStatistics().getVideoCount().

Of course, since is always good to ask from the API only the info that is really of use, I would also recommend you to use the parameter fields (the method setFields) in the form of:

request.setFields(&quot;items(statistics(videoCount))&quot;),

inserted, for example, after request.setKey(apiKey).

This way the API will send back to you only the property that you need.


Addendum

I also have to mention that the assertion above is correct only when you pass to the API endpoint (as you currently do within your code above) one channel ID only. If in the future you'll want to compute in one go the upload rate of N channels (with N &lt;= 50), then the condition above will look like size() &lt;= N.

The call of Channels.list in one go on multiple channels is possible, since this endpoint's id property is allowed to be specified as a comma-separated list of channel IDs.

huangapple
  • 本文由 发表于 2020年9月29日 23:50:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/64123167.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定