Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Backup all youtube playlists from a channel into a git repo in json.
#!/usr/bin/env bash
#
# Backup all youtube playlists from a channel into a git repo in json.
#
# Dependencies:
# - jq
# - git
# - youtube-dl
#
# Copyright (C) 2021 Rafael Cavalcanti - rafaelc.org
# Licensed under GPLv3 Author: Rafael Cavalcanti - rafaelc.org
set -euo pipefail
# Be sure to pass your youtube cookies to youtube-dl 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/youtube-dl"
###################################################
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 - rafaelc.org
[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 - rafaelc.org
[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