Repository: IonicaBizau/youtube-api Branch: master Commit: fe6dcc379c84 Files: 10 Total size: 20.1 KB Directory structure: gitextract_li_u434c/ ├── .github/ │ └── FUNDING.yml ├── .gitignore ├── CONTRIBUTING.md ├── DOCUMENTATION.md ├── LICENSE ├── README.md ├── example/ │ ├── credentials.json │ └── index.js ├── lib/ │ └── index.js └── package.json ================================================ FILE CONTENTS ================================================ ================================================ FILE: .github/FUNDING.yml ================================================ github: ionicabizau patreon: ionicabizau open_collective: ionicabizau custom: https://www.buymeacoffee.com/h96wwchmy ================================================ FILE: .gitignore ================================================ *.swp *.swo *~ *.log node_modules *.env .DS_Store package-lock.json .bloggify/* ================================================ FILE: CONTRIBUTING.md ================================================ # 🌟 Contributing Want to contribute to this project? Great! Please read these quick steps to streamline the process and avoid unnecessary tasks. ✨ ## 💬 Discuss Changes Start by opening an issue in the repository using the [bug tracker][1]. Describe your proposed contribution or the bug you've found. If relevant, include platform info and screenshots. 🖼️ Wait for feedback before proceeding unless the fix is straightforward, like a typo. 📝 ## 🔧 Fixing Issues Fork the project and create a branch for your fix, naming it `some-great-feature` or `some-issue-fix`. Commit changes while following the [code style][2]. If the project has tests, add one. ✅ If a `package.json` or `bower.json` exists, add yourself to the `contributors` array; create it if it doesn't. 🙌 ```json { "contributors": [ "Your Name (http://your.website)" ] } ``` ## 📬 Creating a Pull Request Open a pull request and reference the initial issue (e.g., *fixes #*). Provide a clear title and consider adding visual aids for clarity. 📊 ## ⏳ Wait for Feedback Your contributions will be reviewed. If feedback is given, update your branch as needed, and the pull request will auto-update. 🔄 ## 🎉 Everyone Is Happy! Your contributions will be merged, and everyone will appreciate your effort! 😄❤️ Thanks! 🤩 [1]: /issues [2]: https://github.com/IonicaBizau/code-style ================================================ FILE: DOCUMENTATION.md ================================================ ## Documentation You can see below the API reference of this module. ### `authenticate(options)` Sets an authentication method to have access to protected resources. #### Params - **Object** `options`: An object containing the authentication information. #### Return - **Object** The authentication object ### `getConfig()` Returns Client configuration object #### Return - **Object** Client configuration object ================================================ FILE: LICENSE ================================================ The MIT License (MIT) Copyright (c) 2013-25 Ionică Bizău (https://ionicabizau.net) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: README.md ================================================ # youtube-api [![Support me on Patreon][badge_patreon]][patreon] [![Buy me a book][badge_amazon]][amazon] [![PayPal][badge_paypal_donate]][paypal-donations] [![Ask me anything](https://img.shields.io/badge/ask%20me-anything-1abc9c.svg)](https://github.com/IonicaBizau/ama) [![Version](https://img.shields.io/npm/v/youtube-api.svg)](https://www.npmjs.com/package/youtube-api) [![Downloads](https://img.shields.io/npm/dt/youtube-api.svg)](https://www.npmjs.com/package/youtube-api) [![Get help on Codementor](https://cdn.codementor.io/badges/get_help_github.svg)](https://www.codementor.io/@johnnyb?utm_source=github&utm_medium=button&utm_term=johnnyb&utm_campaign=github) Buy Me A Coffee > A Node.JS module, which provides an object oriented wrapper for the Youtube v3 API. ## :cloud: Installation ```sh # Using npm npm install --save youtube-api # Using yarn yarn add youtube-api ``` ## :clipboard: Example ```js /** * This script uploads a video (specifically `video.mp4` from the current * directory) to YouTube, * * To run this script you have to create OAuth2 credentials and download them * as JSON and replace the `credentials.json` file. Then install the * dependencies: * * npm i r-json lien opn bug-killer * * Don't forget to run an `npm i` to install the `youtube-api` dependencies. * */ const Youtube = require("youtube-api") , fs = require("fs") , readJson = require("r-json") , Lien = require("lien") , Logger = require("bug-killer") , opn = require("opn") , prettyBytes = require("pretty-bytes") ; // I downloaded the file from OAuth2 -> Download JSON const CREDENTIALS = readJson(`${__dirname}/credentials.json`); // Init lien server let server = new Lien({ host: "localhost" , port: 5000 }); // Authenticate // You can access the Youtube resources via OAuth2 only. // https://developers.google.com/youtube/v3/guides/moving_to_oauth#service_accounts let oauth = Youtube.authenticate({ type: "oauth" , client_id: CREDENTIALS.web.client_id , client_secret: CREDENTIALS.web.client_secret , redirect_url: CREDENTIALS.web.redirect_uris[0] }); opn(oauth.generateAuthUrl({ access_type: "offline" , scope: ["https://www.googleapis.com/auth/youtube.upload"] })); // Handle oauth2 callback server.addPage("/oauth2callback", lien => { Logger.log("Trying to get the token using the following code: " + lien.query.code); oauth.getToken(lien.query.code, (err, tokens) => { if (err) { lien.lien(err, 400); return Logger.log(err); } Logger.log("Got the tokens."); oauth.setCredentials(tokens); lien.end("The video is being uploaded. Check out the logs in the terminal."); var req = Youtube.videos.insert({ resource: { // Video title and description snippet: { title: "Testing YoutTube API NodeJS module" , description: "Test video upload via YouTube API" } // I don't want to spam my subscribers , status: { privacyStatus: "private" } } // This is for the callback function , part: "snippet,status" // Create the readable stream to upload the video , media: { body: fs.createReadStream("video.mp4") } }, (err, data) => { console.log("Done."); process.exit(); }); setInterval(function () { Logger.log(`${prettyBytes(req.req.connection._bytesDispatched)} bytes uploaded.`); }, 250); }); }); ``` ## :question: Get Help There are few ways to get help: 1. Please [post questions on Stack Overflow](https://stackoverflow.com/questions/ask). You can open issues with questions, as long you add a link to your Stack Overflow question. 2. For bug reports and feature requests, open issues. :bug: 3. For direct and quick help, you can [use Codementor](https://www.codementor.io/johnnyb). :rocket: ## :memo: Documentation The [official Youtube documentation](https://developers.google.com/youtube/v3/docs/) is a very useful resource. - [Activities](https://developers.google.com/youtube/v3/docs/activities) - [ChannelBanners](https://developers.google.com/youtube/v3/docs/channelBanners) - [Channels](https://developers.google.com/youtube/v3/docs/channels) - [GuideCategories](https://developers.google.com/youtube/v3/docs/guideCategories) - [PlaylistItems](https://developers.google.com/youtube/v3/docs/playlistItems) - [Playlists](https://developers.google.com/youtube/v3/docs/playlists) - [Search](https://developers.google.com/youtube/v3/docs/search) - [Subscriptions](https://developers.google.com/youtube/v3/docs/subscriptions) - [Thumbnails](https://developers.google.com/youtube/v3/docs/thumbnails) - [VideoCategories](https://developers.google.com/youtube/v3/docs/videoCategories) - [Videos](https://developers.google.com/youtube/v3/docs/videos) If you have any questions, please [ask them on **Stack Overflow**](https://stackoverflow.com/questions/ask) and eventually [open an issue](https://github.com/IonicaBizau/youtube-api/issues/new) and link your question there. ### Authentication #### OAuth (Access Token) ```js Youtube.authenticate({ type: "oauth" , token: "your access token" }); ``` #### OAuth (Refresh Token) ```js Youtube.authenticate({ type: "oauth" , refresh_token: "your refresh token" , client_id: "your client id" , client_secret: "your client secret" , redirect_url: "your refresh url" }); ``` #### Server Key Only for requests that don't require [user authorization](https://developers.google.com/youtube/v3/guides/authentication) (certain list operations) ```js Youtube.authenticate({ type: "key" , key: "your server key" }); ``` ## :yum: How to contribute Have an idea? Found a bug? See [how to contribute][contributing]. ## :sparkling_heart: Support my projects I open-source almost everything I can, and I try to reply to everyone needing help using these projects. Obviously, this takes time. You can integrate and use these projects in your applications *for free*! You can even change the source code and redistribute (even resell it). However, if you get some profit from this or just want to encourage me to continue creating stuff, there are few ways you can do it: - Starring and sharing the projects you like :rocket: - [![Buy me a book][badge_amazon]][amazon]—I love books! I will remember you after years if you buy me one. :grin: :book: - [![PayPal][badge_paypal]][paypal-donations]—You can make one-time donations via PayPal. I'll probably buy a ~~coffee~~ tea. :tea: - [![Support me on Patreon][badge_patreon]][patreon]—Set up a recurring monthly donation and you will get interesting news about what I'm doing (things that I don't share with everyone). - **Bitcoin**—You can send me bitcoins at this address (or scanning the code below): `1P9BRsmazNQcuyTxEqveUsnf5CERdq35V6` ![](https://i.imgur.com/z6OQI95.png) Thanks! :heart: ## :scroll: License [MIT][license] © [Ionică Bizău][website] [license]: /LICENSE [website]: https://ionicabizau.net [contributing]: /CONTRIBUTING.md [docs]: /DOCUMENTATION.md [badge_patreon]: https://ionicabizau.github.io/badges/patreon.svg [badge_amazon]: https://ionicabizau.github.io/badges/amazon.svg [badge_paypal]: https://ionicabizau.github.io/badges/paypal.svg [badge_paypal_donate]: https://ionicabizau.github.io/badges/paypal_donate.svg [patreon]: https://www.patreon.com/ionicabizau [amazon]: http://amzn.eu/hRo9sIZ [paypal-donations]: https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=RVXDDLKKLQRJW ================================================ FILE: example/credentials.json ================================================ { "web": { "client_id": "103..................................hf7bb75o0.apps.googleusercontent.com", "auth_uri": "https://accounts.google.com/o/oauth2/auth", "token_uri": "https://accounts.google.com/o/oauth2/token", "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs", "client_email": "1038................................dhf7bb75o0@developer.gserviceaccount.com", "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/1038...................................7bb75o0%40developer.gserviceaccount.com", "client_secret": "ji.....................w", "redirect_uris": ["http://localhost:5000/oauth2callback"], "javascript_origins": ["http://localhost:5000"] } } ================================================ FILE: example/index.js ================================================ "use strict"; /** * This script uploads a video (specifically `video.mp4` from the current * directory) to YouTube, * * To run this script you have to create OAuth2 credentials and download them * as JSON and replace the `credentials.json` file. Then install the * dependencies: * * npm i r-json lien opn bug-killer * * Don't forget to run an `npm i` to install the `youtube-api` dependencies. * */ const Youtube = require("../lib") , fs = require("fs") , readJson = require("r-json") , Lien = require("lien") , Logger = require("bug-killer") , opn = require("opn") , prettyBytes = require("pretty-bytes") ; // I downloaded the file from OAuth2 -> Download JSON const CREDENTIALS = readJson(`${__dirname}/credentials.json`); // Init lien server let server = new Lien({ host: "localhost" , port: 5000 }); // Authenticate // You can access the Youtube resources via OAuth2 only. // https://developers.google.com/youtube/v3/guides/moving_to_oauth#service_accounts let oauth = Youtube.authenticate({ type: "oauth" , client_id: CREDENTIALS.web.client_id , client_secret: CREDENTIALS.web.client_secret , redirect_url: CREDENTIALS.web.redirect_uris[0] }); opn(oauth.generateAuthUrl({ access_type: "offline" , scope: ["https://www.googleapis.com/auth/youtube.upload"] })); // Handle oauth2 callback server.addPage("/oauth2callback", lien => { Logger.log("Trying to get the token using the following code: " + lien.query.code); oauth.getToken(lien.query.code, (err, tokens) => { if (err) { lien.lien(err, 400); return Logger.log(err); } Logger.log("Got the tokens."); oauth.setCredentials(tokens); lien.end("The video is being uploaded. Check out the logs in the terminal."); var req = Youtube.videos.insert({ resource: { // Video title and description snippet: { title: "Testing YoutTube API NodeJS module" , description: "Test video upload via YouTube API" } // I don't want to spam my subscribers , status: { privacyStatus: "private" } } // This is for the callback function , part: "snippet,status" // Create the readable stream to upload the video , media: { body: fs.createReadStream("video.mp4") } }, (err, data) => { console.log("Done."); process.exit(); }); setInterval(function () { Logger.log(`${prettyBytes(req.req.connection._bytesDispatched)} bytes uploaded.`); }, 250); }); }); ================================================ FILE: lib/index.js ================================================ // Dependencies var Google = require("googleapis").google; // Create YoutTube client var Client = module.exports = function(config) {}; (function() { var config = {}; /** * authenticate * Sets an authentication method to have access to protected resources. * * @name authenticate * @function * @param {Object} options An object containing the authentication information. * @return {Object} The authentication object */ this.authenticate = function (options) { if (!options) { config.auth = undefined; return; } var authObj = null; switch (options.type) { case "oauth": authObj = new Google.auth.OAuth2(options.client_id, options.client_secret, options.redirect_url); authObj.setCredentials({ access_token: options.access_token || options.token , refresh_token: options.refresh_token }); break; case "key": authObj = options.key; break; } Google.options({ auth: authObj }); config.auth = options; return authObj; }; /** * getConfig * Returns Client configuration object * * @name getConfig * @function * @return {Object} Client configuration object */ this.getConfig = function () { return config; }; // Add Google YouTube API functions var GoogleYoutube = Google.youtube("v3"); for (var f in GoogleYoutube) { this[f] = GoogleYoutube[f]; } }).call(Client); ================================================ FILE: package.json ================================================ { "name": "youtube-api", "version": "3.0.2", "description": "A Node.JS module, which provides an object oriented wrapper for the Youtube v3 API.", "main": "lib/index.js", "author": "Ionică Bizău (https://ionicabizau.net)", "contributors": [ "Ionică Bizău ", "Adam (brutalhonesty)", "Michael Scharl ", "Vels (velsa)", "Rasmus Karlsson ", "Brad Oyler " ], "repository": { "type": "git", "url": "git://github.com/IonicaBizau/youtube-api.git" }, "keywords": [ "youtube", "api", "v3", "node" ], "license": "MIT", "bugs": { "url": "https://github.com/IonicaBizau/youtube-api/issues" }, "dependencies": { "googleapis": "^54.1.0" }, "homepage": "https://github.com/IonicaBizau/youtube-api", "directories": { "example": "example" }, "devDependencies": { "bug-killer": "^4.2.2", "lien": "^3.3.0", "opn": "^6.0.0", "pretty-bytes": "^5.3.0", "r-json": "^1.2.2" }, "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "blah": { "show_jsdocs": false, "documentation": [ "The [official Youtube documentation](https://developers.google.com/youtube/v3/docs/) is a very useful resource.", { "ul": [ "[Activities](https://developers.google.com/youtube/v3/docs/activities)", "[ChannelBanners](https://developers.google.com/youtube/v3/docs/channelBanners)", "[Channels](https://developers.google.com/youtube/v3/docs/channels)", "[GuideCategories](https://developers.google.com/youtube/v3/docs/guideCategories)", "[PlaylistItems](https://developers.google.com/youtube/v3/docs/playlistItems)", "[Playlists](https://developers.google.com/youtube/v3/docs/playlists)", "[Search](https://developers.google.com/youtube/v3/docs/search)", "[Subscriptions](https://developers.google.com/youtube/v3/docs/subscriptions)", "[Thumbnails](https://developers.google.com/youtube/v3/docs/thumbnails)", "[VideoCategories](https://developers.google.com/youtube/v3/docs/videoCategories)", "[Videos](https://developers.google.com/youtube/v3/docs/videos)" ] }, "If you have any questions, please [ask them on **Stack Overflow**](https://stackoverflow.com/questions/ask) and eventually [open an issue](https://github.com/IonicaBizau/youtube-api/issues/new) and link your question there.", "", { "h3": "Authentication" }, "", { "h4": "OAuth (Access Token)" }, { "code": { "language": "js", "content": [ "Youtube.authenticate({", " type: \"oauth\"", " , token: \"your access token\"", "});" ] } }, { "h4": "OAuth (Refresh Token)" }, { "code": { "language": "js", "content": [ "Youtube.authenticate({", " type: \"oauth\"", " , refresh_token: \"your refresh token\"", " , client_id: \"your client id\"", " , client_secret: \"your client secret\"", " , redirect_url: \"your refresh url\"", "});" ] } }, { "h4": "Server Key" }, "Only for requests that don't require [user authorization](https://developers.google.com/youtube/v3/guides/authentication) (certain list operations)", { "code": { "language": "js", "content": [ "Youtube.authenticate({", " type: \"key\"", " , key: \"your server key\"", "});" ] } } ] }, "files": [ "bin/", "app/", "lib/", "dist/", "src/", "scripts/", "resources/", "menu/", "cli.js", "index.js", "index.d.ts", "package-lock.json", "bloggify.js", "bloggify.json", "bloggify/" ] }