dotfiles/scripts/.local/bin/vidl
Marty Oehme 9f1fe95662
scripts: Added vidl and archive scripts
Added script for downloading videos with ytdl or any of its derivatives.
The script is adapted from one in my rapberry pi setup which serves
videos remotely, and makes some hardcoded assumptions that might not be
the best for all situations.

Added archive script which takes a file and puts a hardlink to it into
an arbitrary archival folder. This means even if the original file is
deleted its data stays on disk because of its hardlinked archive
version.
2021-12-06 10:47:17 +01:00

106 lines
2.6 KiB
Bash
Executable file

#!/usr/bin/env bash
# download a file if it does not exist in the archive alread
# otherwise just re-link it from the archive
DL_FOLDER="${DL_FOLDER:-${XDG_VIDEOS_DIR:-$HOME/videos}}/inbox"
ARCHIVE_FOLDER="${ARCHIVE_FOLDER:-${XDG_VIDEOS_DIR:-$HOME/videos}}/archive"
YT_DL_CMD="${YT_DL_CMD:-yt-dlp}"
YT_DL_TITLE="""${YT_DL_TITLE:-%(channel)s_%(title)s_%(id)s}"""
show_help() {
printf """
archive.sh: Hard linking your stuff.
vidl: Video downloader
Simple wrapper for youtube-dl (or yt-dlp or similar).
Usage: vidl [OPTION] <link>
Point it to a link you want downloaded.
Options:
-h Display this help.
-d Directory to check for existence of file and archive to if needed.
-f Directory to download to.
-t Point to youtube-dl command to use. Can be command or absolute link.
By default will use \`yt-dlp\` which is a more up to date fork of the
program.
"""
}
while getopts "t:f:d:h" opt; do
case "$opt" in
# v) verbose=1
# ;;
f)
DL_FOLDER="$OPTARG"
;;
t)
YT_DL_CMD="$OPTARG"
;;
d)
ARCHIVE_FOLDER="$OPTARG"
;;
h | \? | *)
show_help
exit 0
;;
esac
done
shift $((OPTIND - 1))
_call_archive() {
command -v archive >/dev/null 2>&1 || {
echo "archive command not found."
exit 1
}
archive -d "$2" -a "$1"
}
vid_ext="\(mp4\|avi\|webm\|mkv\|mpe?g\|3gp\|m4a\)"
_findfile() {
dir="$1"
fname="$2"
find "$dir" -type f -name "$fname.*" | sed -ne "/$fname\.$vid_ext$/Ip"
}
YT_DL_TITLE="%(channel)s_%(title)s_%(id)s"
_download() {
"$YT_DL_CMD" \
-f 'best[height<=1080]' \
-o "$DL_FOLDER/$YT_DL_TITLE.%(ext)s" \
--write-sub --write-auto-sub --embed-subs --sub-lang en,de,es,fr \
--retries 15 \
"$url"
}
url="$*"
dl_fn=$("$YT_DL_CMD" --get-filename -o "$YT_DL_TITLE" "$url")
video_file_regex="${dl_fn}"
if [ -z "$dl_fn" ]; then
echo Could not get video filename, error with youtube-dl.
exit 1
fi
alreadyexists=$(_findfile "$ARCHIVE_FOLDER" "$video_file_regex")
# # download the video to download folder
if [ "$alreadyexists" = "" ] || [ -z "$alreadyexists" ]; then
_download
# yt-dl never knows the exact filename in advance
file=$(_findfile "$DL_FOLDER" "$video_file_regex")
if [ -z "$file" ]; then exit 1; fi
_call_archive "$file" "$ARCHIVE_FOLDER"
# only link old file if one exists
else
echo "$alreadyexists" | while read -r file; do
echo "file $file exists, not downloading duplicate"
_call_archive "$file" "$DL_FOLDER"
done
fi