youtubeuploader

repository·master·Indexed 21 days ago

https://github.com/porjo/youtubeuploader

A command-line utility for scripted YouTube video uploads. It supports uploading files from local disks, URLs, or stdin, and allows managing video metadata via CLI flags or JSON files. Features include bandwidth rate-limiting, playlist management, and support for OAuth2 authentication via the YouTube Data API v3.

Tokens
6.3K
Snippets
16
Records
24
Agent score
71%

What's inside youtubeuploader

  1. Configure video metadata using JSON

    master

    You can specify video metadata (title, description, tags, etc.) using the -metaJSON flag. Values provided in the JSON file take precedence over command-line flags.

    Key Details:

    • All fields are optional.
    • Use \n in the description for newlines.
    • Time formats: yyyy-mm-dd (UTC) or yyyy-mm-ddThh:mm:ss+zz:zz.
    • If a URL is provided as a filename, data is streamed through localhost (downloaded from remote, then uploaded to YouTube).
    {
          "title": "my test title",
          "description": "my test description",
          "tags": [
                "test tag1",
                "test tag2"
          ],
          "privacyStatus": "private",
          "madeForKids": false,
          "embeddable": true,
          "license": "creativeCommon",
          "publicStatsViewable": true,
          "publishAt": "2017-06-01T12:05:00+02:00",
          "categoryId": "10",
          "recordingDate": "2017-05-21",
          "playlistIds": [
                "xxxxxxxxxxxxxxxxxx",
                "yyyyyyyyyyyyyyyyyy"
          ],
          "playlistTitles": [
                "my test playlist"
          ],
          "language": "fr",
          "localizations": {
                "en": {
                      "title": "My English Title",
                      "description": "My English description"
                },
                "it": {
                      "title": "Il mio titolo in italiano",
                      "description": "La mia descrizione in italiano"
                }
          },
          "containsSyntheticMedia": false
    }
  2. Run youtubeuploader for the first time

    master

    When running the utility for the first time, a browser window will open to prompt for YouTube credentials. Upon successful authentication, a token file named request.token will be created in the local directory.

    For headless servers, run the utility locally first to generate the request.token file, then copy both request.token and client_secrets.json to the remote server along with the binary.

    ./youtubeuploader -filename blob.mp4
  3. Setup YouTube API authentication

    master

    To use youtubeuploader, you must configure OAuth2 authentication via the Google Developers Console.

    1. Create a project in the Google Developers Console.
    2. Enable the YouTube Data API v3.
    3. Configure an OAuth consent screen and add your YouTube account as a Test user.
    4. Create Credentials using the OAuth client ID type and select Web application.
    5. Set the Authorized redirect URI to http://localhost:8080/oauth2callback.
    6. Download the client secrets JSON file and save it as client_secrets.json in the same directory as the youtubeuploader binary.

    Important Limitations:

    • Privacy: Videos uploaded from unverified API projects are restricted to private status by default.
    • Quota: Google imposes a quota that typically limits uploads to approximately 6 videos every 24 hours.
    {
      "web": {
        "client_id": "xxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com",
        "project_id": "youtubeuploader-yyyyy",
        "auth_uri": "https://accounts.google.com/o/oauth2/auth",
        "token_uri": "https://oauth2.googleapis.com/token",
        "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
        "client_secret": "xxxxxxxxxxxxxxxxxxxx",
        "redirect_uris": [
          "http://localhost:8080/oauth2callback"
        ]
      }
    }
  4. Implement a custom Token Cache

    master

    The Cache interface allows you to provide your own mechanism for storing and retrieving OAuth2 tokens. This is useful if you want to store tokens in a database, a secure vault, or a different file structure instead of the default CacheFile implementation.

    To implement the interface, provide methods for Token() and PutToken(*oauth2.Token).

    type Cache interface {
    	Token() (*oauth2.Token, error)
    	PutToken(*oauth2.Token) error
    }
  5. Configure upload rate limiting

    master

    You can control the upload bandwidth using the -ratelimit and -limitBetween flags:

    • -ratelimit <Kbps>: Sets a hard limit on the upload speed in Kilobits per second.
    • -limitBetween <HH:MM-HH:MM>: Restricts the rate limiting to a specific time window in your local time zone. For example, -limitBetween 10:00-14:00 will only apply the rate limit during those hours.

    Example: To limit uploads to 500 Kbps only between 10:00 AM and 2:00 PM:

    youtubeuploader -filename "video.mp4" -ratelimit 500 -limitBetween 10:00-14:00
  6. Manage video metadata via JSON

    master

    Instead of passing many individual flags, you can provide a JSON file containing the video metadata using the -metaJSON flag. This file can include fields such as title, description, and tags.

    Additionally, you can use the -metaJSONout flag to specify a filename where the tool will write the metadata of the successfully uploaded video.

  7. Use the youtubeuploader CLI to upload videos

    master

    The youtubeuploader CLI tool allows you to upload video files to YouTube with customizable metadata, rate limiting, and playlist management.

    To use the tool, you must provide a video filename. If no title is provided, the tool defaults to using the filename (without the extension) as the video title.

    Basic usage requires the -filename flag. You can also provide metadata like -title, -description, -tags, and -privacy (e.g., private, public, unlisted).

    youtubeuploader -filename "my_video.mp4" -title "My Awesome Video" -description "Check this out!" -privacy "public"
  8. Manage upload progress and quiet mode

    master

    Use the -quiet flag to suppress the progress indicator. If you are running in quiet mode and need to see the current progress, you can send the USR1 signal to the process (Linux/Unix only).

    Example to view progress:

    kill -USR1 <pid>
  9. Configure the Run function via Config

    master

    The Run function relies on a Config struct to define the upload behavior. While the full struct definition is in another file, the following fields are explicitly used in Run to control the process:

    • Filename (string): The name of the video file. Use "-" to indicate uploading from a pipe. This field is mandatory.
    • Thumbnail (string): Path to the thumbnail image file. If provided, it is uploaded after the video.
    • Caption (string): Path to the caption file. If provided, it is uploaded after the video.
    • Language (string): The language code used for captions.
    • Quiet (bool): If true, progress reporting is suppressed.
    • OAuthPort (int): The port used for the OAuth2 flow.
    • Chunksize (int64): The size of chunks used for the media upload.
    • NotifySubscribers (bool): Whether to notify subscribers of the new video.
    • SendFileName (bool): If true and Filename is not "-", the filename is added to the request header as a Slug.
    • MetaJSONOut (string): If provided, the resulting YouTube video metadata is written to this file path as JSON.
  10. Reference: youtubeuploader CLI flags

    master

    The following flags are available for controlling the upload process:

    Usage:
      -cache string
            token cache file (default "request.token")
      -caption string
            caption filename. Can be a URL
      -categoryId string
            video category Id
      -chunksize int
            size (in bytes) of each upload chunk. A zero value will cause all data to be uploaded in a single request (default 16777216)
      -debug
            turn on verbose log output
      -description string
            video description (default "uploaded by youtubeuploader")
      -filename string
            video filename. Can be a URL. Read from stdin with '-'
      -language string
            video language (default "en")
      -limitBetween string
            only rate limit between these times e.g. 10:00-14:00 (local time zone)
      -metaJSON string
            JSON file containing title,description,tags etc (optional)
      -metaJSONout string
            filename to write uploaded video metadata into (optional)
      -notify
            notify channel subscribers of new video. Specify '-notify=false' to disable. (default true)
      -oAuthPort int
            TCP port to listen on when requesting an oAuth token (default 8080)
      -playlistID value
            playlistID to add the video to. Can be used multiple times
      -privacy string
            video privacy status (default "private")
      -quiet
            suppress progress indicator
      -ratelimit int
            rate limit upload in Kbps. No limit by default
      -recordingDate value
            recording date e.g. 2024-11-23
      -secrets string
            Client Secrets configuration (default "client_secrets.json")
      -sendFilename
            send original file name to YouTube (default true)
      -tags string
            comma separated list of video tags
      -thumbnail string
            thumbnail filename. Can be a URL
      -title string
            video title
      -version
            show version
  11. Load video metadata with LoadVideoMeta

    master

    The LoadVideoMeta function prepares the data required for a YouTube upload. It takes a Config object and returns two objects: a *VideoMeta (internal metadata) and a *youtube.Video (the actual object used by the Google YouTube API).

    Behavior Logic:

    1. JSON Priority: If config.MetaJSON is provided, it reads and unmarshals that file into VideoMeta. This metadata takes precedence for fields like Title, Description, Tags, CategoryId, and Localizations.
    2. Config Fallback: If fields are not set in the JSON, the function falls back to the values provided in the Config struct.
    3. YouTube API Mapping: It maps the metadata to the specific structure required by the google.golang.org/api/youtube/v3 package, including setting ForceSendFields for SelfDeclaredMadeForKids and ContainsSyntheticMedia to ensure explicit values are sent to YouTube.
    4. Playlist Merging: It combines PlaylistIDs from both the Config and the VideoMeta JSON, sorts them, and removes duplicates.
    videoMeta, youtubeVideo, err := youtubeuploader.LoadVideoMeta(config)