Full Code of IonicaBizau/youtube-api for AI

master fe6dcc379c84 cached
10 files
20.1 KB
5.2k tokens
1 symbols
1 requests
Download .txt
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 <your@email.address> (http://your.website)"
   ]
}
```

## 📬 Creating a Pull Request
Open a pull request and reference the initial issue (e.g., *fixes #<your-issue-number>*). 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 <bizauionica@gmail.com> (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
================================================
<!-- Please do not edit this file. Edit the `blah` field in the `package.json` instead. If in doubt, open an issue. -->


















# 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)

<a href="https://www.buymeacoffee.com/H96WwChMy" target="_blank"><img src="https://www.buymeacoffee.com/assets/img/custom_images/yellow_img.png" alt="Buy Me A Coffee"></a>







> 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 <bizauionica@gmail.com> (https://ionicabizau.net)",
  "contributors": [
    "Ionică Bizău <bizauionica@gmail.com>",
    "Adam <aaschodd@asu.edu> (brutalhonesty)",
    "Michael Scharl <developeme@gmail.com>",
    "Vels <velshome@yahoo.com> (velsa)",
    "Rasmus Karlsson <pajlada@bithack.se>",
    "Brad Oyler <bradoyler@gmail.com>"
  ],
  "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/"
  ]
}
Download .txt
gitextract_li_u434c/

├── .github/
│   └── FUNDING.yml
├── .gitignore
├── CONTRIBUTING.md
├── DOCUMENTATION.md
├── LICENSE
├── README.md
├── example/
│   ├── credentials.json
│   └── index.js
├── lib/
│   └── index.js
└── package.json
Download .txt
SYMBOL INDEX (1 symbols across 1 files)

FILE: example/index.js
  constant CREDENTIALS (line 26) | const CREDENTIALS = readJson(`${__dirname}/credentials.json`);
Condensed preview — 10 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (22K chars).
[
  {
    "path": ".github/FUNDING.yml",
    "chars": 116,
    "preview": "github: ionicabizau\npatreon: ionicabizau\nopen_collective: ionicabizau\ncustom: https://www.buymeacoffee.com/h96wwchmy"
  },
  {
    "path": ".gitignore",
    "chars": 80,
    "preview": "*.swp\n*.swo\n*~\n*.log\nnode_modules\n*.env\n.DS_Store\npackage-lock.json\n.bloggify/*\n"
  },
  {
    "path": "CONTRIBUTING.md",
    "chars": 1396,
    "preview": "# 🌟 Contributing\n\nWant to contribute to this project? Great! Please read these quick steps to streamline the process and"
  },
  {
    "path": "DOCUMENTATION.md",
    "chars": 421,
    "preview": "## Documentation\n\nYou can see below the API reference of this module.\n\n### `authenticate(options)`\nSets an authenticatio"
  },
  {
    "path": "LICENSE",
    "chars": 1132,
    "preview": "The MIT License (MIT)\n\nCopyright (c) 2013-25 Ionică Bizău <bizauionica@gmail.com> (https://ionicabizau.net)\n\nPermission "
  },
  {
    "path": "README.md",
    "chars": 8140,
    "preview": "<!-- Please do not edit this file. Edit the `blah` field in the `package.json` instead. If in doubt, open an issue. -->\n"
  },
  {
    "path": "example/credentials.json",
    "chars": 782,
    "preview": "{\n    \"web\": {\n        \"client_id\": \"103..................................hf7bb75o0.apps.googleusercontent.com\",\n       "
  },
  {
    "path": "example/index.js",
    "chars": 2759,
    "preview": "\"use strict\";\n\n/**\n * This script uploads a video (specifically `video.mp4` from the current\n * directory) to YouTube,\n "
  },
  {
    "path": "lib/index.js",
    "chars": 1644,
    "preview": "// Dependencies\nvar Google = require(\"googleapis\").google;\n\n// Create YoutTube client\nvar Client = module.exports = func"
  },
  {
    "path": "package.json",
    "chars": 4148,
    "preview": "{\n  \"name\": \"youtube-api\",\n  \"version\": \"3.0.2\",\n  \"description\": \"A Node.JS module, which provides an object oriented w"
  }
]

About this extraction

This page contains the full source code of the IonicaBizau/youtube-api GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 10 files (20.1 KB), approximately 5.2k tokens, and a symbol index with 1 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!