엄민용

Youtube API Sample for Project

const { google } = require("googleapis");
var http = require('http');
var opn = require('opn');
var destroyer = require('destroyer');
var url = require('url');
var enableDestroy = require('server-destroy');
const oauth2Client = new google.auth.OAuth2(
"394965702516-q817fn2gj8r8sqoudhp29k1rd71ku42j.apps.googleusercontent.com",
"xgo5tcTwsmg2alNumeY1Drj_",
"http://localhost:3031/api/oauth2callback"
);
const scopes = [
'https://www.googleapis.com/auth/youtube',
'https://www.googleapis.com/auth/youtube.force-ssl',
'https://www.googleapis.com/auth/youtube.readonly',
'https://www.googleapis.com/auth/youtubepartner'
];
let refreshToken = '';
async function authenticate() {
return new Promise((resolve, reject) => {
if (refreshToken !== "") {
oauth2Client.setCredentials({
refresh_token: refreshToken
});
oauth2Client.getAccessToken((err, ttoken) => {
if (err) {
reject(e);
}
resolve(oauth2Client);
});
} else {
const authorizeUrl = oauth2Client.generateAuthUrl({
access_type: 'offline',
scope: scopes.join(' '),
});
const server = http.createServer(async (req, res) => {
try {
if (req.url.indexOf('/api/oauth2callback') > -1) {
const qs = new url.URL(req.url, 'http://localhost:3031').searchParams;
res.end('Completed');
enableDestroy(server);
server.destroy();
const {
tokens
} = await oauth2Client.getToken(qs.get('code'));
refreshToken = tokens.refresh_token;
oauth2Client.credentials = tokens;
resolve(oauth2Client);
}
} catch (e) {
reject(e);
}
}).listen(3031, () => {
opn(authorizeUrl, {
wait: false
}).then(cp => cp.unref());
});
destroyer(server);
}
});
}
module.exports.refreshClient=authenticate;
\ No newline at end of file
var {google} =require('googleapis');
var service = google.youtube('v3');
const oauth2Service = require('./oauth2');
function getPlaylistData(oauth2Client, channelId) {
service.playlists.list({
auth: oauth2Client,
part: 'id, snippet',
fields: 'items(id, snippet(title, description, thumbnails(default(url))))',
channelId: channelId
}, function(err, response) {
if(err) {
console.log('The API returned an error: ' + err);
return;
}
var channels = response.data.items;
if (channels.length == 0){
console.log('No channel found.')
} else {
console.log(JSON.stringify(channels, null, 4));
}
});
}
oauth2Service.refreshClient()
.then((client) => {
getPlaylistData(client, 'UCx6jsZ02B4K3SECUrkgPyzg');
})
.catch(console.error);
\ No newline at end of file