Created
April 22, 2023 09:43
-
-
Save md-redwan-hossain/6d3dba52fa63d3cd2d657e70df8ecb6d to your computer and use it in GitHub Desktop.
calculate total duration of a youtube playlist by Javascript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"use strict"; | |
// dependencies | |
// npm install axios moment prompt dotenv | |
const axios = require("axios"); | |
const moment = require("moment"); | |
const prompt = require("prompt"); | |
require("dotenv").config(); | |
// configuration | |
const key = process.env.YOUTUBE_API_KEY; | |
const videoApiString = `https://www.googleapis.com/youtube/v3/videos?part=contentDetails&key=${key}`; | |
const playlistApiString = `https://youtube.googleapis.com/youtube/v3/playlistItems?part=contentDetails&maxResults=50&key=${key}`; | |
// variables | |
const videoIdFromPlaylist = []; | |
const videoIdPromiseArr = []; | |
const secondsArr = []; | |
// functions | |
function timeConverter(totalSeconds) { | |
const hours = Math.trunc(totalSeconds / 3600); | |
const minutes = Math.trunc((totalSeconds - 3600 * hours) / 60); | |
const seconds = Math.trunc(totalSeconds - 3600 * hours - minutes * 60); | |
return [hours, minutes, seconds]; | |
} | |
async function fetchDatafromYtApi(url) { | |
try { | |
const response = await axios.get(url); | |
for (const video of response.data.items) { | |
videoIdFromPlaylist.push(video.contentDetails.videoId); | |
} | |
if (!response.data.nextPageToken) return; | |
return await fetchDatafromYtApi(url.concat(`&pageToken=${response.data.nextPageToken}`)); | |
} catch (error) { | |
console.error(error); | |
} | |
} | |
function fetchVideoInfo() { | |
videoIdFromPlaylist.forEach((videoId) => { | |
const promiseResult = axios.get(videoApiString.concat(`&id=${videoId}`)); | |
videoIdPromiseArr.push(promiseResult); | |
}); | |
Promise.all(videoIdPromiseArr).then((resolvedValues) => { | |
resolvedValues.forEach((elem) => { | |
const rawTime = elem.data.items[0].contentDetails.duration; | |
secondsArr.push(moment.duration(rawTime).asSeconds()); | |
}); | |
const totalSeconds = secondsArr.reduce((acc, elem) => acc + elem, 0); | |
const [hours, minutes, seconds] = timeConverter(totalSeconds); | |
console.log(`${hours}h:${minutes}m:${seconds}s`); | |
}); | |
} | |
function promtCallback(err, result) { | |
const playlistID = result.playlistURL.split("=")[1]; | |
if (!playlistID) return; | |
fetchDatafromYtApi(playlistApiString.concat(`&playlistId=${playlistID}`)).then(fetchVideoInfo); | |
} | |
prompt.start(); | |
prompt.get(["playlistURL"], promtCallback); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment