-
Notifications
You must be signed in to change notification settings - Fork 11
/
fetch.sh
executable file
·63 lines (59 loc) · 1.4 KB
/
fetch.sh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#!/usr/bin/env bash
#
# A script to fetch and save the largest thumbnail image for a book with matching ISBN.
#
set -eu
set -o pipefail
function usage () {
cat <<EOF
Usage: bookcovers-save <isbn>
EOF
}
err() {
echo "[$(date +'%Y-%m-%dT%H:%M:%S%z')]: $@" >&2
}
function main () {
if [[ "$*" =~ ^(-h|--help)$ ]]; then
usage
exit
fi
if [[ "$#" != 1 ]]; then
echo "Expect first arguement to be an ISBN number."
exit 1
fi
ISBN="$1";
WORK_DIR=$(mktemp -d);
trap 'rm -rf "${WORK_DIR}"' EXIT
pushd "$WORK_DIR"
# Download all images associated with isbn number
echo "Finding images for $ISBN";
bookcovers "$ISBN" | awk '{print $3}' | xargs -n 1 curl -L -# -O;
echo "Finding largest image from files downloaded."
local max_resolution=0;
local file='';
for f in * ; do
if [[ "$f" == "*" ]]; then
continue;
fi
local image_data;
local res;
image_data=($(set -e; gm identify -format '%w,%h,%m' "$f" | tr "," "\n"))
if [[ ! "${image_data[2]}" =~ ^(PNG|JPE?G|WEBP)$ ]]; then
continue;
fi
res=$(( image_data[0] * image_data[1] ))
if (( res > max_resolution )); then
max_resolution=${res};
file=${f};
fi
done
popd
if [[ -z "$file" ]]; then
err "No image found!"
exit 1
fi
echo "Saving largest image as JPEG"
gm convert -format jpeg "$WORK_DIR/$file" "$ISBN.jpg"
echo "Saved image to ./$ISBN.jpg"
}
main "$@";