diff --git a/README.md b/README.md index 7555e45..6583c53 100644 --- a/README.md +++ b/README.md @@ -79,6 +79,7 @@ will create the symbolic link for each script in the \ directory. - [bor](scripts/bor) displays the latest posts from [bash.im](https://bash.im) website. - [ibor](scripts/ibor) displays the latest posts from [ibash.im](https://ibash.im) website. +- [libgen](scripts/libgen) looks for books in the Library Genesis. - [vandroucli](scripts/vandroucli) retrieves the newest posts from the vandrouki websites ([ru](https://vandrouki.ru), [by](https://vandrouki.by), [asia](https://vandrouki.asia)). ## System diff --git a/scripts/libgen b/scripts/libgen new file mode 100755 index 0000000..208256b --- /dev/null +++ b/scripts/libgen @@ -0,0 +1,82 @@ +#!/usr/bin/env bash + +# +# A tiny script to look for books in the Library Genesis. +# + +set -e +set -o errtrace +trap stacktrace ERR + +\unalias -a + +IFS=$' \t\n' + +function stacktrace () { + [ -n "$TRACED" ] && return + + local depth=${#FUNCNAME[@]} + + for ((i=1; i < "$depth"; i++)); do + printf '%*scall at %s:%s: %s()\n' "$i" '' \ + "${BASH_SOURCE[$i]}" \ + "${BASH_LINENO[$((i-1))]}" \ + "${FUNCNAME[$i]}" + done + + TRACED=true +} + +libgen_search() { + curl -sq "${LIBGEN_SEARCH_URL}?&req=${1}&phrase=0&view=simple&column=def&sort=id&sortmode=DESC" +} + +libgen_get_books_info() { + curl -sq "${LIBGEN_API_URL}?ids=${1}&fields=title,author,year,language,extension,md5" +} + +# ------------------------------------------------------------------------------ + +if [ -z "$1" ]; then + echo "USAGE: $(basename "$0") [query]" >&2 + exit 1 +fi + +QUERY="$1" + +LIBGEN_MIRROR="https://libgen.is" +LIBGEN_API_URL="${LIBGEN_MIRROR}/json.php" +LIBGEN_SEARCH_URL="${LIBGEN_MIRROR}/search.php" +LIBGEN_BOOK_URL="${LIBGEN_MIRROR}/book/index.php" + +rstc="\033[00m" +magenta="\033[0;35m" +yellow="\033[1;33m" +blue="\033[1;34m" +green="\033[1;32m" + +# ------------------------------------------------------------------------------ + +IFS=$' ' read -r -a RAW_IDS <<<"$(libgen_search "$QUERY" | 2>&- xmllint --html --xpath "//@id[. > 0]" -)" + +IDS_LIST=() +for raw_id in "${RAW_IDS[@]}"; do + eval "$raw_id" + + # shellcheck disable=SC2154 + IDS_LIST+=("$id") +done + +IDS=$(IFS=, ; echo "${IDS_LIST[*]}") + +BOOKS="$(jq -r 'reverse | .[] | .author+"@"+.title+"@"+.extension+"@"+.year+"@"+.language+"@"+.md5' <<<"$(libgen_get_books_info "$IDS")")" + +i=1 +while IFS=$'@' read -r -a book; do + printf "%02d. ${green}%s${rstc}\n" "$i" "${book[1]}" + printf " ${yellow}%s${rstc}, ${magenta}%s [%s]${rstc}\n" "${book[0]}" "${book[3]}" "${book[2]}" + printf " ${blue}%s${rstc}\n\n" "${LIBGEN_BOOK_URL}?md5=${book[5]}" + + ((i++)) +done <<<"$BOOKS" +