Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const { google } = require('googleapis');
- const fs = require('fs');
- const readline = require('readline');
- const SCOPES = ['https://www.googleapis.com/auth/youtube.force-ssl'];
- const TOKEN_PATH = 'token.json';
- const CREDENTIALS_PATH = 'client_secrets.json';
- function authenticate() {
- const credentials = JSON.parse(fs.readFileSync(CREDENTIALS_PATH));
- const { client_secret, client_id, redirect_uris } = credentials.installed;
- const oAuth2Client = new google.auth.OAuth2(
- client_id,
- client_secret,
- redirect_uris[0]
- );
- // Check if we have previously stored a token.
- if (fs.existsSync(TOKEN_PATH)) {
- const token = fs.readFileSync(TOKEN_PATH);
- oAuth2Client.setCredentials(JSON.parse(token));
- return oAuth2Client;
- } else {
- return getNewToken(oAuth2Client);
- }
- }
- function getNewToken(oAuth2Client) {
- const authUrl = oAuth2Client.generateAuthUrl({
- access_type: 'offline',
- scope: SCOPES,
- });
- const rl = readline.createInterface({
- input: process.stdin,
- output: process.stdout,
- });
- console.log('Authorize this app by visiting this url:', authUrl);
- return new Promise((resolve, reject) => {
- rl.question('Enter the code from that page here: ', (code) => {
- rl.close();
- oAuth2Client.getToken(code, (err, token) => {
- if (err) {
- reject(err);
- } else {
- oAuth2Client.setCredentials(token);
- fs.writeFileSync(TOKEN_PATH, JSON.stringify(token));
- resolve(oAuth2Client);
- }
- });
- });
- });
- }
- async function getVideoId() {
- const videoUrl = await new Promise((resolve, reject) => {
- const rl = readline.createInterface({
- input: process.stdin,
- output: process.stdout,
- });
- rl.question('Enter YouTube video URL: ', (url) => {
- rl.close();
- resolve(url);
- });
- });
- const url = new URL(videoUrl);
- return url.searchParams.get('v');
- }
- async function getVideoViews(videoId) {
- const auth = await authenticate();
- const youtube = google.youtube({ version: 'v3', auth });
- const response = await youtube.videos.list({
- part: 'statistics',
- id: videoId,
- });
- const views = response.data.items[0].statistics.viewCount;
- return views;
- }
- async function updateVideoTitle(videoId, views) {
- const auth = await authenticate();
- const youtube = google.youtube({ version: 'v3', auth });
- const response = await youtube.videos.update({
- part: 'snippet',
- requestBody: {
- id: videoId,
- snippet: { title: views + ' просмотров' },
- },
- });
- console.log('Video title successfully updated!');
- }
- async function main() {
- const videoId = await getVideoId();
- const views = await getVideoViews(videoId);
- await updateVideoTitle(videoId, views);
- }
- main().catch(console.error);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement