0

youtube analytics api에 요청하려고합니다. 요청을 구성하는 데 문제가있어 허용됩니다. 나는 구글 API를 Node.js를 클라이언트Youtube Analytics - 요청 작성하기

https://github.com/google/google-api-nodejs-client

을 이용하고 있고

import { Meteor } from 'meteor/meteor'; 
import google from 'googleapis'; 
import KEY_FILE from './keyFile.json'; 
import { CHANNEL_ID } from './channelId.js'; 

//api's 
const analytics = google.youtubeAnalytics('v1'); 

//fetch youtube analytics 
export function youtubeAnalytics(start, end){ 
    //initalise request data 
    const startDate = `${start.getFullYear()}-${('0'+(start.getMonth()+1)).slice(-2)}-${('0'+(start.getDate())).slice(-2)}`; 
    const endDate = `${end.getFullYear()}-${('0'+(end.getMonth()+1)).slice(-2)}-${('0'+(end.getDate())).slice(-2)}`; 
    const scopes = [ 
    'https://www.googleapis.com/auth/youtube', 
    'https://www.googleapis.com/auth/youtube.readonly', 
    'https://www.googleapis.com/auth/yt-analytics-monetary.readonly', 
    'https://www.googleapis.com/auth/yt-analytics-monetary.readonly' 
    ]; 

    //generate authorisation token 
    var AUTH = new google.auth.JWT(
    KEY_FILE.client_email, 
    null, 
    KEY_FILE.private_key, 
    scopes, 
    null 
    ); 

    //authorize request 
    AUTH.authorize(function (err, tokens) { 
    if (err) { 
     console.log(err); 
     return; 
    } 

    //create request 
    const analyticsRequest = { 
     auth: AUTH, 
     'start-date': startDate, 
     'end-date': endDate, 
     ids: `channel==${CHANNEL_ID}`, 
     metrics: 'views', 
    }; 

    //make request 
    analytics.reports.query(analyticsRequest, function (err, data) { 
     if (err) { 
     console.error('Error: ' + err); 
     return false; 
     } 
     if (data) { 
     console.log(data); 
     return data; 
     } 
    }); 
    }); 
    return false; 
} 

Meteor.methods({youtubeAnalytics}); 

를 다음과 같이 내 코드는 내가

Error: Error: Invalid query. Query did not conform to the expectations. 

내가 그 할 생각 다음과 같은 오류가 계속입니다 내 요청 개체와 함께

const analyticsRequest = { 
    auth: AUTH, 
    'start-date': startDate, 
    'end-date': endDate, 
    ids: `channel==${CHANNEL_ID}`, 
    metrics: 'views', 
}; 

하지만 내가 발견 한 모든 예에서는이 요청 개체가 작동해야한다고 말합니다. 나는 그것을 최대한 단순화했다. 내 원래 요청 (내가 실제로 원하는 하나)은 다음과 같습니다.

const analyticsRequest = { 
    auth: AUTH, 
    'start-date': startDate, 
    'end-date': endDate, 
    ids: `channel==${CHANNEL_ID}`, 
    metrics: 'views', 
    dimensions: 'video', 
    sort: '-views', 
    'max-results': '200' 
} 

그 후 다른 API 끝점을 사용하는 동영상에 대한 모든 관련 정보를 얻기 위해 다른 요청을해야합니다. 요약 그래서

//api's 
const youtube = google.youtube('v3'); 

/* 
    do processing of analytics data to create batchRequest 
    which is a string of comma separated video ids 
*/ 

videoRequest = { 
    auth: AUTH, 
    part: 'id,snippet', 
    id: batchRequest; 
} 

youtubeApiData.search.list(videosRequest, function (err, data) { 
    if (err) { 
     console.error('Error: ' + err); 
     return false; 
    } 
    if (data) { 
     console.log(data); 
     return data; 
    } 
}); 

나는 다양한 구글 API를의 요청을해야하고 (나는 유튜브 분석에서 첫 번째 요청 과거 없어)들이 수용되도록 요청을 형성하는 데 문제가 있어요 .

누군가 나를 올바른 방향으로 안내 할 수 있습니까?

답변

0

알아 냈어. 이 API에 대한 서비스 계정 요청을 수행합니다. 를 통해 내가 설정 계정 확인

https://guide.meteor.com/accounts.html

이 계정을 융합하여 기본 계정에 병합 계정 - 구글 나에게 사용자에게 다음의 OAuth했다 부착 된 액세스 토큰을 제공

https://atmospherejs.com/splendido/accounts-meld

2.0 대신에 전화하십시오. 페이 스북에 대해서도 비슷한 것이 있었습니까?

내가 아직도 가지고있는 한 가지 문제는 '동영상의 보존 유지'섹션이 매우 비효율적이라는 것입니다. 그것은 비디오 당 하나의 전화를합니다. 구글 API에 사용할 수있는 일괄 요청이 있지만 'googleapis'패키지를 사용하여 적절한 예제를 찾는 것 같습니다. 누구든지 크게 감사 할만한 모범이 있다면.

