|
| 1 | +package com.google.api.services.samples.youtube.cmdline.analytics; |
| 2 | + |
| 3 | +import com.google.api.client.auth.oauth2.Credential; |
| 4 | +import com.google.api.client.http.HttpTransport; |
| 5 | +import com.google.api.client.http.javanet.NetHttpTransport; |
| 6 | +import com.google.api.client.json.JsonFactory; |
| 7 | +import com.google.api.client.json.jackson2.JacksonFactory; |
| 8 | +import com.google.api.services.samples.youtube.cmdline.Auth; |
| 9 | +import com.google.api.services.youtube.YouTube; |
| 10 | +import com.google.api.services.youtube.model.Channel; |
| 11 | +import com.google.api.services.youtube.model.ChannelListResponse; |
| 12 | +import com.google.api.services.youtubeAnalytics.YouTubeAnalytics; |
| 13 | +import com.google.api.services.youtubeAnalytics.model.ResultTable; |
| 14 | +import com.google.api.services.youtubeAnalytics.model.ResultTable.ColumnHeaders; |
| 15 | +import com.google.common.collect.Lists; |
| 16 | + |
| 17 | +import java.io.IOException; |
| 18 | +import java.io.PrintStream; |
| 19 | +import java.math.BigDecimal; |
| 20 | +import java.util.List; |
| 21 | + |
| 22 | +/** |
| 23 | + * This example uses the YouTube Data and YouTube Analytics APIs to retrieve |
| 24 | + * YouTube Analytics data. It also uses OAuth 2.0 for authorization. |
| 25 | + * |
| 26 | + * @author Christoph Schwab-Ganser and Jeremy Walker |
| 27 | + */ |
| 28 | +public class YouTubeAnalyticsReports { |
| 29 | + |
| 30 | + /** |
| 31 | + * Define a global instance of the HTTP transport. |
| 32 | + */ |
| 33 | + private static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport(); |
| 34 | + |
| 35 | + /** |
| 36 | + * Define a global instance of the JSON factory. |
| 37 | + */ |
| 38 | + private static final JsonFactory JSON_FACTORY = new JacksonFactory(); |
| 39 | + |
| 40 | + /** |
| 41 | + * Define a global instance of a Youtube object, which will be used |
| 42 | + * to make YouTube Data API requests. |
| 43 | + */ |
| 44 | + private static YouTube youtube; |
| 45 | + |
| 46 | + /** |
| 47 | + * Define a global instance of a YoutubeAnalytics object, which will be |
| 48 | + * used to make YouTube Analytics API requests. |
| 49 | + */ |
| 50 | + private static YouTubeAnalytics analytics; |
| 51 | + |
| 52 | + /** |
| 53 | + * This code authorizes the user, uses the YouTube Data API to retrieve |
| 54 | + * information about the user's YouTube channel, and then fetches and |
| 55 | + * prints statistics for the user's channel using the YouTube Analytics API. |
| 56 | + * |
| 57 | + * @param args command line args (not used). |
| 58 | + */ |
| 59 | + public static void main(String[] args) { |
| 60 | + |
| 61 | + // These scopes are required to access information about the |
| 62 | + // authenticated user's YouTube channel as well as Analytics |
| 63 | + // data for that channel. |
| 64 | + List<String> scopes = Lists.newArrayList( |
| 65 | + "https://www.googleapis.com/auth/yt-analytics.readonly", |
| 66 | + "https://www.googleapis.com/auth/youtube.readonly" |
| 67 | + ); |
| 68 | + |
| 69 | + try { |
| 70 | + // Authorize the request. |
| 71 | + Credential credential = Auth.authorize(scopes, "analyticsreports"); |
| 72 | + |
| 73 | + // This object is used to make YouTube Data API requests. |
| 74 | + youtube = new YouTube.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential) |
| 75 | + .setApplicationName("youtube-analytics-api-report-example") |
| 76 | + .build(); |
| 77 | + |
| 78 | + // This object is used to make YouTube Analytics API requests. |
| 79 | + analytics = new YouTubeAnalytics.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential) |
| 80 | + .setApplicationName("youtube-analytics-api-report-example") |
| 81 | + .build(); |
| 82 | + |
| 83 | + // Construct a request to retrieve the current user's channel ID. |
| 84 | + YouTube.Channels.List channelRequest = youtube.channels().list("id,snippet"); |
| 85 | + channelRequest.setMine(true); |
| 86 | + channelRequest.setFields("items(id,snippet/title)"); |
| 87 | + ChannelListResponse channels = channelRequest.execute(); |
| 88 | + |
| 89 | + // List channels associated with the user. |
| 90 | + List<Channel> listOfChannels = channels.getItems(); |
| 91 | + |
| 92 | + // The user's default channel is the first item in the list. |
| 93 | + Channel defaultChannel = listOfChannels.get(0); |
| 94 | + String channelId = defaultChannel.getId(); |
| 95 | + |
| 96 | + PrintStream writer = System.out; |
| 97 | + if (channelId == null) { |
| 98 | + writer.println("No channel found."); |
| 99 | + } else { |
| 100 | + writer.println("Default Channel: " + defaultChannel.getSnippet().getTitle() + |
| 101 | + " ( " + channelId + " )\n"); |
| 102 | + |
| 103 | + printData(writer, "Views Over Time.", executeViewsOverTimeQuery(analytics, channelId)); |
| 104 | + printData(writer, "Top Videos", executeTopVideosQuery(analytics, channelId)); |
| 105 | + printData(writer, "Demographics", executeDemographicsQuery(analytics, channelId)); |
| 106 | + } |
| 107 | + } catch (IOException e) { |
| 108 | + System.err.println("IOException: " + e.getMessage()); |
| 109 | + e.printStackTrace(); |
| 110 | + } catch (Throwable t) { |
| 111 | + System.err.println("Throwable: " + t.getMessage()); |
| 112 | + t.printStackTrace(); |
| 113 | + } |
| 114 | + } |
| 115 | + |
| 116 | + /** |
| 117 | + * Retrieve the views and unique viewers per day for the channel. |
| 118 | + * |
| 119 | + * @param analytics The service object used to access the Analytics API. |
| 120 | + * @param id The channel ID from which to retrieve data. |
| 121 | + * @return The API response. |
| 122 | + * @throws IOException if an API error occurred. |
| 123 | + */ |
| 124 | + private static ResultTable executeViewsOverTimeQuery(YouTubeAnalytics analytics, |
| 125 | + String id) throws IOException { |
| 126 | + |
| 127 | + return analytics.reports() |
| 128 | + .query("channel==" + id, // channel id |
| 129 | + "2012-01-01", // Start date. |
| 130 | + "2012-01-14", // End date. |
| 131 | + "views,uniques") // Metrics. |
| 132 | + .setDimensions("day") |
| 133 | + .setSort("day") |
| 134 | + .execute(); |
| 135 | + } |
| 136 | + |
| 137 | + /** |
| 138 | + * Retrieve the channel's 10 most viewed videos in descending order. |
| 139 | + * |
| 140 | + * @param analytics the analytics service object used to access the API. |
| 141 | + * @param id the string id from which to retrieve data. |
| 142 | + * @return the response from the API. |
| 143 | + * @throws IOException if an API error occurred. |
| 144 | + */ |
| 145 | + private static ResultTable executeTopVideosQuery(YouTubeAnalytics analytics, |
| 146 | + String id) throws IOException { |
| 147 | + |
| 148 | + return analytics.reports() |
| 149 | + .query("channel==" + id, // channel id |
| 150 | + "2012-01-01", // Start date. |
| 151 | + "2012-08-14", // End date. |
| 152 | + "views,subscribersGained,subscribersLost") // Metrics. |
| 153 | + .setDimensions("video") |
| 154 | + .setSort("-views") |
| 155 | + .setMaxResults(10) |
| 156 | + .execute(); |
| 157 | + } |
| 158 | + |
| 159 | + /** |
| 160 | + * Retrieve the demographics report for the channel. |
| 161 | + * |
| 162 | + * @param analytics the analytics service object used to access the API. |
| 163 | + * @param id the string id from which to retrieve data. |
| 164 | + * @return the response from the API. |
| 165 | + * @throws IOException if an API error occurred. |
| 166 | + */ |
| 167 | + private static ResultTable executeDemographicsQuery(YouTubeAnalytics analytics, |
| 168 | + String id) throws IOException { |
| 169 | + return analytics.reports() |
| 170 | + .query("channel==" + id, // channel id |
| 171 | + "2007-01-01", // Start date. |
| 172 | + "2012-08-14", // End date. |
| 173 | + "viewerPercentage") // Metrics. |
| 174 | + .setDimensions("ageGroup,gender") |
| 175 | + .setSort("-viewerPercentage") |
| 176 | + .execute(); |
| 177 | + } |
| 178 | + |
| 179 | + /** |
| 180 | + * Prints the API response. The channel name is printed along with |
| 181 | + * each column name and all the data in the rows. |
| 182 | + * |
| 183 | + * @param writer stream to output to |
| 184 | + * @param title title of the report |
| 185 | + * @param results data returned from the API. |
| 186 | + */ |
| 187 | + private static void printData(PrintStream writer, String title, ResultTable results) { |
| 188 | + writer.println("Report: " + title); |
| 189 | + if (results.getRows() == null || results.getRows().isEmpty()) { |
| 190 | + writer.println("No results Found."); |
| 191 | + } else { |
| 192 | + |
| 193 | + // Print column headers. |
| 194 | + for (ColumnHeaders header : results.getColumnHeaders()) { |
| 195 | + writer.printf("%30s", header.getName()); |
| 196 | + } |
| 197 | + writer.println(); |
| 198 | + |
| 199 | + // Print actual data. |
| 200 | + for (List<Object> row : results.getRows()) { |
| 201 | + for (int colNum = 0; colNum < results.getColumnHeaders().size(); colNum++) { |
| 202 | + ColumnHeaders header = results.getColumnHeaders().get(colNum); |
| 203 | + Object column = row.get(colNum); |
| 204 | + if ("INTEGER".equals(header.getUnknownKeys().get("dataType"))) { |
| 205 | + long l = ((BigDecimal) column).longValue(); |
| 206 | + writer.printf("%30d", l); |
| 207 | + } else if ("FLOAT".equals(header.getUnknownKeys().get("dataType"))) { |
| 208 | + writer.printf("%30f", column); |
| 209 | + } else if ("STRING".equals(header.getUnknownKeys().get("dataType"))) { |
| 210 | + writer.printf("%30s", column); |
| 211 | + } else { |
| 212 | + // default output. |
| 213 | + writer.printf("%30s", column); |
| 214 | + } |
| 215 | + } |
| 216 | + writer.println(); |
| 217 | + } |
| 218 | + writer.println(); |
| 219 | + } |
| 220 | + } |
| 221 | + |
| 222 | +} |
0 commit comments