320x100
320x100
const fs = require('fs');
const readline = require('readline');
const { google } = require('googleapis');

const { OAuth2 } = google.auth;

// If modifying these scopes, delete your previously saved credentials
// at ~/.credentials/youtube-nodejs-quickstart.json
const SCOPES = ['https://www.googleapis.com/auth/youtube.readonly'];
const TOKEN_DIR = `${
  process.env.HOME || process.env.HOMEPATH || process.env.USERPROFILE
}/.credentials/`;
const TOKEN_PATH = `${TOKEN_DIR}youtube-nodejs-quickstart.json`;

/**
 * Store token to disk be used in later program executions.
 *
 * @param {Object} token The token to store to disk.
 */
function storeToken(token) {
  try {
    fs.mkdirSync(TOKEN_DIR);
  } catch (err) {
    if (err.code !== 'EEXIST') {
      throw err;
    }
  }
  fs.writeFile(TOKEN_PATH, JSON.stringify(token), (err) => {
    if (err) throw err;
    console.log('Token stored to ', TOKEN_PATH);
  });
}

/**
 * Lists the names and IDs of up to 10 files.
 *
 * @param {google.auth.OAuth2} auth An authorized OAuth2 client.
 */
function getChannel(auth) {
  const service = google.youtube('v3');
  service.channels.list(
    {
      auth,
      part: 'snippet,contentDetails,statistics',
      forUsername: 'GoogleDevelopers',
    },
    (err, response) => {
      if (err) {
        console.log('The API returned an error: ', err);
        return;
      }
      const channels = response.data.items;
      if (channels.length === 0) {
        console.log('No channel found.');
      } else {
        console.log(
          "This channel's ID is %s. Its title is %s, and it has %s views.",
          channels[0].id,
          channels[0].snippet.title,
          channels[0].statistics.viewCount,
        );
      }
    },
  );
}

/**
 * Get and store new token after prompting for user authorization, and then
 * execute the given callback with the authorized OAuth2 client.
 *
 * @param {google.auth.OAuth2} oauth2Client The OAuth2 client to get token for.
 * @param {getEventsCallback} callback The callback to call with the authorized
 *     client.
 */
function getNewToken(oauth2Client, callback) {
  const oauth2Client1 = oauth2Client;
  const authUrl = oauth2Client.generateAuthUrl({
    access_type: 'offline',
    scope: SCOPES,
  });
  console.log('Authorize this app by visiting this url: ', authUrl);
  const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
  });
  rl.question('Enter the code from that page here: ', (code) => {
    rl.close();
    oauth2Client.getToken(code, (err, token) => {
      if (err) {
        console.log('Error while trying to retrieve access token', err);
        return;
      }
      oauth2Client1.credentials = token;
      storeToken(token);
      callback(oauth2Client);
    });
  });
}

/**
 * Create an OAuth2 client with the given credentials, and then execute the
 * given callback function.
 *
 * @param {Object} credentials The authorization client credentials.
 * @param {function} callback The callback to call with the authorized client.
 */
function authorize(credentials, callback) {
  const clientSecret = credentials.installed.client_secret;
  const clientId = credentials.installed.client_id;
  const redirectUrl = credentials.installed.redirect_uris[0];
  const oauth2Client = new OAuth2(clientId, clientSecret, redirectUrl);

  // Check if we have previously stored a token.
  fs.readFile(TOKEN_PATH, (err, token) => {
    if (err) {
      getNewToken(oauth2Client, callback);
    } else {
      oauth2Client.credentials = JSON.parse(token);
      callback(oauth2Client);
    }
  });
}

// Load client secrets from a local file.
fs.readFile('client_secret.json', (err, content) => {
  if (err) {
    console.log('Error loading client secret file: ', err);
    return;
  }
  // Authorize a client with the loaded credentials, then call the YouTube API.
  authorize(JSON.parse(content), getChannel);
});

: Youtube Data API v3의 공식문서에 나온 quick start 소스코드를 AirBnb ESLint에 맞게 수정하였다.

: 위 코드를 실행하면 client_secret.json 파일이 없다고 나오는데, 공식문서를 참고하여 만들고 

  파일을 알맞은 경로에 놓도록 하자

 

- Client_secret 토큰 생성하기

: https://developers.google.com/youtube/registering_an_application

 

인증 자격증명 가져오기  |  YouTube Data API  |  Google Developers

인증 자격증명 가져오기 YouTube Data API을(를) 사용하려면 애플리케이션에 인증 자격증명 정보가 포함되어 있어야 합니다. 이 문서에서는 Google API Console 콘솔이 지원하는 다양한 인증 자격증명

developers.google.com

 

 

※ Youtube Data API v3 공식문서

: https://developers.google.com/youtube/v3/quickstart/nodejs

 

Node.js Quickstart  |  YouTube Data API  |  Google Developers

Node.js Quickstart Complete the steps described in the rest of this page, and in about five minutes you'll have a simple Node.js command-line application that makes requests to the YouTube Data API. The sample code used in this guide retrieves the channel

developers.google.com

 

 

 

 

 

 

300x250
728x90