여기가 새로운 코드입니다.

import { Meteor } from 'meteor/meteor'; 
import google from 'googleapis'; 
import { CHANNEL_ID, USER_ID, KEY_FILE, API_KEY, CLIENT_ID, CLIENT_SECRET } from './keys.js'; 

//api's 
const fetchAnalytics = google.youtubeAnalytics('v1'); 
const fetchYoutube = google.youtube('v3'); 
const OAuth2 = google.auth.OAuth2; 

export function youtubeAnalytics(start, end){ 
    //requires login to generate authorisation 
    const user = Meteor.user(); 
    if(user && user.services && user.services.google && user.services.google.accessToken){ 
    //-------------------- general setup -------------------- // 

    //convert async functions to sync functions 
    const fetchYoutubeSync = Meteor.wrapAsync(fetchYoutube.search.list); 
    const fetchAnalyticsSync = Meteor.wrapAsync(fetchAnalytics.reports.query); 

    // set up default values 
    const analytics = {views: [], retention: []}; 
    const videos = []; 

    const startDate = `${start.getFullYear()}-${('0'+(start.getMonth()+1)).slice(-2)}-${('0'+(start.getDate())).slice(-2)}`; 
    const endDate = `${end.getFullYear()}-${('0'+(end.getMonth()+1)).slice(-2)}-${('0'+(end.getDate())).slice(-2)}`; 
    const startDateLong = `${start.getFullYear()}-${('0'+(start.getMonth()+1)).slice(-2)}-${('0'+(start.getDate())).slice(-2)}T00:00:00.0+00:00`; 
    const endDateLong = `${end.getFullYear()}-${('0'+(end.getMonth()+1)).slice(-2)}-${('0'+(end.getDate())).slice(-2)}T00:00:00.0+00:00`; 

    // generate authorisation tokens 
    const oauth2Client = new OAuth2(CLIENT_ID, CLIENT_SECRET,''); 
    oauth2Client.setCredentials({access_token: user.services.google.accessToken}); 
    google.options({ 
     auth: oauth2Client 
    }); 

    //-------------------- fetch videos between dates -------------------- // 

    let fetch = true; 
    let next = ''; 
    while (fetch) { 
     //create video request 
     let videosRequest = { 
     auth: oauth2Client, 
     part: 'id,snippet', 
     type: 'video', 
     channelId: CHANNEL_ID, 
     publishedAfter: startDateLong, 
     publishedBefore: endDateLong, 
     maxResults: 50, 
     pageToken: next, 
     } 
     //make video request 
     let response = fetchYoutubeSync(videosRequest); 
     //store video request 
     videos.push.apply(videos, response.items); 
     //check if more data is available 
     if(response.nextPageToken){ next = response.nextPageToken; } 
     else{ fetch = false;} 
    } 

    //-------------------- create batch request objects -------------------- // 
    if(videos.length > 0){ 
     //process videos 
     let batchRequestViews = ''; 
     let batchRequestRetention = []; 
     let first = true; 
     for(let i = 0; i < videos.length; i += 1){ 
     let id = false; 
     if(videos[i].id.kind === 'youtube#video'){ id = videos[i].id.videoId;} 
     if(id){ 
      //views processing 
      if(first){ first = false; batchRequestViews = id;} 
      else{ batchRequestViews = `${batchRequestViews},${id}`} 
      //retention processing 
      let request = { 
      auth: oauth2Client, 
      'start-date': startDate, 
      'end-date': endDate, 
      ids: `channel==${CHANNEL_ID}`, 
      metrics: 'audienceWatchRatio', 
      dimensions: 'elapsedVideoTimeRatio', 
      filters: `video==${id}` 
      }; 
      batchRequestRetention.push(request); 
     } 
     } 

     //-------------------- fetch views for videos -------------------- // 

     // create views request 
     const analyticsRequestViews = { 
     auth: oauth2Client, 
     'start-date': startDate, 
     'end-date': endDate, 
     ids: `channel==${CHANNEL_ID}`, 
     metrics: 'views', 
     dimensions: 'video', 
     filters: `video==${batchRequestViews}` 
     }; 
     // make and store views request 
     analytics.views = fetchAnalyticsSync(analyticsRequestViews).rows; 

     //-------------------- fetch retention for videos -------------------- // 

     //make retention batch request 
     if(batchRequestRetention && batchRequestRetention.length > 0){ 
     for(let i = 0; i < batchRequestRetention.length; i += 1){ 
      //fetch retention request 
      let request = batchRequestRetention[i]; 
      //make retention request 
      let response = fetchAnalyticsSync(request); 
      //store response 
      analytics.retention.push({id: request.filters.substring(7), response}); 
     } 
     } 

     //-------------------- return results -------------------- // 
     return {videos, analytics}; 
    } 
    } 
    return false; 
} 

Meteor.methods({youtubeAnalytics}); 
관련 문제