set -eu
fetch() (
##
# The movie/show details page has a link like the following that starts the
# player:
START=${1} # http://olevod.com/index.php/vod/play/id/62435/sid/1/nid/1.html
TITLE=${2}
END=${1%.html}
END=$(printf "%02d" "${END##*/}") #number of the episode/movie/etc.
mkdir "${END}"
cd "${END}"
##
# That fetches an m3u file, which can be fetched from that file.
STAGE1=$(mktemp)
wget --no-check-certificate "${START}" -O "${STAGE1}"
##
# STAGE1 now contains the page source, inside that is an m3u8 link to the
# playlist.
echo "content placed in STAGE1: ${STAGE1}" >&1
STANZA=$(grep -Eo '"url":"https:.*master.m3u8"' "${STAGE1}")
PLAYLIST=$(jq -r .url <<< "{${STANZA}}")
STAGE2=$(mktemp)
echo "fetching stage 2 (first playlist) STAGE2: ${STAGE2}"
wget --no-check-certificate "${PLAYLIST}" -O "${STAGE2}"
##
# STAGE2 (the first m3u file) now contains a relative link to the real
# playlist.
# Create a new link from the file in there and the current path.
echo "constructing path to playlist..."
REL_PATH_TO_PLAYLIST=$(grep -o '.*m3u8$' "${STAGE2}" | cut -f2 -d")
BASE=${PLAYLIST%/*}
echo "base: ${BASE}"
FULL_PATH="${BASE}/${REL_PATH_TO_PLAYLIST}"
STAGE3=$(mktemp)
echo "Fetching first playlist from ${FULL_PATH} and placing it in ${STAGE3}"
wget --no-check-certificate "${FULL_PATH}" -O "${STAGE3}"
##
# Stage 3 now contains the real playlist full of relative links.
# Build a new link for each entry in the file.
while read -r REL ; do
wget --no-check-certificate "${BASE}/$REL"
done < <(grep -Eo '.*ts$' "${STAGE3}")
##
# Now they're fetched, combine them into one ts file with ffmpeg.
#
find . -type f -name '*.ts' | cut -f2 -d- | grep -v '[A-Za-z]' | sort -h | xargs --replace=REP echo file 'seg-REP-v1-a1.ts' > inputs
ffmpeg -f concat -i inputs -c copy output.ts
ffmpeg -i output.ts -acodec copy -vcodec copy output.mp4
mv output.mp4 ../"${TITLE}${END}.mp4"
rm output.ts
)
STEM=${1%/*}
START=${1##*/}
START=${START%.html}
STOP=${4:-999}
for ((i=START;i<STOP;i++)); do
if fetch "${STEM}/${i}.html" "${2}" ; then
echo "Fetched $i…" >&2
else
echo "No $i, ${2} possibly done." >&2
break
##
# FIXME: need error handling to resume on hiccups.
fi
done