Skip to content

Instantly share code, notes, and snippets.

@rc2dev
Last active March 31, 2024 19:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rc2dev/437e122e5554469a35f10fd893381721 to your computer and use it in GitHub Desktop.
Save rc2dev/437e122e5554469a35f10fd893381721 to your computer and use it in GitHub Desktop.
Backup all youtube playlists from a channel into a git repo in json (https://rafaelc.org/posts/backup-your-youtube-playlists-in-json-with-git/).
#!/usr/bin/env bash
#
# Backup all playlists from a channel into a git repo in json.
#
# Dependencies:
# - jq
# - git
# - yt-dlp
#
# Copyright (C) 2021 Rafael Cavalcanti <https://rafaelc.org/dev>
# Licensed under GPLv3
set -euo pipefail
# Be sure to pass your youtube cookies to yt-dlp if
# some of your playlists are private.
###################################################
# COMPLETE THE FOLLOWING INFO
###################################################
readonly yt_user=
readonly dest_dir=
readonly branch="master"
# Use full path as it is run by a systemd unit.
readonly ydl="$HOME/.local/bin/yt-dlp"
###################################################
if [[ ! -d "$dest_dir" ]]; then
echo "Creating destination directory..."
mkdir -p "$dest_dir"
git init -b "$branch" "$dest_dir"
fi
cd "$dest_dir" || exit 1
if [[ ! -d .git ]]; then
echo "Destination directory exists and is not tracked by git."
exit 1
fi
echo "Preparing repository..."
git stash > /dev/null
git checkout "$branch"
echo "Removing last backup jsons..."
git rm -f ./*.json
echo "Backuping youtube playlists..."
# Get list of playlists
pls_json="$($ydl --flat-playlist --dump-json "https://www.youtube.com/user/$yt_user/playlists?view=1&sort=dd&shelf_id=0")"
# Add missing "Watch Later"
pls_json+=' {"url": "https://www.youtube.com/playlist?list=WL", "title": "Watch Later"}'
readarray -t pls_titles < <(jq -r .title <<< "$pls_json")
readarray -t pls_urls < <(jq -r .url <<< "$pls_json")
for i in "${!pls_titles[@]}"; do
pl_title="${pls_titles[$i]}"
pl_url="${pls_urls[$i]}"
$ydl --flat-playlist --dump-json "$pl_url" > "${dest_dir}/${pl_title}.json"
done
echo "Commiting backup..."
git add ./*.json
# Commiting directly will exit with non-zero code if no changes
git diff-index --quiet HEAD || git commit -m "Backup for $(date +%F)"
# Author: Rafael Cavalcanti <https://rafaelc.org/dev>
[Unit]
Description=Backup from yt
After=network.target
OnFailure=status-email@%n.service
[Service]
ExecStart=%h/Documents/Sysadmin/Backups/bin/backup-from-yt
Nice=19
# Author: Rafael Cavalcanti <https://rafaelc.org/dev>
[Unit]
Description=Run backup-from-yt periodically
[Timer]
OnCalendar=weekly
Persistent=true
RandomizedDelaySec=1h
[Install]
WantedBy=timers.target
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment